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