Remove the hack where, to get the return status, we had special case for VerifyDiagno...
[clang.git] / include / clang / Basic / Diagnostic.h
blob1f3b2cd5f47ca86c32a5ac87baef021bde2810ef
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 // This file defines the Diagnostic-related interfaces.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_DIAGNOSTIC_H
15 #define LLVM_CLANG_DIAGNOSTIC_H
17 #include "clang/Basic/DiagnosticIDs.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "llvm/ADT/IntrusiveRefCntPtr.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/Support/type_traits.h"
23 #include <vector>
25 namespace clang {
26 class DiagnosticClient;
27 class DiagnosticBuilder;
28 class IdentifierInfo;
29 class DeclContext;
30 class LangOptions;
31 class Preprocessor;
33 /// \brief Annotates a diagnostic with some code that should be
34 /// inserted, removed, or replaced to fix the problem.
35 ///
36 /// This kind of hint should be used when we are certain that the
37 /// introduction, removal, or modification of a particular (small!)
38 /// amount of code will correct a compilation error. The compiler
39 /// should also provide full recovery from such errors, such that
40 /// suppressing the diagnostic output can still result in successful
41 /// compilation.
42 class FixItHint {
43 public:
44 /// \brief Code that should be replaced to correct the error. Empty for an
45 /// insertion hint.
46 CharSourceRange RemoveRange;
48 /// \brief The actual code to insert at the insertion location, as a
49 /// string.
50 std::string CodeToInsert;
52 /// \brief Empty code modification hint, indicating that no code
53 /// modification is known.
54 FixItHint() : RemoveRange() { }
56 bool isNull() const {
57 return !RemoveRange.isValid();
60 /// \brief Create a code modification hint that inserts the given
61 /// code string at a specific location.
62 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
63 llvm::StringRef Code) {
64 FixItHint Hint;
65 Hint.RemoveRange =
66 CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
67 Hint.CodeToInsert = Code;
68 return Hint;
71 /// \brief Create a code modification hint that removes the given
72 /// source range.
73 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
74 FixItHint Hint;
75 Hint.RemoveRange = RemoveRange;
76 return Hint;
78 static FixItHint CreateRemoval(SourceRange RemoveRange) {
79 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
82 /// \brief Create a code modification hint that replaces the given
83 /// source range with the given code string.
84 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
85 llvm::StringRef Code) {
86 FixItHint Hint;
87 Hint.RemoveRange = RemoveRange;
88 Hint.CodeToInsert = Code;
89 return Hint;
92 static FixItHint CreateReplacement(SourceRange RemoveRange,
93 llvm::StringRef Code) {
94 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
98 /// Diagnostic - This concrete class is used by the front-end to report
99 /// problems and issues. It massages the diagnostics (e.g. handling things like
100 /// "report warnings as errors" and passes them off to the DiagnosticClient for
101 /// reporting to the user. Diagnostic is tied to one translation unit and
102 /// one SourceManager.
103 class Diagnostic : public llvm::RefCountedBase<Diagnostic> {
104 public:
105 /// Level - The level of the diagnostic, after it has been through mapping.
106 enum Level {
107 Ignored = DiagnosticIDs::Ignored,
108 Note = DiagnosticIDs::Note,
109 Warning = DiagnosticIDs::Warning,
110 Error = DiagnosticIDs::Error,
111 Fatal = DiagnosticIDs::Fatal
114 /// ExtensionHandling - How do we handle otherwise-unmapped extension? This
115 /// is controlled by -pedantic and -pedantic-errors.
116 enum ExtensionHandling {
117 Ext_Ignore, Ext_Warn, Ext_Error
120 enum ArgumentKind {
121 ak_std_string, // std::string
122 ak_c_string, // const char *
123 ak_sint, // int
124 ak_uint, // unsigned
125 ak_identifierinfo, // IdentifierInfo
126 ak_qualtype, // QualType
127 ak_declarationname, // DeclarationName
128 ak_nameddecl, // NamedDecl *
129 ak_nestednamespec, // NestedNameSpecifier *
130 ak_declcontext // DeclContext *
133 /// Specifies which overload candidates to display when overload resolution
134 /// fails.
135 enum OverloadsShown {
136 Ovl_All, ///< Show all overloads.
137 Ovl_Best ///< Show just the "best" overload candidates.
140 /// ArgumentValue - This typedef represents on argument value, which is a
141 /// union discriminated by ArgumentKind, with a value.
142 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
144 private:
145 unsigned char AllExtensionsSilenced; // Used by __extension__
146 bool IgnoreAllWarnings; // Ignore all warnings: -w
147 bool WarningsAsErrors; // Treat warnings like errors:
148 bool ErrorsAsFatal; // Treat errors like fatal errors.
149 bool SuppressSystemWarnings; // Suppress warnings in system headers.
150 bool SuppressAllDiagnostics; // Suppress all diagnostics.
151 OverloadsShown ShowOverloads; // Which overload candidates to show.
152 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
153 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
154 // 0 -> no limit.
155 ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
156 llvm::IntrusiveRefCntPtr<DiagnosticIDs> Diags;
157 DiagnosticClient *Client;
158 bool OwnsDiagClient;
159 SourceManager *SourceMgr;
161 /// DiagMappings - Mapping information for diagnostics. Mapping info is
162 /// packed into four bits per diagnostic. The low three bits are the mapping
163 /// (an instance of diag::Mapping), or zero if unset. The high bit is set
164 /// when the mapping was established as a user mapping. If the high bit is
165 /// clear, then the low bits are set to the default value, and should be
166 /// mapped with -pedantic, -Werror, etc.
167 class DiagMappings {
168 unsigned char Values[diag::DIAG_UPPER_LIMIT/2];
170 public:
171 DiagMappings() : Values() /*zero-initialization of array*/ { }
173 void setMapping(diag::kind Diag, unsigned Map) {
174 size_t Shift = (Diag & 1)*4;
175 Values[Diag/2] = (Values[Diag/2] & ~(15 << Shift)) | (Map << Shift);
178 diag::Mapping getMapping(diag::kind Diag) const {
179 return (diag::Mapping)((Values[Diag/2] >> (Diag & 1)*4) & 15);
183 mutable std::vector<DiagMappings> DiagMappingsStack;
185 /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
186 /// fatal error is emitted, and is sticky.
187 bool ErrorOccurred;
188 bool FatalErrorOccurred;
190 /// LastDiagLevel - This is the level of the last diagnostic emitted. This is
191 /// used to emit continuation diagnostics with the same level as the
192 /// diagnostic that they follow.
193 DiagnosticIDs::Level LastDiagLevel;
195 unsigned NumWarnings; // Number of warnings reported
196 unsigned NumErrors; // Number of errors reported
197 unsigned NumErrorsSuppressed; // Number of errors suppressed
199 /// ArgToStringFn - A function pointer that converts an opaque diagnostic
200 /// argument to a strings. This takes the modifiers and argument that was
201 /// present in the diagnostic.
203 /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
204 /// arguments formatted for this diagnostic. Implementations of this function
205 /// can use this information to avoid redundancy across arguments.
207 /// This is a hack to avoid a layering violation between libbasic and libsema.
208 typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
209 const char *Modifier, unsigned ModifierLen,
210 const char *Argument, unsigned ArgumentLen,
211 const ArgumentValue *PrevArgs,
212 unsigned NumPrevArgs,
213 llvm::SmallVectorImpl<char> &Output,
214 void *Cookie);
215 void *ArgToStringCookie;
216 ArgToStringFnTy ArgToStringFn;
218 /// \brief ID of the "delayed" diagnostic, which is a (typically
219 /// fatal) diagnostic that had to be delayed because it was found
220 /// while emitting another diagnostic.
221 unsigned DelayedDiagID;
223 /// \brief First string argument for the delayed diagnostic.
224 std::string DelayedDiagArg1;
226 /// \brief Second string argument for the delayed diagnostic.
227 std::string DelayedDiagArg2;
229 public:
230 explicit Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
231 DiagnosticClient *client = 0,
232 bool ShouldOwnClient = true);
233 ~Diagnostic();
235 const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
236 return Diags;
239 DiagnosticClient *getClient() { return Client; }
240 const DiagnosticClient *getClient() const { return Client; }
242 /// \brief Return the current diagnostic client along with ownership of that
243 /// client.
244 DiagnosticClient *takeClient() {
245 OwnsDiagClient = false;
246 return Client;
249 bool hasSourceManager() const { return SourceMgr != 0; }
250 SourceManager &getSourceManager() const {
251 assert(SourceMgr && "SourceManager not set!");
252 return *SourceMgr;
254 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
256 //===--------------------------------------------------------------------===//
257 // Diagnostic characterization methods, used by a client to customize how
258 // diagnostics are emitted.
261 /// pushMappings - Copies the current DiagMappings and pushes the new copy
262 /// onto the top of the stack.
263 void pushMappings();
265 /// popMappings - Pops the current DiagMappings off the top of the stack
266 /// causing the new top of the stack to be the active mappings. Returns
267 /// true if the pop happens, false if there is only one DiagMapping on the
268 /// stack.
269 bool popMappings();
271 /// \brief Set the diagnostic client associated with this diagnostic object.
273 /// \param ShouldOwnClient true if the diagnostic object should take
274 /// ownership of \c client.
275 void setClient(DiagnosticClient *client, bool ShouldOwnClient = true) {
276 Client = client;
277 OwnsDiagClient = ShouldOwnClient;
280 /// setErrorLimit - Specify a limit for the number of errors we should
281 /// emit before giving up. Zero disables the limit.
282 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
284 /// \brief Specify the maximum number of template instantiation
285 /// notes to emit along with a given diagnostic.
286 void setTemplateBacktraceLimit(unsigned Limit) {
287 TemplateBacktraceLimit = Limit;
290 /// \brief Retrieve the maximum number of template instantiation
291 /// nodes to emit along with a given diagnostic.
292 unsigned getTemplateBacktraceLimit() const {
293 return TemplateBacktraceLimit;
296 /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
297 /// ignored. If this and WarningsAsErrors are both set, then this one wins.
298 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
299 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
301 /// setWarningsAsErrors - When set to true, any warnings reported are issued
302 /// as errors.
303 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
304 bool getWarningsAsErrors() const { return WarningsAsErrors; }
306 /// setErrorsAsFatal - When set to true, any error reported is made a
307 /// fatal error.
308 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
309 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
311 /// setSuppressSystemWarnings - When set to true mask warnings that
312 /// come from system headers.
313 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
314 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
316 /// \brief Suppress all diagnostics, to silence the front end when we
317 /// know that we don't want any more diagnostics to be passed along to the
318 /// client
319 void setSuppressAllDiagnostics(bool Val = true) {
320 SuppressAllDiagnostics = Val;
322 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
324 /// \brief Specify which overload candidates to show when overload resolution
325 /// fails. By default, we show all candidates.
326 void setShowOverloads(OverloadsShown Val) {
327 ShowOverloads = Val;
329 OverloadsShown getShowOverloads() const { return ShowOverloads; }
331 /// \brief Pretend that the last diagnostic issued was ignored. This can
332 /// be used by clients who suppress diagnostics themselves.
333 void setLastDiagnosticIgnored() {
334 LastDiagLevel = DiagnosticIDs::Ignored;
337 /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
338 /// extension diagnostics are mapped onto ignore/warning/error. This
339 /// corresponds to the GCC -pedantic and -pedantic-errors option.
340 void setExtensionHandlingBehavior(ExtensionHandling H) {
341 ExtBehavior = H;
344 /// AllExtensionsSilenced - This is a counter bumped when an __extension__
345 /// block is encountered. When non-zero, all extension diagnostics are
346 /// entirely silenced, no matter how they are mapped.
347 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
348 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
349 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
351 /// setDiagnosticMapping - This allows the client to specify that certain
352 /// warnings are ignored. Notes can never be mapped, errors can only be
353 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
354 void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map) {
355 assert(Diag < diag::DIAG_UPPER_LIMIT &&
356 "Can only map builtin diagnostics");
357 assert((Diags->isBuiltinWarningOrExtension(Diag) ||
358 (Map == diag::MAP_FATAL || Map == diag::MAP_ERROR)) &&
359 "Cannot map errors into warnings!");
360 setDiagnosticMappingInternal(Diag, Map, true);
363 /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
364 /// "unknown-pragmas" to have the specified mapping. This returns true and
365 /// ignores the request if "Group" was unknown, false otherwise.
366 bool setDiagnosticGroupMapping(const char *Group, diag::Mapping Map) {
367 return Diags->setDiagnosticGroupMapping(Group, Map, *this);
370 bool hasErrorOccurred() const { return ErrorOccurred; }
371 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
373 unsigned getNumErrors() const { return NumErrors; }
374 unsigned getNumErrorsSuppressed() const { return NumErrorsSuppressed; }
375 unsigned getNumWarnings() const { return NumWarnings; }
377 void setNumWarnings(unsigned NumWarnings) {
378 this->NumWarnings = NumWarnings;
381 void setNumErrors(unsigned NumErrors) {
382 this->NumErrors = NumErrors;
385 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
386 /// and level. If this is the first request for this diagnosic, it is
387 /// registered and created, otherwise the existing ID is returned.
388 unsigned getCustomDiagID(Level L, llvm::StringRef Message) {
389 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
392 /// ConvertArgToString - This method converts a diagnostic argument (as an
393 /// intptr_t) into the string that represents it.
394 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
395 const char *Modifier, unsigned ModLen,
396 const char *Argument, unsigned ArgLen,
397 const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
398 llvm::SmallVectorImpl<char> &Output) const {
399 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
400 PrevArgs, NumPrevArgs, Output, ArgToStringCookie);
403 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
404 ArgToStringFn = Fn;
405 ArgToStringCookie = Cookie;
408 /// \brief Reset the state of the diagnostic object to its initial
409 /// configuration.
410 void Reset();
412 //===--------------------------------------------------------------------===//
413 // Diagnostic classification and reporting interfaces.
416 /// getDiagnosticLevel - Based on the way the client configured the Diagnostic
417 /// object, classify the specified diagnostic ID into a Level, consumable by
418 /// the DiagnosticClient.
419 Level getDiagnosticLevel(unsigned DiagID) const {
420 return (Level)Diags->getDiagnosticLevel(DiagID, *this);
423 /// Report - Issue the message to the client. @c DiagID is a member of the
424 /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder
425 /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
426 /// @c Pos represents the source location associated with the diagnostic,
427 /// which can be an invalid location if no position information is available.
428 inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID);
429 inline DiagnosticBuilder Report(unsigned DiagID);
431 /// \brief Determine whethere there is already a diagnostic in flight.
432 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
434 /// \brief Set the "delayed" diagnostic that will be emitted once
435 /// the current diagnostic completes.
437 /// If a diagnostic is already in-flight but the front end must
438 /// report a problem (e.g., with an inconsistent file system
439 /// state), this routine sets a "delayed" diagnostic that will be
440 /// emitted after the current diagnostic completes. This should
441 /// only be used for fatal errors detected at inconvenient
442 /// times. If emitting a delayed diagnostic causes a second delayed
443 /// diagnostic to be introduced, that second delayed diagnostic
444 /// will be ignored.
446 /// \param DiagID The ID of the diagnostic being delayed.
448 /// \param Arg1 A string argument that will be provided to the
449 /// diagnostic. A copy of this string will be stored in the
450 /// Diagnostic object itself.
452 /// \param Arg2 A string argument that will be provided to the
453 /// diagnostic. A copy of this string will be stored in the
454 /// Diagnostic object itself.
455 void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "",
456 llvm::StringRef Arg2 = "");
458 /// \brief Clear out the current diagnostic.
459 void Clear() { CurDiagID = ~0U; }
461 private:
462 /// \brief Report the delayed diagnostic.
463 void ReportDelayed();
466 /// getDiagnosticMappingInfo - Return the mapping info currently set for the
467 /// specified builtin diagnostic. This returns the high bit encoding, or zero
468 /// if the field is completely uninitialized.
469 diag::Mapping getDiagnosticMappingInfo(diag::kind Diag) const {
470 return DiagMappingsStack.back().getMapping(Diag);
473 void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
474 bool isUser) const {
475 if (isUser) Map |= 8; // Set the high bit for user mappings.
476 DiagMappingsStack.back().setMapping((diag::kind)DiagId, Map);
479 // This is private state used by DiagnosticBuilder. We put it here instead of
480 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
481 // object. This implementation choice means that we can only have one
482 // diagnostic "in flight" at a time, but this seems to be a reasonable
483 // tradeoff to keep these objects small. Assertions verify that only one
484 // diagnostic is in flight at a time.
485 friend class DiagnosticIDs;
486 friend class DiagnosticBuilder;
487 friend class DiagnosticInfo;
488 friend class PartialDiagnostic;
490 /// CurDiagLoc - This is the location of the current diagnostic that is in
491 /// flight.
492 SourceLocation CurDiagLoc;
494 /// CurDiagID - This is the ID of the current diagnostic that is in flight.
495 /// This is set to ~0U when there is no diagnostic in flight.
496 unsigned CurDiagID;
498 enum {
499 /// MaxArguments - The maximum number of arguments we can hold. We currently
500 /// only support up to 10 arguments (%0-%9). A single diagnostic with more
501 /// than that almost certainly has to be simplified anyway.
502 MaxArguments = 10
505 /// NumDiagArgs - This contains the number of entries in Arguments.
506 signed char NumDiagArgs;
507 /// NumRanges - This is the number of ranges in the DiagRanges array.
508 unsigned char NumDiagRanges;
509 /// \brief The number of code modifications hints in the
510 /// FixItHints array.
511 unsigned char NumFixItHints;
513 /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
514 /// values, with one for each argument. This specifies whether the argument
515 /// is in DiagArgumentsStr or in DiagArguments.
516 unsigned char DiagArgumentsKind[MaxArguments];
518 /// DiagArgumentsStr - This holds the values of each string argument for the
519 /// current diagnostic. This value is only used when the corresponding
520 /// ArgumentKind is ak_std_string.
521 std::string DiagArgumentsStr[MaxArguments];
523 /// DiagArgumentsVal - The values for the various substitution positions. This
524 /// is used when the argument is not an std::string. The specific value is
525 /// mangled into an intptr_t and the intepretation depends on exactly what
526 /// sort of argument kind it is.
527 intptr_t DiagArgumentsVal[MaxArguments];
529 /// DiagRanges - The list of ranges added to this diagnostic. It currently
530 /// only support 10 ranges, could easily be extended if needed.
531 CharSourceRange DiagRanges[10];
533 enum { MaxFixItHints = 3 };
535 /// FixItHints - If valid, provides a hint with some code
536 /// to insert, remove, or modify at a particular position.
537 FixItHint FixItHints[MaxFixItHints];
539 /// ProcessDiag - This is the method used to report a diagnostic that is
540 /// finally fully formed.
542 /// \returns true if the diagnostic was emitted, false if it was
543 /// suppressed.
544 bool ProcessDiag() {
545 return Diags->ProcessDiag(*this);
548 friend class ASTReader;
549 friend class ASTWriter;
552 //===----------------------------------------------------------------------===//
553 // DiagnosticBuilder
554 //===----------------------------------------------------------------------===//
556 /// DiagnosticBuilder - This is a little helper class used to produce
557 /// diagnostics. This is constructed by the Diagnostic::Report method, and
558 /// allows insertion of extra information (arguments and source ranges) into the
559 /// currently "in flight" diagnostic. When the temporary for the builder is
560 /// destroyed, the diagnostic is issued.
562 /// Note that many of these will be created as temporary objects (many call
563 /// sites), so we want them to be small and we never want their address taken.
564 /// This ensures that compilers with somewhat reasonable optimizers will promote
565 /// the common fields to registers, eliminating increments of the NumArgs field,
566 /// for example.
567 class DiagnosticBuilder {
568 mutable Diagnostic *DiagObj;
569 mutable unsigned NumArgs, NumRanges, NumFixItHints;
571 void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
572 friend class Diagnostic;
573 explicit DiagnosticBuilder(Diagnostic *diagObj)
574 : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
576 friend class PartialDiagnostic;
578 protected:
579 void FlushCounts();
581 public:
582 /// Copy constructor. When copied, this "takes" the diagnostic info from the
583 /// input and neuters it.
584 DiagnosticBuilder(const DiagnosticBuilder &D) {
585 DiagObj = D.DiagObj;
586 D.DiagObj = 0;
587 NumArgs = D.NumArgs;
588 NumRanges = D.NumRanges;
589 NumFixItHints = D.NumFixItHints;
592 /// \brief Simple enumeration value used to give a name to the
593 /// suppress-diagnostic constructor.
594 enum SuppressKind { Suppress };
596 /// \brief Create an empty DiagnosticBuilder object that represents
597 /// no actual diagnostic.
598 explicit DiagnosticBuilder(SuppressKind)
599 : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
601 /// \brief Force the diagnostic builder to emit the diagnostic now.
603 /// Once this function has been called, the DiagnosticBuilder object
604 /// should not be used again before it is destroyed.
606 /// \returns true if a diagnostic was emitted, false if the
607 /// diagnostic was suppressed.
608 bool Emit();
610 /// Destructor - The dtor emits the diagnostic if it hasn't already
611 /// been emitted.
612 ~DiagnosticBuilder() { Emit(); }
614 /// isActive - Determine whether this diagnostic is still active.
615 bool isActive() const { return DiagObj != 0; }
617 /// \brief Retrieve the active diagnostic ID.
619 /// \pre \c isActive()
620 unsigned getDiagID() const {
621 assert(isActive() && "Diagnostic is inactive");
622 return DiagObj->CurDiagID;
625 /// \brief Clear out the current diagnostic.
626 void Clear() { DiagObj = 0; }
628 /// Operator bool: conversion of DiagnosticBuilder to bool always returns
629 /// true. This allows is to be used in boolean error contexts like:
630 /// return Diag(...);
631 operator bool() const { return true; }
633 void AddString(llvm::StringRef S) const {
634 assert(NumArgs < Diagnostic::MaxArguments &&
635 "Too many arguments to diagnostic!");
636 if (DiagObj) {
637 DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
638 DiagObj->DiagArgumentsStr[NumArgs++] = S;
642 void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
643 assert(NumArgs < Diagnostic::MaxArguments &&
644 "Too many arguments to diagnostic!");
645 if (DiagObj) {
646 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
647 DiagObj->DiagArgumentsVal[NumArgs++] = V;
651 void AddSourceRange(const CharSourceRange &R) const {
652 assert(NumRanges <
653 sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
654 "Too many arguments to diagnostic!");
655 if (DiagObj)
656 DiagObj->DiagRanges[NumRanges++] = R;
659 void AddFixItHint(const FixItHint &Hint) const {
660 if (Hint.isNull())
661 return;
663 assert(NumFixItHints < Diagnostic::MaxFixItHints &&
664 "Too many fix-it hints!");
665 if (DiagObj)
666 DiagObj->FixItHints[NumFixItHints++] = Hint;
670 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
671 llvm::StringRef S) {
672 DB.AddString(S);
673 return DB;
676 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
677 const char *Str) {
678 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
679 Diagnostic::ak_c_string);
680 return DB;
683 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
684 DB.AddTaggedVal(I, Diagnostic::ak_sint);
685 return DB;
688 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
689 DB.AddTaggedVal(I, Diagnostic::ak_sint);
690 return DB;
693 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
694 unsigned I) {
695 DB.AddTaggedVal(I, Diagnostic::ak_uint);
696 return DB;
699 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
700 const IdentifierInfo *II) {
701 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
702 Diagnostic::ak_identifierinfo);
703 return DB;
706 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
707 // so that we only match those arguments that are (statically) DeclContexts;
708 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
709 // match.
710 template<typename T>
711 inline
712 typename llvm::enable_if<llvm::is_same<T, DeclContext>,
713 const DiagnosticBuilder &>::type
714 operator<<(const DiagnosticBuilder &DB, T *DC) {
715 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
716 Diagnostic::ak_declcontext);
717 return DB;
720 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
721 const SourceRange &R) {
722 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
723 return DB;
726 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
727 const CharSourceRange &R) {
728 DB.AddSourceRange(R);
729 return DB;
732 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
733 const FixItHint &Hint) {
734 DB.AddFixItHint(Hint);
735 return DB;
738 /// Report - Issue the message to the client. DiagID is a member of the
739 /// diag::kind enum. This actually returns a new instance of DiagnosticBuilder
740 /// which emits the diagnostics (through ProcessDiag) when it is destroyed.
741 inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc,
742 unsigned DiagID){
743 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
744 CurDiagLoc = Loc;
745 CurDiagID = DiagID;
746 return DiagnosticBuilder(this);
748 inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
749 return Report(SourceLocation(), DiagID);
752 //===----------------------------------------------------------------------===//
753 // DiagnosticInfo
754 //===----------------------------------------------------------------------===//
756 /// DiagnosticInfo - This is a little helper class (which is basically a smart
757 /// pointer that forward info from Diagnostic) that allows clients to enquire
758 /// about the currently in-flight diagnostic.
759 class DiagnosticInfo {
760 const Diagnostic *DiagObj;
761 public:
762 explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
764 const Diagnostic *getDiags() const { return DiagObj; }
765 unsigned getID() const { return DiagObj->CurDiagID; }
766 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
767 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
768 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
770 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
772 /// getArgKind - Return the kind of the specified index. Based on the kind
773 /// of argument, the accessors below can be used to get the value.
774 Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
775 assert(Idx < getNumArgs() && "Argument index out of range!");
776 return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
779 /// getArgStdStr - Return the provided argument string specified by Idx.
780 const std::string &getArgStdStr(unsigned Idx) const {
781 assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
782 "invalid argument accessor!");
783 return DiagObj->DiagArgumentsStr[Idx];
786 /// getArgCStr - Return the specified C string argument.
787 const char *getArgCStr(unsigned Idx) const {
788 assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
789 "invalid argument accessor!");
790 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
793 /// getArgSInt - Return the specified signed integer argument.
794 int getArgSInt(unsigned Idx) const {
795 assert(getArgKind(Idx) == Diagnostic::ak_sint &&
796 "invalid argument accessor!");
797 return (int)DiagObj->DiagArgumentsVal[Idx];
800 /// getArgUInt - Return the specified unsigned integer argument.
801 unsigned getArgUInt(unsigned Idx) const {
802 assert(getArgKind(Idx) == Diagnostic::ak_uint &&
803 "invalid argument accessor!");
804 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
807 /// getArgIdentifier - Return the specified IdentifierInfo argument.
808 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
809 assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
810 "invalid argument accessor!");
811 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
814 /// getRawArg - Return the specified non-string argument in an opaque form.
815 intptr_t getRawArg(unsigned Idx) const {
816 assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
817 "invalid argument accessor!");
818 return DiagObj->DiagArgumentsVal[Idx];
822 /// getNumRanges - Return the number of source ranges associated with this
823 /// diagnostic.
824 unsigned getNumRanges() const {
825 return DiagObj->NumDiagRanges;
828 const CharSourceRange &getRange(unsigned Idx) const {
829 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
830 return DiagObj->DiagRanges[Idx];
833 unsigned getNumFixItHints() const {
834 return DiagObj->NumFixItHints;
837 const FixItHint &getFixItHint(unsigned Idx) const {
838 return DiagObj->FixItHints[Idx];
841 const FixItHint *getFixItHints() const {
842 return DiagObj->NumFixItHints?
843 &DiagObj->FixItHints[0] : 0;
846 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
847 /// formal arguments into the %0 slots. The result is appended onto the Str
848 /// array.
849 void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
851 /// FormatDiagnostic - Format the given format-string into the
852 /// output buffer using the arguments stored in this diagnostic.
853 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
854 llvm::SmallVectorImpl<char> &OutStr) const;
858 * \brief Represents a diagnostic in a form that can be retained until its
859 * corresponding source manager is destroyed.
861 class StoredDiagnostic {
862 Diagnostic::Level Level;
863 FullSourceLoc Loc;
864 std::string Message;
865 std::vector<CharSourceRange> Ranges;
866 std::vector<FixItHint> FixIts;
868 public:
869 StoredDiagnostic();
870 StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
871 StoredDiagnostic(Diagnostic::Level Level, llvm::StringRef Message);
872 ~StoredDiagnostic();
874 /// \brief Evaluates true when this object stores a diagnostic.
875 operator bool() const { return Message.size() > 0; }
877 Diagnostic::Level getLevel() const { return Level; }
878 const FullSourceLoc &getLocation() const { return Loc; }
879 llvm::StringRef getMessage() const { return Message; }
881 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
883 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
884 range_iterator range_begin() const { return Ranges.begin(); }
885 range_iterator range_end() const { return Ranges.end(); }
886 unsigned range_size() const { return Ranges.size(); }
888 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
889 fixit_iterator fixit_begin() const { return FixIts.begin(); }
890 fixit_iterator fixit_end() const { return FixIts.end(); }
891 unsigned fixit_size() const { return FixIts.size(); }
894 /// DiagnosticClient - This is an abstract interface implemented by clients of
895 /// the front-end, which formats and prints fully processed diagnostics.
896 class DiagnosticClient {
897 protected:
898 unsigned NumWarnings; // Number of warnings reported
899 unsigned NumErrors; // Number of errors reported
901 public:
902 DiagnosticClient() : NumWarnings(0), NumErrors(0) { }
904 unsigned getNumErrors() const { return NumErrors; }
905 unsigned getNumWarnings() const { return NumWarnings; }
907 virtual ~DiagnosticClient();
909 /// BeginSourceFile - Callback to inform the diagnostic client that processing
910 /// of a source file is beginning.
912 /// Note that diagnostics may be emitted outside the processing of a source
913 /// file, for example during the parsing of command line options. However,
914 /// diagnostics with source range information are required to only be emitted
915 /// in between BeginSourceFile() and EndSourceFile().
917 /// \arg LO - The language options for the source file being processed.
918 /// \arg PP - The preprocessor object being used for the source; this optional
919 /// and may not be present, for example when processing AST source files.
920 virtual void BeginSourceFile(const LangOptions &LangOpts,
921 const Preprocessor *PP = 0) {}
923 /// EndSourceFile - Callback to inform the diagnostic client that processing
924 /// of a source file has ended. The diagnostic client should assume that any
925 /// objects made available via \see BeginSourceFile() are inaccessible.
926 virtual void EndSourceFile() {}
928 /// IncludeInDiagnosticCounts - This method (whose default implementation
929 /// returns true) indicates whether the diagnostics handled by this
930 /// DiagnosticClient should be included in the number of diagnostics reported
931 /// by Diagnostic.
932 virtual bool IncludeInDiagnosticCounts() const;
934 /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
935 /// capturing it to a log as needed.
937 /// Default implementation just keeps track of the total number of warnings
938 /// and errors.
939 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
940 const DiagnosticInfo &Info);
943 } // end namespace clang
945 #endif