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
17#include "clang/Basic/DiagnosticIDs.h"
18#include "clang/Basic/DiagnosticOptions.h"
19#include "clang/Basic/SourceLocation.h"
20#include "clang/Basic/Specifiers.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/IntrusiveRefCntPtr.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringRef.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 <string>
35#include <type_traits>
36#include <utility>
37#include <vector>
38
39namespace clang {
40
41class DeclContext;
42class DiagnosticBuilder;
43class DiagnosticConsumer;
44class IdentifierInfo;
45class LangOptions;
46class Preprocessor;
47class SourceManager;
48class StoredDiagnostic;
49
50namespace tok {
51
52enum TokenKind : unsigned short;
53
54} // namespace tok
55
56/// Annotates a diagnostic with some code that should be
57/// inserted, removed, or replaced to fix the problem.
58///
59/// This kind of hint should be used when we are certain that the
60/// introduction, removal, or modification of a particular (small!)
61/// amount of code will correct a compilation error. The compiler
62/// should also provide full recovery from such errors, such that
63/// suppressing the diagnostic output can still result in successful
64/// compilation.
65class FixItHint {
66public:
67 /// Code that should be replaced to correct the error. Empty for an
68 /// insertion hint.
69 CharSourceRange RemoveRange;
70
71 /// Code in the specific range that should be inserted in the insertion
72 /// location.
73 CharSourceRange InsertFromRange;
74
75 /// The actual code to insert at the insertion location, as a
76 /// string.
77 std::string CodeToInsert;
78
79 bool BeforePreviousInsertions = false;
80
81 /// Empty code modification hint, indicating that no code
82 /// modification is known.
83 FixItHint() = default;
84
85 bool isNull() const {
86 return !RemoveRange.isValid();
87 }
88
89 /// Create a code modification hint that inserts the given
90 /// code string at a specific location.
91 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
92 StringRef Code,
93 bool BeforePreviousInsertions = false) {
94 FixItHint Hint;
95 Hint.RemoveRange =
96 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
97 Hint.CodeToInsert = Code;
98 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
99 return Hint;
100 }
101
102 /// Create a code modification hint that inserts the given
103 /// code from \p FromRange at a specific location.
104 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc,
105 CharSourceRange FromRange,
106 bool BeforePreviousInsertions = false) {
107 FixItHint Hint;
108 Hint.RemoveRange =
109 CharSourceRange::getCharRange(InsertionLoc, InsertionLoc);
110 Hint.InsertFromRange = FromRange;
111 Hint.BeforePreviousInsertions = BeforePreviousInsertions;
112 return Hint;
113 }
114
115 /// Create a code modification hint that removes the given
116 /// source range.
117 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
118 FixItHint Hint;
119 Hint.RemoveRange = RemoveRange;
120 return Hint;
121 }
122 static FixItHint CreateRemoval(SourceRange RemoveRange) {
123 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
124 }
125
126 /// Create a code modification hint that replaces the given
127 /// source range with the given code string.
128 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
129 StringRef Code) {
130 FixItHint Hint;
131 Hint.RemoveRange = RemoveRange;
132 Hint.CodeToInsert = Code;
133 return Hint;
134 }
135
136 static FixItHint CreateReplacement(SourceRange RemoveRange,
137 StringRef Code) {
138 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
139 }
140};
141
142/// Concrete class used by the front-end to report problems and issues.
143///
144/// This massages the diagnostics (e.g. handling things like "report warnings
145/// as errors" and passes them off to the DiagnosticConsumer for reporting to
146/// the user. DiagnosticsEngine is tied to one translation unit and one
147/// SourceManager.
148class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> {
149public:
150 /// The level of the diagnostic, after it has been through mapping.
151 enum Level {
152 Ignored = DiagnosticIDs::Ignored,
153 Note = DiagnosticIDs::Note,
154 Remark = DiagnosticIDs::Remark,
155 Warning = DiagnosticIDs::Warning,
156 Error = DiagnosticIDs::Error,
157 Fatal = DiagnosticIDs::Fatal
158 };
159
160 enum ArgumentKind {
161 /// std::string
162 ak_std_string,
163
164 /// const char *
165 ak_c_string,
166
167 /// int
168 ak_sint,
169
170 /// unsigned
171 ak_uint,
172
173 /// enum TokenKind : unsigned
174 ak_tokenkind,
175
176 /// IdentifierInfo
177 ak_identifierinfo,
178
179 /// Qualifiers
180 ak_qual,
181
182 /// QualType
183 ak_qualtype,
184
185 /// DeclarationName
186 ak_declarationname,
187
188 /// NamedDecl *
189 ak_nameddecl,
190
191 /// NestedNameSpecifier *
192 ak_nestednamespec,
193
194 /// DeclContext *
195 ak_declcontext,
196
197 /// pair<QualType, QualType>
198 ak_qualtype_pair,
199
200 /// Attr *
201 ak_attr
202 };
203
204 /// Represents on argument value, which is a union discriminated
205 /// by ArgumentKind, with a value.
206 using ArgumentValue = std::pair<ArgumentKind, intptr_t>;
207
208private:
209 // Used by __extension__
210 unsigned char AllExtensionsSilenced = 0;
211
212 // Suppress diagnostics after a fatal error?
213 bool SuppressAfterFatalError = true;
214
215 // Suppress all diagnostics.
216 bool SuppressAllDiagnostics = false;
217
218 // Elide common types of templates.
219 bool ElideType = true;
220
221 // Print a tree when comparing templates.
222 bool PrintTemplateTree = false;
223
224 // Color printing is enabled.
225 bool ShowColors = false;
226
227 // Which overload candidates to show.
228 OverloadsShown ShowOverloads = Ovl_All;
229
230 // Cap of # errors emitted, 0 -> no limit.
231 unsigned ErrorLimit = 0;
232
233 // Cap on depth of template backtrace stack, 0 -> no limit.
234 unsigned TemplateBacktraceLimit = 0;
235
236 // Cap on depth of constexpr evaluation backtrace stack, 0 -> no limit.
237 unsigned ConstexprBacktraceLimit = 0;
238
239 IntrusiveRefCntPtr<DiagnosticIDs> Diags;
240 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts;
241 DiagnosticConsumer *Client = nullptr;
242 std::unique_ptr<DiagnosticConsumer> Owner;
243 SourceManager *SourceMgr = nullptr;
244
245 /// Mapping information for diagnostics.
246 ///
247 /// Mapping info is packed into four bits per diagnostic. The low three
248 /// bits are the mapping (an instance of diag::Severity), or zero if unset.
249 /// The high bit is set when the mapping was established as a user mapping.
250 /// If the high bit is clear, then the low bits are set to the default
251 /// value, and should be mapped with -pedantic, -Werror, etc.
252 ///
253 /// A new DiagState is created and kept around when diagnostic pragmas modify
254 /// the state so that we know what is the diagnostic state at any given
255 /// source location.
256 class DiagState {
257 llvm::DenseMap<unsigned, DiagnosticMapping> DiagMap;
258
259 public:
260 // "Global" configuration state that can actually vary between modules.
261
262 // Ignore all warnings: -w
263 unsigned IgnoreAllWarnings : 1;
264
265 // Enable all warnings.
266 unsigned EnableAllWarnings : 1;
267
268 // Treat warnings like errors.
269 unsigned WarningsAsErrors : 1;
270
271 // Treat errors like fatal errors.
272 unsigned ErrorsAsFatal : 1;
273
274 // Suppress warnings in system headers.
275 unsigned SuppressSystemWarnings : 1;
276
277 // Map extensions to warnings or errors?
278 diag::Severity ExtBehavior = diag::Severity::Ignored;
279
280 DiagState()
281 : IgnoreAllWarnings(false), EnableAllWarnings(false),
282 WarningsAsErrors(false), ErrorsAsFatal(false),
283 SuppressSystemWarnings(false) {}
284
285 using iterator = llvm::DenseMap<unsigned, DiagnosticMapping>::iterator;
286 using const_iterator =
287 llvm::DenseMap<unsigned, DiagnosticMapping>::const_iterator;
288
289 void setMapping(diag::kind Diag, DiagnosticMapping Info) {
290 DiagMap[Diag] = Info;
291 }
292
293 DiagnosticMapping lookupMapping(diag::kind Diag) const {
294 return DiagMap.lookup(Diag);
295 }
296
297 DiagnosticMapping &getOrAddMapping(diag::kind Diag);
298
299 const_iterator begin() const { return DiagMap.begin(); }
300 const_iterator end() const { return DiagMap.end(); }
301 };
302
303 /// Keeps and automatically disposes all DiagStates that we create.
304 std::list<DiagState> DiagStates;
305
306 /// A mapping from files to the diagnostic states for those files. Lazily
307 /// built on demand for files in which the diagnostic state has not changed.
308 class DiagStateMap {
309 public:
310 /// Add an initial diagnostic state.
311 void appendFirst(DiagState *State);
312
313 /// Add a new latest state point.
314 void append(SourceManager &SrcMgr, SourceLocation Loc, DiagState *State);
315
316 /// Look up the diagnostic state at a given source location.
317 DiagState *lookup(SourceManager &SrcMgr, SourceLocation Loc) const;
318
319 /// Determine whether this map is empty.
320 bool empty() const { return Files.empty(); }
321
322 /// Clear out this map.
323 void clear() {
324 Files.clear();
325 FirstDiagState = CurDiagState = nullptr;
326 CurDiagStateLoc = SourceLocation();
327 }
328
329 /// Produce a debugging dump of the diagnostic state.
330 LLVM_DUMP_METHOD void dump(SourceManager &SrcMgr,
331 StringRef DiagName = StringRef()) const;
332
333 /// Grab the most-recently-added state point.
334 DiagState *getCurDiagState() const { return CurDiagState; }
335
336 /// Get the location at which a diagnostic state was last added.
337 SourceLocation getCurDiagStateLoc() const { return CurDiagStateLoc; }
338
339 private:
340 friend class ASTReader;
341 friend class ASTWriter;
342
343 /// Represents a point in source where the diagnostic state was
344 /// modified because of a pragma.
345 ///
346 /// 'Loc' can be null if the point represents the diagnostic state
347 /// modifications done through the command-line.
348 struct DiagStatePoint {
349 DiagState *State;
350 unsigned Offset;
351
352 DiagStatePoint(DiagState *State, unsigned Offset)
353 : State(State), Offset(Offset) {}
354 };
355
356 /// Description of the diagnostic states and state transitions for a
357 /// particular FileID.
358 struct File {
359 /// The diagnostic state for the parent file. This is strictly redundant,
360 /// as looking up the DecomposedIncludedLoc for the FileID in the Files
361 /// map would give us this, but we cache it here for performance.
362 File *Parent = nullptr;
363
364 /// The offset of this file within its parent.
365 unsigned ParentOffset = 0;
366
367 /// Whether this file has any local (not imported from an AST file)
368 /// diagnostic state transitions.
369 bool HasLocalTransitions = false;
370
371 /// The points within the file where the state changes. There will always
372 /// be at least one of these (the state on entry to the file).
373 llvm::SmallVector<DiagStatePoint, 4> StateTransitions;
374
375 DiagState *lookup(unsigned Offset) const;
376 };
377
378 /// The diagnostic states for each file.
379 mutable std::map<FileID, File> Files;
380
381 /// The initial diagnostic state.
382 DiagState *FirstDiagState;
383
384 /// The current diagnostic state.
385 DiagState *CurDiagState;
386
387 /// The location at which the current diagnostic state was established.
388 SourceLocation CurDiagStateLoc;
389
390 /// Get the diagnostic state information for a file.
391 File *getFile(SourceManager &SrcMgr, FileID ID) const;
392 };
393
394 DiagStateMap DiagStatesByLoc;
395
396 /// Keeps the DiagState that was active during each diagnostic 'push'
397 /// so we can get back at it when we 'pop'.
398 std::vector<DiagState *> DiagStateOnPushStack;
399
400 DiagState *GetCurDiagState() const {
401 return DiagStatesByLoc.getCurDiagState();
402 }
403
404 void PushDiagStatePoint(DiagState *State, SourceLocation L);
405
406 /// Finds the DiagStatePoint that contains the diagnostic state of
407 /// the given source location.
408 DiagState *GetDiagStateForLoc(SourceLocation Loc) const {
409 return SourceMgr ? DiagStatesByLoc.lookup(*SourceMgr, Loc)
410 : DiagStatesByLoc.getCurDiagState();
411 }
412
413 /// Sticky flag set to \c true when an error is emitted.
414 bool ErrorOccurred;
415
416 /// Sticky flag set to \c true when an "uncompilable error" occurs.
417 /// I.e. an error that was not upgraded from a warning by -Werror.
418 bool UncompilableErrorOccurred;
419
420 /// Sticky flag set to \c true when a fatal error is emitted.
421 bool FatalErrorOccurred;
422
423 /// Indicates that an unrecoverable error has occurred.
424 bool UnrecoverableErrorOccurred;
425
426 /// Counts for DiagnosticErrorTrap to check whether an error occurred
427 /// during a parsing section, e.g. during parsing a function.
428 unsigned TrapNumErrorsOccurred;
429 unsigned TrapNumUnrecoverableErrorsOccurred;
430
431 /// The level of the last diagnostic emitted.
432 ///
433 /// This is used to emit continuation diagnostics with the same level as the
434 /// diagnostic that they follow.
435 DiagnosticIDs::Level LastDiagLevel;
436
437 /// Number of warnings reported
438 unsigned NumWarnings;
439
440 /// Number of errors reported
441 unsigned NumErrors;
442
443 /// A function pointer that converts an opaque diagnostic
444 /// argument to a strings.
445 ///
446 /// This takes the modifiers and argument that was present in the diagnostic.
447 ///
448 /// The PrevArgs array indicates the previous arguments formatted for this
449 /// diagnostic. Implementations of this function can use this information to
450 /// avoid redundancy across arguments.
451 ///
452 /// This is a hack to avoid a layering violation between libbasic and libsema.
453 using ArgToStringFnTy = void (*)(
454 ArgumentKind Kind, intptr_t Val,
455 StringRef Modifier, StringRef Argument,
456 ArrayRef<ArgumentValue> PrevArgs,
457 SmallVectorImpl<char> &Output,
458 void *Cookie,
459 ArrayRef<intptr_t> QualTypeVals);
460
461 void *ArgToStringCookie = nullptr;
462 ArgToStringFnTy ArgToStringFn;
463
464 /// ID of the "delayed" diagnostic, which is a (typically
465 /// fatal) diagnostic that had to be delayed because it was found
466 /// while emitting another diagnostic.
467 unsigned DelayedDiagID;
468
469 /// First string argument for the delayed diagnostic.
470 std::string DelayedDiagArg1;
471
472 /// Second string argument for the delayed diagnostic.
473 std::string DelayedDiagArg2;
474
475 /// Optional flag value.
476 ///
477 /// Some flags accept values, for instance: -Wframe-larger-than=<value> and
478 /// -Rpass=<value>. The content of this string is emitted after the flag name
479 /// and '='.
480 std::string FlagValue;
481
482public:
483 explicit DiagnosticsEngine(IntrusiveRefCntPtr<DiagnosticIDs> Diags,
484 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts,
485 DiagnosticConsumer *client = nullptr,
486 bool ShouldOwnClient = true);
487 DiagnosticsEngine(const DiagnosticsEngine &) = delete;
488 DiagnosticsEngine &operator=(const DiagnosticsEngine &) = delete;
489 ~DiagnosticsEngine();
490
491 LLVM_DUMP_METHOD void dump() const;
492 LLVM_DUMP_METHOD void dump(StringRef DiagName) const;
493
494 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
495 return Diags;
496 }
497
498 /// Retrieve the diagnostic options.
499 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; }
500
501 using diag_mapping_range = llvm::iterator_range<DiagState::const_iterator>;
502
503 /// Get the current set of diagnostic mappings.
504 diag_mapping_range getDiagnosticMappings() const {
505 const DiagState &DS = *GetCurDiagState();
506 return diag_mapping_range(DS.begin(), DS.end());
507 }
508
509 DiagnosticConsumer *getClient() { return Client; }
510 const DiagnosticConsumer *getClient() const { return Client; }
511
512 /// Determine whether this \c DiagnosticsEngine object own its client.
513 bool ownsClient() const { return Owner != nullptr; }
514
515 /// Return the current diagnostic client along with ownership of that
516 /// client.
517 std::unique_ptr<DiagnosticConsumer> takeClient() { return std::move(Owner); }
518
519 bool hasSourceManager() const { return SourceMgr != nullptr; }
520
521 SourceManager &getSourceManager() const {
522 assert(SourceMgr && "SourceManager not set!");
523 return *SourceMgr;
524 }
525
526 void setSourceManager(SourceManager *SrcMgr) {
527 assert(DiagStatesByLoc.empty() &&
528 "Leftover diag state from a different SourceManager.");
529 SourceMgr = SrcMgr;
530 }
531
532 //===--------------------------------------------------------------------===//
533 // DiagnosticsEngine characterization methods, used by a client to customize
534 // how diagnostics are emitted.
535 //
536
537 /// Copies the current DiagMappings and pushes the new copy
538 /// onto the top of the stack.
539 void pushMappings(SourceLocation Loc);
540
541 /// Pops the current DiagMappings off the top of the stack,
542 /// causing the new top of the stack to be the active mappings.
543 ///
544 /// \returns \c true if the pop happens, \c false if there is only one
545 /// DiagMapping on the stack.
546 bool popMappings(SourceLocation Loc);
547
548 /// Set the diagnostic client associated with this diagnostic object.
549 ///
550 /// \param ShouldOwnClient true if the diagnostic object should take
551 /// ownership of \c client.
552 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true);
553
554 /// Specify a limit for the number of errors we should
555 /// emit before giving up.
556 ///
557 /// Zero disables the limit.
558 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
559
560 /// Specify the maximum number of template instantiation
561 /// notes to emit along with a given diagnostic.
562 void setTemplateBacktraceLimit(unsigned Limit) {
563 TemplateBacktraceLimit = Limit;
564 }
565
566 /// Retrieve the maximum number of template instantiation
567 /// notes to emit along with a given diagnostic.
568 unsigned getTemplateBacktraceLimit() const {
569 return TemplateBacktraceLimit;
570 }
571
572 /// Specify the maximum number of constexpr evaluation
573 /// notes to emit along with a given diagnostic.
574 void setConstexprBacktraceLimit(unsigned Limit) {
575 ConstexprBacktraceLimit = Limit;
576 }
577
578 /// Retrieve the maximum number of constexpr evaluation
579 /// notes to emit along with a given diagnostic.
580 unsigned getConstexprBacktraceLimit() const {
581 return ConstexprBacktraceLimit;
582 }
583
584 /// When set to true, any unmapped warnings are ignored.
585 ///
586 /// If this and WarningsAsErrors are both set, then this one wins.
587 void setIgnoreAllWarnings(bool Val) {
588 GetCurDiagState()->IgnoreAllWarnings = Val;
589 }
590 bool getIgnoreAllWarnings() const {
591 return GetCurDiagState()->IgnoreAllWarnings;
592 }
593
594 /// When set to true, any unmapped ignored warnings are no longer
595 /// ignored.
596 ///
597 /// If this and IgnoreAllWarnings are both set, then that one wins.
598 void setEnableAllWarnings(bool Val) {
599 GetCurDiagState()->EnableAllWarnings = Val;
600 }
601 bool getEnableAllWarnings() const {
602 return GetCurDiagState()->EnableAllWarnings;
603 }
604
605 /// When set to true, any warnings reported are issued as errors.
606 void setWarningsAsErrors(bool Val) {
607 GetCurDiagState()->WarningsAsErrors = Val;
608 }
609 bool getWarningsAsErrors() const {
610 return GetCurDiagState()->WarningsAsErrors;
611 }
612
613 /// When set to true, any error reported is made a fatal error.
614 void setErrorsAsFatal(bool Val) { GetCurDiagState()->ErrorsAsFatal = Val; }
615 bool getErrorsAsFatal() const { return GetCurDiagState()->ErrorsAsFatal; }
616
617 /// When set to true (the default), suppress further diagnostics after
618 /// a fatal error.
619 void setSuppressAfterFatalError(bool Val) { SuppressAfterFatalError = Val; }
620
621 /// When set to true mask warnings that come from system headers.
622 void setSuppressSystemWarnings(bool Val) {
623 GetCurDiagState()->SuppressSystemWarnings = Val;
624 }
625 bool getSuppressSystemWarnings() const {
626 return GetCurDiagState()->SuppressSystemWarnings;
627 }
628
629 /// Suppress all diagnostics, to silence the front end when we
630 /// know that we don't want any more diagnostics to be passed along to the
631 /// client
632 void setSuppressAllDiagnostics(bool Val = true) {
633 SuppressAllDiagnostics = Val;
634 }
635 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
636
637 /// Set type eliding, to skip outputting same types occurring in
638 /// template types.
639 void setElideType(bool Val = true) { ElideType = Val; }
640 bool getElideType() { return ElideType; }
641
642 /// Set tree printing, to outputting the template difference in a
643 /// tree format.
644 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; }
645 bool getPrintTemplateTree() { return PrintTemplateTree; }
646
647 /// Set color printing, so the type diffing will inject color markers
648 /// into the output.
649 void setShowColors(bool Val = false) { ShowColors = Val; }
650 bool getShowColors() { return ShowColors; }
651
652 /// Specify which overload candidates to show when overload resolution
653 /// fails.
654 ///
655 /// By default, we show all candidates.
656 void setShowOverloads(OverloadsShown Val) {
657 ShowOverloads = Val;
658 }
659 OverloadsShown getShowOverloads() const { return ShowOverloads; }
660
661 /// Pretend that the last diagnostic issued was ignored, so any
662 /// subsequent notes will be suppressed, or restore a prior ignoring
663 /// state after ignoring some diagnostics and their notes, possibly in
664 /// the middle of another diagnostic.
665 ///
666 /// This can be used by clients who suppress diagnostics themselves.
667 void setLastDiagnosticIgnored(bool Ignored = true) {
668 if (LastDiagLevel == DiagnosticIDs::Fatal)
669 FatalErrorOccurred = true;
670 LastDiagLevel = Ignored ? DiagnosticIDs::Ignored : DiagnosticIDs::Warning;
671 }
672
673 /// Determine whether the previous diagnostic was ignored. This can
674 /// be used by clients that want to determine whether notes attached to a
675 /// diagnostic will be suppressed.
676 bool isLastDiagnosticIgnored() const {
677 return LastDiagLevel == DiagnosticIDs::Ignored;
678 }
679
680 /// Controls whether otherwise-unmapped extension diagnostics are
681 /// mapped onto ignore/warning/error.
682 ///
683 /// This corresponds to the GCC -pedantic and -pedantic-errors option.
684 void setExtensionHandlingBehavior(diag::Severity H) {
685 GetCurDiagState()->ExtBehavior = H;
686 }
687 diag::Severity getExtensionHandlingBehavior() const {
688 return GetCurDiagState()->ExtBehavior;
689 }
690
691 /// Counter bumped when an __extension__ block is/ encountered.
692 ///
693 /// When non-zero, all extension diagnostics are entirely silenced, no
694 /// matter how they are mapped.
695 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
696 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
697 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
698
699 /// This allows the client to specify that certain warnings are
700 /// ignored.
701 ///
702 /// Notes can never be mapped, errors can only be mapped to fatal, and
703 /// WARNINGs and EXTENSIONs can be mapped arbitrarily.
704 ///
705 /// \param Loc The source location that this change of diagnostic state should
706 /// take affect. It can be null if we are setting the latest state.
707 void setSeverity(diag::kind Diag, diag::Severity Map, SourceLocation Loc);
708
709 /// Change an entire diagnostic group (e.g. "unknown-pragmas") to
710 /// have the specified mapping.
711 ///
712 /// \returns true (and ignores the request) if "Group" was unknown, false
713 /// otherwise.
714 ///
715 /// \param Flavor The flavor of group to affect. -Rfoo does not affect the
716 /// state of the -Wfoo group and vice versa.
717 ///
718 /// \param Loc The source location that this change of diagnostic state should
719 /// take affect. It can be null if we are setting the state from command-line.
720 bool setSeverityForGroup(diag::Flavor Flavor, StringRef Group,
721 diag::Severity Map,
722 SourceLocation Loc = SourceLocation());
723
724 /// Set the warning-as-error flag for the given diagnostic group.
725 ///
726 /// This function always only operates on the current diagnostic state.
727 ///
728 /// \returns True if the given group is unknown, false otherwise.
729 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled);
730
731 /// Set the error-as-fatal flag for the given diagnostic group.
732 ///
733 /// This function always only operates on the current diagnostic state.
734 ///
735 /// \returns True if the given group is unknown, false otherwise.
736 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled);
737
738 /// Add the specified mapping to all diagnostics of the specified
739 /// flavor.
740 ///
741 /// Mainly to be used by -Wno-everything to disable all warnings but allow
742 /// subsequent -W options to enable specific warnings.
743 void setSeverityForAll(diag::Flavor Flavor, diag::Severity Map,
744 SourceLocation Loc = SourceLocation());
745
746 bool hasErrorOccurred() const { return ErrorOccurred; }
747
748 /// Errors that actually prevent compilation, not those that are
749 /// upgraded from a warning by -Werror.
750 bool hasUncompilableErrorOccurred() const {
751 return UncompilableErrorOccurred;
752 }
753 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
754
755 /// Determine whether any kind of unrecoverable error has occurred.
756 bool hasUnrecoverableErrorOccurred() const {
757 return FatalErrorOccurred || UnrecoverableErrorOccurred;
758 }
759
760 unsigned getNumWarnings() const { return NumWarnings; }
761
762 void setNumWarnings(unsigned NumWarnings) {
763 this->NumWarnings = NumWarnings;
764 }
765
766 /// Return an ID for a diagnostic with the specified format string and
767 /// level.
768 ///
769 /// If this is the first request for this diagnostic, it is registered and
770 /// created, otherwise the existing ID is returned.
771 ///
772 /// \param FormatString A fixed diagnostic format string that will be hashed
773 /// and mapped to a unique DiagID.
774 template <unsigned N>
775 unsigned getCustomDiagID(Level L, const char (&FormatString)[N]) {
776 return Diags->getCustomDiagID((DiagnosticIDs::Level)L,
777 StringRef(FormatString, N - 1));
778 }
779
780 /// Converts a diagnostic argument (as an intptr_t) into the string
781 /// that represents it.
782 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
783 StringRef Modifier, StringRef Argument,
784 ArrayRef<ArgumentValue> PrevArgs,
785 SmallVectorImpl<char> &Output,
786 ArrayRef<intptr_t> QualTypeVals) const {
787 ArgToStringFn(Kind, Val, Modifier, Argument, PrevArgs, Output,
788 ArgToStringCookie, QualTypeVals);
789 }
790
791 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
792 ArgToStringFn = Fn;
793 ArgToStringCookie = Cookie;
794 }
795
796 /// Note that the prior diagnostic was emitted by some other
797 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic.
798 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) {
799 LastDiagLevel = Other.LastDiagLevel;
800 }
801
802 /// Reset the state of the diagnostic object to its initial
803 /// configuration.
804 void Reset();
805
806 //===--------------------------------------------------------------------===//
807 // DiagnosticsEngine classification and reporting interfaces.
808 //
809
810 /// Determine whether the diagnostic is known to be ignored.
811 ///
812 /// This can be used to opportunistically avoid expensive checks when it's
813 /// known for certain that the diagnostic has been suppressed at the
814 /// specified location \p Loc.
815 ///
816 /// \param Loc The source location we are interested in finding out the
817 /// diagnostic state. Can be null in order to query the latest state.
818 bool isIgnored(unsigned DiagID, SourceLocation Loc) const {
819 return Diags->getDiagnosticSeverity(DiagID, Loc, *this) ==
820 diag::Severity::Ignored;
821 }
822
823 /// Based on the way the client configured the DiagnosticsEngine
824 /// object, classify the specified diagnostic ID into a Level, consumable by
825 /// the DiagnosticConsumer.
826 ///
827 /// To preserve invariant assumptions, this function should not be used to
828 /// influence parse or semantic analysis actions. Instead consider using
829 /// \c isIgnored().
830 ///
831 /// \param Loc The source location we are interested in finding out the
832 /// diagnostic state. Can be null in order to query the latest state.
833 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const {
834 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this);
835 }
836
837 /// Issue the message to the client.
838 ///
839 /// This actually returns an instance of DiagnosticBuilder which emits the
840 /// diagnostics (through @c ProcessDiag) when it is destroyed.
841 ///
842 /// \param DiagID A member of the @c diag::kind enum.
843 /// \param Loc Represents the source location associated with the diagnostic,
844 /// which can be an invalid location if no position information is available.
845 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID);
846 inline DiagnosticBuilder Report(unsigned DiagID);
847
848 void Report(const StoredDiagnostic &storedDiag);
849
850 /// Determine whethere there is already a diagnostic in flight.
851 bool isDiagnosticInFlight() const {
852 return CurDiagID != std::numeric_limits<unsigned>::max();
853 }
854
855 /// Set the "delayed" diagnostic that will be emitted once
856 /// the current diagnostic completes.
857 ///
858 /// If a diagnostic is already in-flight but the front end must
859 /// report a problem (e.g., with an inconsistent file system
860 /// state), this routine sets a "delayed" diagnostic that will be
861 /// emitted after the current diagnostic completes. This should
862 /// only be used for fatal errors detected at inconvenient
863 /// times. If emitting a delayed diagnostic causes a second delayed
864 /// diagnostic to be introduced, that second delayed diagnostic
865 /// will be ignored.
866 ///
867 /// \param DiagID The ID of the diagnostic being delayed.
868 ///
869 /// \param Arg1 A string argument that will be provided to the
870 /// diagnostic. A copy of this string will be stored in the
871 /// DiagnosticsEngine object itself.
872 ///
873 /// \param Arg2 A string argument that will be provided to the
874 /// diagnostic. A copy of this string will be stored in the
875 /// DiagnosticsEngine object itself.
876 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "",
877 StringRef Arg2 = "");
878
879 /// Clear out the current diagnostic.
880 void Clear() { CurDiagID = std::numeric_limits<unsigned>::max(); }
881
882 /// Return the value associated with this diagnostic flag.
883 StringRef getFlagValue() const { return FlagValue; }
884
885private:
886 // This is private state used by DiagnosticBuilder. We put it here instead of
887 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
888 // object. This implementation choice means that we can only have one
889 // diagnostic "in flight" at a time, but this seems to be a reasonable
890 // tradeoff to keep these objects small. Assertions verify that only one
891 // diagnostic is in flight at a time.
892 friend class Diagnostic;
893 friend class DiagnosticBuilder;
894 friend class DiagnosticErrorTrap;
895 friend class DiagnosticIDs;
896 friend class PartialDiagnostic;
897
898 /// Report the delayed diagnostic.
899 void ReportDelayed();
900
901 /// The location of the current diagnostic that is in flight.
902 SourceLocation CurDiagLoc;
903
904 /// The ID of the current diagnostic that is in flight.
905 ///
906 /// This is set to std::numeric_limits<unsigned>::max() when there is no
907 /// diagnostic in flight.
908 unsigned CurDiagID;
909
910 enum {
911 /// The maximum number of arguments we can hold.
912 ///
913 /// We currently only support up to 10 arguments (%0-%9). A single
914 /// diagnostic with more than that almost certainly has to be simplified
915 /// anyway.
916 MaxArguments = 10,
917 };
918
919 /// The number of entries in Arguments.
920 signed char NumDiagArgs;
921
922 /// Specifies whether an argument is in DiagArgumentsStr or
923 /// in DiagArguments.
924 ///
925 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each
926 /// argument.
927 unsigned char DiagArgumentsKind[MaxArguments];
928
929 /// Holds the values of each string argument for the current
930 /// diagnostic.
931 ///
932 /// This is only used when the corresponding ArgumentKind is ak_std_string.
933 std::string DiagArgumentsStr[MaxArguments];
934
935 /// The values for the various substitution positions.
936 ///
937 /// This is used when the argument is not an std::string. The specific
938 /// value is mangled into an intptr_t and the interpretation depends on
939 /// exactly what sort of argument kind it is.
940 intptr_t DiagArgumentsVal[MaxArguments];
941
942 /// The list of ranges added to this diagnostic.
943 SmallVector<CharSourceRange, 8> DiagRanges;
944
945 /// If valid, provides a hint with some code to insert, remove,
946 /// or modify at a particular position.
947 SmallVector<FixItHint, 8> DiagFixItHints;
948
949 DiagnosticMapping makeUserMapping(diag::Severity Map, SourceLocation L) {
950 bool isPragma = L.isValid();
951 DiagnosticMapping Mapping =
952 DiagnosticMapping::Make(Map, /*IsUser=*/true, isPragma);
953
954 // If this is a pragma mapping, then set the diagnostic mapping flags so
955 // that we override command line options.
956 if (isPragma) {
957 Mapping.setNoWarningAsError(true);
958 Mapping.setNoErrorAsFatal(true);
959 }
960
961 return Mapping;
962 }
963
964 /// Used to report a diagnostic that is finally fully formed.
965 ///
966 /// \returns true if the diagnostic was emitted, false if it was suppressed.
967 bool ProcessDiag() {
968 return Diags->ProcessDiag(*this);
969 }
970
971 /// @name Diagnostic Emission
972 /// @{
973protected:
974 friend class ASTReader;
975 friend class ASTWriter;
976
977 // Sema requires access to the following functions because the current design
978 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to
979 // access us directly to ensure we minimize the emitted code for the common
980 // Sema::Diag() patterns.
981 friend class Sema;
982
983 /// Emit the current diagnostic and clear the diagnostic state.
984 ///
985 /// \param Force Emit the diagnostic regardless of suppression settings.
986 bool EmitCurrentDiagnostic(bool Force = false);
987
988 unsigned getCurrentDiagID() const { return CurDiagID; }
989
990 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; }
991
992 /// @}
993};
994
995/// RAII class that determines when any errors have occurred
996/// between the time the instance was created and the time it was
997/// queried.
998class DiagnosticErrorTrap {
999 DiagnosticsEngine &Diag;
1000 unsigned NumErrors;
1001 unsigned NumUnrecoverableErrors;
1002
1003public:
1004 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag)
1005 : Diag(Diag) { reset(); }
1006
1007 /// Determine whether any errors have occurred since this
1008 /// object instance was created.
1009 bool hasErrorOccurred() const {
1010 return Diag.TrapNumErrorsOccurred > NumErrors;
1011 }
1012
1013 /// Determine whether any unrecoverable errors have occurred since this
1014 /// object instance was created.
1015 bool hasUnrecoverableErrorOccurred() const {
1016 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors;
1017 }
1018
1019 /// Set to initial state of "no errors occurred".
1020 void reset() {
1021 NumErrors = Diag.TrapNumErrorsOccurred;
1022 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred;
1023 }
1024};
1025
1026//===----------------------------------------------------------------------===//
1027// DiagnosticBuilder
1028//===----------------------------------------------------------------------===//
1029
1030/// A little helper class used to produce diagnostics.
1031///
1032/// This is constructed by the DiagnosticsEngine::Report method, and
1033/// allows insertion of extra information (arguments and source ranges) into
1034/// the currently "in flight" diagnostic. When the temporary for the builder
1035/// is destroyed, the diagnostic is issued.
1036///
1037/// Note that many of these will be created as temporary objects (many call
1038/// sites), so we want them to be small and we never want their address taken.
1039/// This ensures that compilers with somewhat reasonable optimizers will promote
1040/// the common fields to registers, eliminating increments of the NumArgs field,
1041/// for example.
1042class DiagnosticBuilder {
1043 friend class DiagnosticsEngine;
1044 friend class PartialDiagnostic;
1045
1046 mutable DiagnosticsEngine *DiagObj = nullptr;
1047 mutable unsigned NumArgs = 0;
1048
1049 /// Status variable indicating if this diagnostic is still active.
1050 ///
1051 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)),
1052 // but LLVM is not currently smart enough to eliminate the null check that
1053 // Emit() would end up with if we used that as our status variable.
1054 mutable bool IsActive = false;
1055
1056 /// Flag indicating that this diagnostic is being emitted via a
1057 /// call to ForceEmit.
1058 mutable bool IsForceEmit = false;
1059
1060 DiagnosticBuilder() = default;
1061
1062 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj)
1063 : DiagObj(diagObj), IsActive(true) {
1064 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!");
1065 diagObj->DiagRanges.clear();
1066 diagObj->DiagFixItHints.clear();
1067 }
1068
1069protected:
1070 void FlushCounts() {
1071 DiagObj->NumDiagArgs = NumArgs;
1072 }
1073
1074 /// Clear out the current diagnostic.
1075 void Clear() const {
1076 DiagObj = nullptr;
1077 IsActive = false;
1078 IsForceEmit = false;
1079 }
1080
1081 /// Determine whether this diagnostic is still active.
1082 bool isActive() const { return IsActive; }
1083
1084 /// Force the diagnostic builder to emit the diagnostic now.
1085 ///
1086 /// Once this function has been called, the DiagnosticBuilder object
1087 /// should not be used again before it is destroyed.
1088 ///
1089 /// \returns true if a diagnostic was emitted, false if the
1090 /// diagnostic was suppressed.
1091 bool Emit() {
1092 // If this diagnostic is inactive, then its soul was stolen by the copy ctor
1093 // (or by a subclass, as in SemaDiagnosticBuilder).
1094 if (!isActive()) return false;
1095
1096 // When emitting diagnostics, we set the final argument count into
1097 // the DiagnosticsEngine object.
1098 FlushCounts();
1099
1100 // Process the diagnostic.
1101 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit);
1102
1103 // This diagnostic is dead.
1104 Clear();
1105
1106 return Result;
1107 }
1108
1109public:
1110 /// Copy constructor. When copied, this "takes" the diagnostic info from the
1111 /// input and neuters it.
1112 DiagnosticBuilder(const DiagnosticBuilder &D) {
1113 DiagObj = D.DiagObj;
1114 IsActive = D.IsActive;
1115 IsForceEmit = D.IsForceEmit;
1116 D.Clear();
1117 NumArgs = D.NumArgs;
1118 }
1119
1120 DiagnosticBuilder &operator=(const DiagnosticBuilder &) = delete;
1121
1122 /// Emits the diagnostic.
1123 ~DiagnosticBuilder() {
1124 Emit();
1125 }
1126
1127 /// Retrieve an empty diagnostic builder.
1128 static DiagnosticBuilder getEmpty() {
1129 return {};
1130 }
1131
1132 /// Forces the diagnostic to be emitted.
1133 const DiagnosticBuilder &setForceEmit() const {
1134 IsForceEmit = true;
1135 return *this;
1136 }
1137
1138 /// Conversion of DiagnosticBuilder to bool always returns \c true.
1139 ///
1140 /// This allows is to be used in boolean error contexts (where \c true is
1141 /// used to indicate that an error has occurred), like:
1142 /// \code
1143 /// return Diag(...);
1144 /// \endcode
1145 operator bool() const { return true; }
1146
1147 void AddString(StringRef S) const {
1148 assert(isActive() && "Clients must not add to cleared diagnostic!");
1149 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1150 "Too many arguments to diagnostic!");
1151 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string;
1152 DiagObj->DiagArgumentsStr[NumArgs++] = S;
1153 }
1154
1155 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const {
1156 assert(isActive() && "Clients must not add to cleared diagnostic!");
1157 assert(NumArgs < DiagnosticsEngine::MaxArguments &&
1158 "Too many arguments to diagnostic!");
1159 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
1160 DiagObj->DiagArgumentsVal[NumArgs++] = V;
1161 }
1162
1163 void AddSourceRange(const CharSourceRange &R) const {
1164 assert(isActive() && "Clients must not add to cleared diagnostic!");
1165 DiagObj->DiagRanges.push_back(R);
1166 }
1167
1168 void AddFixItHint(const FixItHint &Hint) const {
1169 assert(isActive() && "Clients must not add to cleared diagnostic!");
1170 if (!Hint.isNull())
1171 DiagObj->DiagFixItHints.push_back(Hint);
1172 }
1173
1174 void addFlagValue(StringRef V) const { DiagObj->FlagValue = V; }
1175};
1176
1177struct AddFlagValue {
1178 StringRef Val;
1179
1180 explicit AddFlagValue(StringRef V) : Val(V) {}
1181};
1182
1183/// Register a value for the flag in the current diagnostic. This
1184/// value will be shown as the suffix "=value" after the flag name. It is
1185/// useful in cases where the diagnostic flag accepts values (e.g.,
1186/// -Rpass or -Wframe-larger-than).
1187inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1188 const AddFlagValue V) {
1189 DB.addFlagValue(V.Val);
1190 return DB;
1191}
1192
1193inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1194 StringRef S) {
1195 DB.AddString(S);
1196 return DB;
1197}
1198
1199inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1200 const char *Str) {
1201 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
1202 DiagnosticsEngine::ak_c_string);
1203 return DB;
1204}
1205
1206inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
1207 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1208 return DB;
1209}
1210
1211// We use enable_if here to prevent that this overload is selected for
1212// pointers or other arguments that are implicitly convertible to bool.
1213template <typename T>
1214inline
1215typename std::enable_if<std::is_same<T, bool>::value,
1216 const DiagnosticBuilder &>::type
1217operator<<(const DiagnosticBuilder &DB, T I) {
1218 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint);
1219 return DB;
1220}
1221
1222inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1223 unsigned I) {
1224 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint);
1225 return DB;
1226}
1227
1228inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1229 tok::TokenKind I) {
1230 DB.AddTaggedVal(static_cast<unsigned>(I), DiagnosticsEngine::ak_tokenkind);
1231 return DB;
1232}
1233
1234inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1235 const IdentifierInfo *II) {
1236 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
1237 DiagnosticsEngine::ak_identifierinfo);
1238 return DB;
1239}
1240
1241// Adds a DeclContext to the diagnostic. The enable_if template magic is here
1242// so that we only match those arguments that are (statically) DeclContexts;
1243// other arguments that derive from DeclContext (e.g., RecordDecls) will not
1244// match.
1245template <typename T>
1246inline typename std::enable_if<
1247 std::is_same<typename std::remove_const<T>::type, DeclContext>::value,
1248 const DiagnosticBuilder &>::type
1249operator<<(const DiagnosticBuilder &DB, T *DC) {
1250 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
1251 DiagnosticsEngine::ak_declcontext);
1252 return DB;
1253}
1254
1255inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1256 SourceRange R) {
1257 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1258 return DB;
1259}
1260
1261inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1262 ArrayRef<SourceRange> Ranges) {
1263 for (SourceRange R : Ranges)
1264 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
1265 return DB;
1266}
1267
1268inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1269 const CharSourceRange &R) {
1270 DB.AddSourceRange(R);
1271 return DB;
1272}
1273
1274inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1275 const FixItHint &Hint) {
1276 DB.AddFixItHint(Hint);
1277 return DB;
1278}
1279
1280inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1281 ArrayRef<FixItHint> Hints) {
1282 for (const FixItHint &Hint : Hints)
1283 DB.AddFixItHint(Hint);
1284 return DB;
1285}
1286
1287/// A nullability kind paired with a bit indicating whether it used a
1288/// context-sensitive keyword.
1289using DiagNullabilityKind = std::pair<NullabilityKind, bool>;
1290
1291const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
1292 DiagNullabilityKind nullability);
1293
1294inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc,
1295 unsigned DiagID) {
1296 assert(CurDiagID == std::numeric_limits<unsigned>::max() &&
1297 "Multiple diagnostics in flight at once!");
1298 CurDiagLoc = Loc;
1299 CurDiagID = DiagID;
1300 FlagValue.clear();
1301 return DiagnosticBuilder(this);
1302}
1303
1304inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) {
1305 return Report(SourceLocation(), DiagID);
1306}
1307
1308//===----------------------------------------------------------------------===//
1309// Diagnostic
1310//===----------------------------------------------------------------------===//
1311
1312/// A little helper class (which is basically a smart pointer that forwards
1313/// info from DiagnosticsEngine) that allows clients to enquire about the
1314/// currently in-flight diagnostic.
1315class Diagnostic {
1316 const DiagnosticsEngine *DiagObj;
1317 StringRef StoredDiagMessage;
1318
1319public:
1320 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {}
1321 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage)
1322 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
1323
1324 const DiagnosticsEngine *getDiags() const { return DiagObj; }
1325 unsigned getID() const { return DiagObj->CurDiagID; }
1326 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
1327 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
1328 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
1329
1330 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
1331
1332 /// Return the kind of the specified index.
1333 ///
1334 /// Based on the kind of argument, the accessors below can be used to get
1335 /// the value.
1336 ///
1337 /// \pre Idx < getNumArgs()
1338 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const {
1339 assert(Idx < getNumArgs() && "Argument index out of range!");
1340 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
1341 }
1342
1343 /// Return the provided argument string specified by \p Idx.
1344 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string
1345 const std::string &getArgStdStr(unsigned Idx) const {
1346 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string &&
1347 "invalid argument accessor!");
1348 return DiagObj->DiagArgumentsStr[Idx];
1349 }
1350
1351 /// Return the specified C string argument.
1352 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string
1353 const char *getArgCStr(unsigned Idx) const {
1354 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string &&
1355 "invalid argument accessor!");
1356 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
1357 }
1358
1359 /// Return the specified signed integer argument.
1360 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint
1361 int getArgSInt(unsigned Idx) const {
1362 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint &&
1363 "invalid argument accessor!");
1364 return (int)DiagObj->DiagArgumentsVal[Idx];
1365 }
1366
1367 /// Return the specified unsigned integer argument.
1368 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint
1369 unsigned getArgUInt(unsigned Idx) const {
1370 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint &&
1371 "invalid argument accessor!");
1372 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
1373 }
1374
1375 /// Return the specified IdentifierInfo argument.
1376 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo
1377 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
1378 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo &&
1379 "invalid argument accessor!");
1380 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
1381 }
1382
1383 /// Return the specified non-string argument in an opaque form.
1384 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string
1385 intptr_t getRawArg(unsigned Idx) const {
1386 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string &&
1387 "invalid argument accessor!");
1388 return DiagObj->DiagArgumentsVal[Idx];
1389 }
1390
1391 /// Return the number of source ranges associated with this diagnostic.
1392 unsigned getNumRanges() const {
1393 return DiagObj->DiagRanges.size();
1394 }
1395
1396 /// \pre Idx < getNumRanges()
1397 const CharSourceRange &getRange(unsigned Idx) const {
1398 assert(Idx < getNumRanges() && "Invalid diagnostic range index!");
1399 return DiagObj->DiagRanges[Idx];
1400 }
1401
1402 /// Return an array reference for this diagnostic's ranges.
1403 ArrayRef<CharSourceRange> getRanges() const {
1404 return DiagObj->DiagRanges;
1405 }
1406
1407 unsigned getNumFixItHints() const {
1408 return DiagObj->DiagFixItHints.size();
1409 }
1410
1411 const FixItHint &getFixItHint(unsigned Idx) const {
1412 assert(Idx < getNumFixItHints() && "Invalid index!");
1413 return DiagObj->DiagFixItHints[Idx];
1414 }
1415
1416 ArrayRef<FixItHint> getFixItHints() const {
1417 return DiagObj->DiagFixItHints;
1418 }
1419
1420 /// Format this diagnostic into a string, substituting the
1421 /// formal arguments into the %0 slots.
1422 ///
1423 /// The result is appended onto the \p OutStr array.
1424 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const;
1425
1426 /// Format the given format-string into the output buffer using the
1427 /// arguments stored in this diagnostic.
1428 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
1429 SmallVectorImpl<char> &OutStr) const;
1430};
1431
1432/**
1433 * Represents a diagnostic in a form that can be retained until its
1434 * corresponding source manager is destroyed.
1435 */
1436class StoredDiagnostic {
1437 unsigned ID;
1438 DiagnosticsEngine::Level Level;
1439 FullSourceLoc Loc;
1440 std::string Message;
1441 std::vector<CharSourceRange> Ranges;
1442 std::vector<FixItHint> FixIts;
1443
1444public:
1445 StoredDiagnostic() = default;
1446 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info);
1447 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1448 StringRef Message);
1449 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID,
1450 StringRef Message, FullSourceLoc Loc,
1451 ArrayRef<CharSourceRange> Ranges,
1452 ArrayRef<FixItHint> Fixits);
1453
1454 /// Evaluates true when this object stores a diagnostic.
1455 explicit operator bool() const { return !Message.empty(); }
1456
1457 unsigned getID() const { return ID; }
1458 DiagnosticsEngine::Level getLevel() const { return Level; }
1459 const FullSourceLoc &getLocation() const { return Loc; }
1460 StringRef getMessage() const { return Message; }
1461
1462 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
1463
1464 using range_iterator = std::vector<CharSourceRange>::const_iterator;
1465
1466 range_iterator range_begin() const { return Ranges.begin(); }
1467 range_iterator range_end() const { return Ranges.end(); }
1468 unsigned range_size() const { return Ranges.size(); }
1469
1470 ArrayRef<CharSourceRange> getRanges() const {
1471 return llvm::makeArrayRef(Ranges);
1472 }
1473
1474 using fixit_iterator = std::vector<FixItHint>::const_iterator;
1475
1476 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1477 fixit_iterator fixit_end() const { return FixIts.end(); }
1478 unsigned fixit_size() const { return FixIts.size(); }
1479
1480 ArrayRef<FixItHint> getFixIts() const {
1481 return llvm::makeArrayRef(FixIts);
1482 }
1483};
1484
1485/// Abstract interface, implemented by clients of the front-end, which
1486/// formats and prints fully processed diagnostics.
1487class DiagnosticConsumer {
1488protected:
1489 unsigned NumWarnings = 0; ///< Number of warnings reported
1490 unsigned NumErrors = 0; ///< Number of errors reported
1491
1492public:
1493 DiagnosticConsumer() = default;
1494 virtual ~DiagnosticConsumer();
1495
1496 unsigned getNumErrors() const { return NumErrors; }
1497 unsigned getNumWarnings() const { return NumWarnings; }
1498 virtual void clear() { NumWarnings = NumErrors = 0; }
1499
1500 /// Callback to inform the diagnostic client that processing
1501 /// of a source file is beginning.
1502 ///
1503 /// Note that diagnostics may be emitted outside the processing of a source
1504 /// file, for example during the parsing of command line options. However,
1505 /// diagnostics with source range information are required to only be emitted
1506 /// in between BeginSourceFile() and EndSourceFile().
1507 ///
1508 /// \param LangOpts The language options for the source file being processed.
1509 /// \param PP The preprocessor object being used for the source; this is
1510 /// optional, e.g., it may not be present when processing AST source files.
1511 virtual void BeginSourceFile(const LangOptions &LangOpts,
1512 const Preprocessor *PP = nullptr) {}
1513
1514 /// Callback to inform the diagnostic client that processing
1515 /// of a source file has ended.
1516 ///
1517 /// The diagnostic client should assume that any objects made available via
1518 /// BeginSourceFile() are inaccessible.
1519 virtual void EndSourceFile() {}
1520
1521 /// Callback to inform the diagnostic client that processing of all
1522 /// source files has ended.
1523 virtual void finish() {}
1524
1525 /// Indicates whether the diagnostics handled by this
1526 /// DiagnosticConsumer should be included in the number of diagnostics
1527 /// reported by DiagnosticsEngine.
1528 ///
1529 /// The default implementation returns true.
1530 virtual bool IncludeInDiagnosticCounts() const;
1531
1532 /// Handle this diagnostic, reporting it to the user or
1533 /// capturing it to a log as needed.
1534 ///
1535 /// The default implementation just keeps track of the total number of
1536 /// warnings and errors.
1537 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1538 const Diagnostic &Info);
1539};
1540
1541/// A diagnostic client that ignores all diagnostics.
1542class IgnoringDiagConsumer : public DiagnosticConsumer {
1543 virtual void anchor();
1544
1545 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1546 const Diagnostic &Info) override {
1547 // Just ignore it.
1548 }
1549};
1550
1551/// Diagnostic consumer that forwards diagnostics along to an
1552/// existing, already-initialized diagnostic consumer.
1553///
1554class ForwardingDiagnosticConsumer : public DiagnosticConsumer {
1555 DiagnosticConsumer &Target;
1556
1557public:
1558 ForwardingDiagnosticConsumer(DiagnosticConsumer &Target) : Target(Target) {}
1559 ~ForwardingDiagnosticConsumer() override;
1560
1561 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel,
1562 const Diagnostic &Info) override;
1563 void clear() override;
1564
1565 bool IncludeInDiagnosticCounts() const override;
1566};
1567
1568// Struct used for sending info about how a type should be printed.
1569struct TemplateDiffTypes {
1570 intptr_t FromType;
1571 intptr_t ToType;
1572 unsigned PrintTree : 1;
1573 unsigned PrintFromType : 1;
1574 unsigned ElideType : 1;
1575 unsigned ShowColors : 1;
1576
1577 // The printer sets this variable to true if the template diff was used.
1578 unsigned TemplateDiffUsed : 1;
1579};
1580
1581/// Special character that the diagnostic printer will use to toggle the bold
1582/// attribute. The character itself will be not be printed.
1583const char ToggleHighlight = 127;
1584
1585/// ProcessWarningOptions - Initialize the diagnostic client and process the
1586/// warning options specified on the command line.
1587void ProcessWarningOptions(DiagnosticsEngine &Diags,
1588 const DiagnosticOptions &Opts,
1589 bool ReportDiags = true);
1590
1591} // namespace clang
1592
1593#endif // LLVM_CLANG_BASIC_DIAGNOSTIC_H
1594