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