1 //===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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/DenseMap.h"
20 #include "llvm/ADT/IntrusiveRefCntPtr.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/Support/type_traits.h"
28 class DiagnosticClient;
29 class DiagnosticBuilder;
34 class DiagnosticErrorTrap;
35 class StoredDiagnostic;
37 /// \brief Annotates a diagnostic with some code that should be
38 /// inserted, removed, or replaced to fix the problem.
40 /// This kind of hint should be used when we are certain that the
41 /// introduction, removal, or modification of a particular (small!)
42 /// amount of code will correct a compilation error. The compiler
43 /// should also provide full recovery from such errors, such that
44 /// suppressing the diagnostic output can still result in successful
48 /// \brief Code that should be replaced to correct the error. Empty for an
50 CharSourceRange RemoveRange;
52 /// \brief The actual code to insert at the insertion location, as a
54 std::string CodeToInsert;
56 /// \brief Empty code modification hint, indicating that no code
57 /// modification is known.
58 FixItHint() : RemoveRange() { }
61 return !RemoveRange.isValid();
64 /// \brief Create a code modification hint that inserts the given
65 /// code string at a specific location.
66 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
67 llvm::StringRef Code) {
70 CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
71 Hint.CodeToInsert = Code;
75 /// \brief Create a code modification hint that removes the given
77 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
79 Hint.RemoveRange = RemoveRange;
82 static FixItHint CreateRemoval(SourceRange RemoveRange) {
83 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
86 /// \brief Create a code modification hint that replaces the given
87 /// source range with the given code string.
88 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
89 llvm::StringRef Code) {
91 Hint.RemoveRange = RemoveRange;
92 Hint.CodeToInsert = Code;
96 static FixItHint CreateReplacement(SourceRange RemoveRange,
97 llvm::StringRef Code) {
98 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
102 /// Diagnostic - This concrete class is used by the front-end to report
103 /// problems and issues. It massages the diagnostics (e.g. handling things like
104 /// "report warnings as errors" and passes them off to the DiagnosticClient for
105 /// reporting to the user. Diagnostic is tied to one translation unit and
106 /// one SourceManager.
107 class Diagnostic : public llvm::RefCountedBase<Diagnostic> {
109 /// Level - The level of the diagnostic, after it has been through mapping.
111 Ignored = DiagnosticIDs::Ignored,
112 Note = DiagnosticIDs::Note,
113 Warning = DiagnosticIDs::Warning,
114 Error = DiagnosticIDs::Error,
115 Fatal = DiagnosticIDs::Fatal
118 /// ExtensionHandling - How do we handle otherwise-unmapped extension? This
119 /// is controlled by -pedantic and -pedantic-errors.
120 enum ExtensionHandling {
121 Ext_Ignore, Ext_Warn, Ext_Error
125 ak_std_string, // std::string
126 ak_c_string, // const char *
129 ak_identifierinfo, // IdentifierInfo
130 ak_qualtype, // QualType
131 ak_declarationname, // DeclarationName
132 ak_nameddecl, // NamedDecl *
133 ak_nestednamespec, // NestedNameSpecifier *
134 ak_declcontext // DeclContext *
137 /// Specifies which overload candidates to display when overload resolution
139 enum OverloadsShown {
140 Ovl_All, ///< Show all overloads.
141 Ovl_Best ///< Show just the "best" overload candidates.
144 /// ArgumentValue - This typedef represents on argument value, which is a
145 /// union discriminated by ArgumentKind, with a value.
146 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
149 unsigned char AllExtensionsSilenced; // Used by __extension__
150 bool IgnoreAllWarnings; // Ignore all warnings: -w
151 bool WarningsAsErrors; // Treat warnings like errors:
152 bool ErrorsAsFatal; // Treat errors like fatal errors.
153 bool SuppressSystemWarnings; // Suppress warnings in system headers.
154 bool SuppressAllDiagnostics; // Suppress all diagnostics.
155 OverloadsShown ShowOverloads; // Which overload candidates to show.
156 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
157 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
159 ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
160 llvm::IntrusiveRefCntPtr<DiagnosticIDs> Diags;
161 DiagnosticClient *Client;
163 SourceManager *SourceMgr;
165 /// \brief Mapping information for diagnostics. Mapping info is
166 /// packed into four bits per diagnostic. The low three bits are the mapping
167 /// (an instance of diag::Mapping), or zero if unset. The high bit is set
168 /// when the mapping was established as a user mapping. If the high bit is
169 /// clear, then the low bits are set to the default value, and should be
170 /// mapped with -pedantic, -Werror, etc.
172 /// A new DiagState is created and kept around when diagnostic pragmas modify
173 /// the state so that we know what is the diagnostic state at any given
176 llvm::DenseMap<unsigned, unsigned> DiagMap;
179 typedef llvm::DenseMap<unsigned, unsigned>::const_iterator iterator;
181 void setMapping(diag::kind Diag, unsigned Map) { DiagMap[Diag] = Map; }
183 diag::Mapping getMapping(diag::kind Diag) const {
184 iterator I = DiagMap.find(Diag);
185 if (I != DiagMap.end())
186 return (diag::Mapping)I->second;
187 return diag::Mapping();
190 iterator begin() const { return DiagMap.begin(); }
191 iterator end() const { return DiagMap.end(); }
194 /// \brief Keeps and automatically disposes all DiagStates that we create.
195 std::list<DiagState> DiagStates;
197 /// \brief Represents a point in source where the diagnostic state was
198 /// modified because of a pragma. 'Loc' can be null if the point represents
199 /// the diagnostic state modifications done through the command-line.
200 struct DiagStatePoint {
203 DiagStatePoint(DiagState *State, FullSourceLoc Loc)
204 : State(State), Loc(Loc) { }
206 bool operator<(const DiagStatePoint &RHS) const {
207 // If Loc is invalid it means it came from <command-line>, in which case
208 // we regard it as coming before any valid source location.
209 if (RHS.Loc.isInvalid())
213 return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
217 /// \brief A vector of all DiagStatePoints representing changes in diagnostic
218 /// state due to diagnostic pragmas. The vector is always sorted according to
219 /// the SourceLocation of the DiagStatePoint.
220 typedef std::vector<DiagStatePoint> DiagStatePointsTy;
221 mutable DiagStatePointsTy DiagStatePoints;
223 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
224 /// so we can get back at it when we 'pop'.
225 std::vector<DiagState *> DiagStateOnPushStack;
227 DiagState *GetCurDiagState() const {
228 assert(!DiagStatePoints.empty());
229 return DiagStatePoints.back().State;
232 void PushDiagStatePoint(DiagState *State, SourceLocation L) {
233 FullSourceLoc Loc(L, *SourceMgr);
234 // Make sure that DiagStatePoints is always sorted according to Loc.
235 assert((Loc.isValid() || DiagStatePoints.empty()) &&
236 "Adding invalid loc point after another point");
237 assert((Loc.isInvalid() || DiagStatePoints.empty() ||
238 DiagStatePoints.back().Loc.isInvalid() ||
239 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
240 "Previous point loc comes after or is the same as new one");
241 DiagStatePoints.push_back(DiagStatePoint(State,
242 FullSourceLoc(Loc, *SourceMgr)));
245 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
246 /// the given source location.
247 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
249 /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
250 /// fatal error is emitted, and is sticky.
252 bool FatalErrorOccurred;
254 /// LastDiagLevel - This is the level of the last diagnostic emitted. This is
255 /// used to emit continuation diagnostics with the same level as the
256 /// diagnostic that they follow.
257 DiagnosticIDs::Level LastDiagLevel;
259 unsigned NumWarnings; // Number of warnings reported
260 unsigned NumErrors; // Number of errors reported
261 unsigned NumErrorsSuppressed; // Number of errors suppressed
263 /// ArgToStringFn - A function pointer that converts an opaque diagnostic
264 /// argument to a strings. This takes the modifiers and argument that was
265 /// present in the diagnostic.
267 /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
268 /// arguments formatted for this diagnostic. Implementations of this function
269 /// can use this information to avoid redundancy across arguments.
271 /// This is a hack to avoid a layering violation between libbasic and libsema.
272 typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
273 const char *Modifier, unsigned ModifierLen,
274 const char *Argument, unsigned ArgumentLen,
275 const ArgumentValue *PrevArgs,
276 unsigned NumPrevArgs,
277 llvm::SmallVectorImpl<char> &Output,
279 void *ArgToStringCookie;
280 ArgToStringFnTy ArgToStringFn;
282 /// \brief ID of the "delayed" diagnostic, which is a (typically
283 /// fatal) diagnostic that had to be delayed because it was found
284 /// while emitting another diagnostic.
285 unsigned DelayedDiagID;
287 /// \brief First string argument for the delayed diagnostic.
288 std::string DelayedDiagArg1;
290 /// \brief Second string argument for the delayed diagnostic.
291 std::string DelayedDiagArg2;
294 explicit Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
295 DiagnosticClient *client = 0,
296 bool ShouldOwnClient = true);
299 const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
303 DiagnosticClient *getClient() { return Client; }
304 const DiagnosticClient *getClient() const { return Client; }
306 /// \brief Return the current diagnostic client along with ownership of that
308 DiagnosticClient *takeClient() {
309 OwnsDiagClient = false;
313 bool hasSourceManager() const { return SourceMgr != 0; }
314 SourceManager &getSourceManager() const {
315 assert(SourceMgr && "SourceManager not set!");
318 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
320 //===--------------------------------------------------------------------===//
321 // Diagnostic characterization methods, used by a client to customize how
322 // diagnostics are emitted.
325 /// pushMappings - Copies the current DiagMappings and pushes the new copy
326 /// onto the top of the stack.
327 void pushMappings(SourceLocation Loc);
329 /// popMappings - Pops the current DiagMappings off the top of the stack
330 /// causing the new top of the stack to be the active mappings. Returns
331 /// true if the pop happens, false if there is only one DiagMapping on the
333 bool popMappings(SourceLocation Loc);
335 /// \brief Set the diagnostic client associated with this diagnostic object.
337 /// \param ShouldOwnClient true if the diagnostic object should take
338 /// ownership of \c client.
339 void setClient(DiagnosticClient *client, bool ShouldOwnClient = true);
341 /// setErrorLimit - Specify a limit for the number of errors we should
342 /// emit before giving up. Zero disables the limit.
343 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
345 /// \brief Specify the maximum number of template instantiation
346 /// notes to emit along with a given diagnostic.
347 void setTemplateBacktraceLimit(unsigned Limit) {
348 TemplateBacktraceLimit = Limit;
351 /// \brief Retrieve the maximum number of template instantiation
352 /// nodes to emit along with a given diagnostic.
353 unsigned getTemplateBacktraceLimit() const {
354 return TemplateBacktraceLimit;
357 /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
358 /// ignored. If this and WarningsAsErrors are both set, then this one wins.
359 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
360 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
362 /// setWarningsAsErrors - When set to true, any warnings reported are issued
364 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
365 bool getWarningsAsErrors() const { return WarningsAsErrors; }
367 /// setErrorsAsFatal - When set to true, any error reported is made a
369 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
370 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
372 /// setSuppressSystemWarnings - When set to true mask warnings that
373 /// come from system headers.
374 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
375 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
377 /// \brief Suppress all diagnostics, to silence the front end when we
378 /// know that we don't want any more diagnostics to be passed along to the
380 void setSuppressAllDiagnostics(bool Val = true) {
381 SuppressAllDiagnostics = Val;
383 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
385 /// \brief Specify which overload candidates to show when overload resolution
386 /// fails. By default, we show all candidates.
387 void setShowOverloads(OverloadsShown Val) {
390 OverloadsShown getShowOverloads() const { return ShowOverloads; }
392 /// \brief Pretend that the last diagnostic issued was ignored. This can
393 /// be used by clients who suppress diagnostics themselves.
394 void setLastDiagnosticIgnored() {
395 LastDiagLevel = DiagnosticIDs::Ignored;
398 /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
399 /// extension diagnostics are mapped onto ignore/warning/error. This
400 /// corresponds to the GCC -pedantic and -pedantic-errors option.
401 void setExtensionHandlingBehavior(ExtensionHandling H) {
404 ExtensionHandling getExtensionHandlingBehavior() const { return ExtBehavior; }
406 /// AllExtensionsSilenced - This is a counter bumped when an __extension__
407 /// block is encountered. When non-zero, all extension diagnostics are
408 /// entirely silenced, no matter how they are mapped.
409 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
410 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
411 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
413 /// \brief This allows the client to specify that certain
414 /// warnings are ignored. Notes can never be mapped, errors can only be
415 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
417 /// \param Loc The source location that this change of diagnostic state should
418 /// take affect. It can be null if we are setting the latest state.
419 void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
422 /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
423 /// "unknown-pragmas" to have the specified mapping. This returns true and
424 /// ignores the request if "Group" was unknown, false otherwise.
426 /// 'Loc' is the source location that this change of diagnostic state should
427 /// take affect. It can be null if we are setting the state from command-line.
428 bool setDiagnosticGroupMapping(llvm::StringRef Group, diag::Mapping Map,
429 SourceLocation Loc = SourceLocation()) {
430 return Diags->setDiagnosticGroupMapping(Group, Map, Loc, *this);
433 bool hasErrorOccurred() const { return ErrorOccurred; }
434 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
436 unsigned getNumWarnings() const { return NumWarnings; }
438 void setNumWarnings(unsigned NumWarnings) {
439 this->NumWarnings = NumWarnings;
442 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
443 /// and level. If this is the first request for this diagnosic, it is
444 /// registered and created, otherwise the existing ID is returned.
445 unsigned getCustomDiagID(Level L, llvm::StringRef Message) {
446 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
449 /// ConvertArgToString - This method converts a diagnostic argument (as an
450 /// intptr_t) into the string that represents it.
451 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
452 const char *Modifier, unsigned ModLen,
453 const char *Argument, unsigned ArgLen,
454 const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
455 llvm::SmallVectorImpl<char> &Output) const {
456 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
457 PrevArgs, NumPrevArgs, Output, ArgToStringCookie);
460 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
462 ArgToStringCookie = Cookie;
465 /// \brief Reset the state of the diagnostic object to its initial
469 //===--------------------------------------------------------------------===//
470 // Diagnostic classification and reporting interfaces.
473 /// \brief Based on the way the client configured the Diagnostic
474 /// object, classify the specified diagnostic ID into a Level, consumable by
475 /// the DiagnosticClient.
477 /// \param Loc The source location we are interested in finding out the
478 /// diagnostic state. Can be null in order to query the latest state.
479 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
480 diag::Mapping *mapping = 0) const {
481 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this, mapping);
484 /// Report - Issue the message to the client. @c DiagID is a member of the
485 /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder
486 /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
487 /// @c Pos represents the source location associated with the diagnostic,
488 /// which can be an invalid location if no position information is available.
489 inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID);
490 inline DiagnosticBuilder Report(unsigned DiagID);
492 void Report(const StoredDiagnostic &storedDiag);
494 /// \brief Determine whethere there is already a diagnostic in flight.
495 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
497 /// \brief Set the "delayed" diagnostic that will be emitted once
498 /// the current diagnostic completes.
500 /// If a diagnostic is already in-flight but the front end must
501 /// report a problem (e.g., with an inconsistent file system
502 /// state), this routine sets a "delayed" diagnostic that will be
503 /// emitted after the current diagnostic completes. This should
504 /// only be used for fatal errors detected at inconvenient
505 /// times. If emitting a delayed diagnostic causes a second delayed
506 /// diagnostic to be introduced, that second delayed diagnostic
509 /// \param DiagID The ID of the diagnostic being delayed.
511 /// \param Arg1 A string argument that will be provided to the
512 /// diagnostic. A copy of this string will be stored in the
513 /// Diagnostic object itself.
515 /// \param Arg2 A string argument that will be provided to the
516 /// diagnostic. A copy of this string will be stored in the
517 /// Diagnostic object itself.
518 void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "",
519 llvm::StringRef Arg2 = "");
521 /// \brief Clear out the current diagnostic.
522 void Clear() { CurDiagID = ~0U; }
525 /// \brief Report the delayed diagnostic.
526 void ReportDelayed();
529 /// getDiagnosticMappingInfo - Return the mapping info currently set for the
530 /// specified builtin diagnostic. This returns the high bit encoding, or zero
531 /// if the field is completely uninitialized.
532 diag::Mapping getDiagnosticMappingInfo(diag::kind Diag,
533 DiagState *State) const {
534 return State->getMapping(Diag);
537 void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
539 bool isUser, bool isPragma) const {
540 if (isUser) Map |= 8; // Set the high bit for user mappings.
541 if (isPragma) Map |= 0x10; // Set the bit for diagnostic pragma mappings.
542 State->setMapping((diag::kind)DiagId, Map);
545 // This is private state used by DiagnosticBuilder. We put it here instead of
546 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
547 // object. This implementation choice means that we can only have one
548 // diagnostic "in flight" at a time, but this seems to be a reasonable
549 // tradeoff to keep these objects small. Assertions verify that only one
550 // diagnostic is in flight at a time.
551 friend class DiagnosticIDs;
552 friend class DiagnosticBuilder;
553 friend class DiagnosticInfo;
554 friend class PartialDiagnostic;
555 friend class DiagnosticErrorTrap;
557 /// CurDiagLoc - This is the location of the current diagnostic that is in
559 SourceLocation CurDiagLoc;
561 /// CurDiagID - This is the ID of the current diagnostic that is in flight.
562 /// This is set to ~0U when there is no diagnostic in flight.
566 /// MaxArguments - The maximum number of arguments we can hold. We currently
567 /// only support up to 10 arguments (%0-%9). A single diagnostic with more
568 /// than that almost certainly has to be simplified anyway.
572 /// NumDiagArgs - This contains the number of entries in Arguments.
573 signed char NumDiagArgs;
574 /// NumRanges - This is the number of ranges in the DiagRanges array.
575 unsigned char NumDiagRanges;
576 /// \brief The number of code modifications hints in the
577 /// FixItHints array.
578 unsigned char NumFixItHints;
580 /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
581 /// values, with one for each argument. This specifies whether the argument
582 /// is in DiagArgumentsStr or in DiagArguments.
583 unsigned char DiagArgumentsKind[MaxArguments];
585 /// DiagArgumentsStr - This holds the values of each string argument for the
586 /// current diagnostic. This value is only used when the corresponding
587 /// ArgumentKind is ak_std_string.
588 std::string DiagArgumentsStr[MaxArguments];
590 /// DiagArgumentsVal - The values for the various substitution positions. This
591 /// is used when the argument is not an std::string. The specific value is
592 /// mangled into an intptr_t and the interpretation depends on exactly what
593 /// sort of argument kind it is.
594 intptr_t DiagArgumentsVal[MaxArguments];
596 /// DiagRanges - The list of ranges added to this diagnostic. It currently
597 /// only support 10 ranges, could easily be extended if needed.
598 CharSourceRange DiagRanges[10];
600 enum { MaxFixItHints = 3 };
602 /// FixItHints - If valid, provides a hint with some code
603 /// to insert, remove, or modify at a particular position.
604 FixItHint FixItHints[MaxFixItHints];
606 /// ProcessDiag - This is the method used to report a diagnostic that is
607 /// finally fully formed.
609 /// \returns true if the diagnostic was emitted, false if it was
612 return Diags->ProcessDiag(*this);
615 friend class ASTReader;
616 friend class ASTWriter;
619 /// \brief RAII class that determines when any errors have occurred
620 /// between the time the instance was created and the time it was
622 class DiagnosticErrorTrap {
627 explicit DiagnosticErrorTrap(Diagnostic &Diag)
628 : Diag(Diag), PrevErrors(Diag.NumErrors) {}
630 /// \brief Determine whether any errors have occurred since this
631 /// object instance was created.
632 bool hasErrorOccurred() const {
633 return Diag.NumErrors > PrevErrors;
636 // Set to initial state of "no errors occurred".
637 void reset() { PrevErrors = Diag.NumErrors; }
640 //===----------------------------------------------------------------------===//
642 //===----------------------------------------------------------------------===//
644 /// DiagnosticBuilder - This is a little helper class used to produce
645 /// diagnostics. This is constructed by the Diagnostic::Report method, and
646 /// allows insertion of extra information (arguments and source ranges) into the
647 /// currently "in flight" diagnostic. When the temporary for the builder is
648 /// destroyed, the diagnostic is issued.
650 /// Note that many of these will be created as temporary objects (many call
651 /// sites), so we want them to be small and we never want their address taken.
652 /// This ensures that compilers with somewhat reasonable optimizers will promote
653 /// the common fields to registers, eliminating increments of the NumArgs field,
655 class DiagnosticBuilder {
656 mutable Diagnostic *DiagObj;
657 mutable unsigned NumArgs, NumRanges, NumFixItHints;
659 void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
660 friend class Diagnostic;
661 explicit DiagnosticBuilder(Diagnostic *diagObj)
662 : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
664 friend class PartialDiagnostic;
670 /// Copy constructor. When copied, this "takes" the diagnostic info from the
671 /// input and neuters it.
672 DiagnosticBuilder(const DiagnosticBuilder &D) {
676 NumRanges = D.NumRanges;
677 NumFixItHints = D.NumFixItHints;
680 /// \brief Simple enumeration value used to give a name to the
681 /// suppress-diagnostic constructor.
682 enum SuppressKind { Suppress };
684 /// \brief Create an empty DiagnosticBuilder object that represents
685 /// no actual diagnostic.
686 explicit DiagnosticBuilder(SuppressKind)
687 : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
689 /// \brief Force the diagnostic builder to emit the diagnostic now.
691 /// Once this function has been called, the DiagnosticBuilder object
692 /// should not be used again before it is destroyed.
694 /// \returns true if a diagnostic was emitted, false if the
695 /// diagnostic was suppressed.
698 /// Destructor - The dtor emits the diagnostic if it hasn't already
700 ~DiagnosticBuilder() { Emit(); }
702 /// isActive - Determine whether this diagnostic is still active.
703 bool isActive() const { return DiagObj != 0; }
705 /// \brief Retrieve the active diagnostic ID.
707 /// \pre \c isActive()
708 unsigned getDiagID() const {
709 assert(isActive() && "Diagnostic is inactive");
710 return DiagObj->CurDiagID;
713 /// \brief Clear out the current diagnostic.
714 void Clear() { DiagObj = 0; }
716 /// Operator bool: conversion of DiagnosticBuilder to bool always returns
717 /// true. This allows is to be used in boolean error contexts like:
718 /// return Diag(...);
719 operator bool() const { return true; }
721 void AddString(llvm::StringRef S) const {
722 assert(NumArgs < Diagnostic::MaxArguments &&
723 "Too many arguments to diagnostic!");
725 DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
726 DiagObj->DiagArgumentsStr[NumArgs++] = S;
730 void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
731 assert(NumArgs < Diagnostic::MaxArguments &&
732 "Too many arguments to diagnostic!");
734 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
735 DiagObj->DiagArgumentsVal[NumArgs++] = V;
739 void AddSourceRange(const CharSourceRange &R) const {
741 sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
742 "Too many arguments to diagnostic!");
744 DiagObj->DiagRanges[NumRanges++] = R;
747 void AddFixItHint(const FixItHint &Hint) const {
748 assert(NumFixItHints < Diagnostic::MaxFixItHints &&
749 "Too many fix-it hints!");
751 DiagObj->FixItHints[NumFixItHints++] = Hint;
755 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
761 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
763 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
764 Diagnostic::ak_c_string);
768 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
769 DB.AddTaggedVal(I, Diagnostic::ak_sint);
773 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
774 DB.AddTaggedVal(I, Diagnostic::ak_sint);
778 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
780 DB.AddTaggedVal(I, Diagnostic::ak_uint);
784 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
785 const IdentifierInfo *II) {
786 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
787 Diagnostic::ak_identifierinfo);
791 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
792 // so that we only match those arguments that are (statically) DeclContexts;
793 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
797 typename llvm::enable_if<llvm::is_same<T, DeclContext>,
798 const DiagnosticBuilder &>::type
799 operator<<(const DiagnosticBuilder &DB, T *DC) {
800 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
801 Diagnostic::ak_declcontext);
805 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
806 const SourceRange &R) {
807 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
811 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
812 const CharSourceRange &R) {
813 DB.AddSourceRange(R);
817 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
818 const FixItHint &Hint) {
819 DB.AddFixItHint(Hint);
823 /// Report - Issue the message to the client. DiagID is a member of the
824 /// diag::kind enum. This actually returns a new instance of DiagnosticBuilder
825 /// which emits the diagnostics (through ProcessDiag) when it is destroyed.
826 inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc,
828 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
831 return DiagnosticBuilder(this);
833 inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
834 return Report(SourceLocation(), DiagID);
837 //===----------------------------------------------------------------------===//
839 //===----------------------------------------------------------------------===//
841 /// DiagnosticInfo - This is a little helper class (which is basically a smart
842 /// pointer that forward info from Diagnostic) that allows clients to enquire
843 /// about the currently in-flight diagnostic.
844 class DiagnosticInfo {
845 const Diagnostic *DiagObj;
846 llvm::StringRef StoredDiagMessage;
848 explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
849 DiagnosticInfo(const Diagnostic *DO, llvm::StringRef storedDiagMessage)
850 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
852 const Diagnostic *getDiags() const { return DiagObj; }
853 unsigned getID() const { return DiagObj->CurDiagID; }
854 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
855 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
856 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
858 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
860 /// getArgKind - Return the kind of the specified index. Based on the kind
861 /// of argument, the accessors below can be used to get the value.
862 Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
863 assert(Idx < getNumArgs() && "Argument index out of range!");
864 return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
867 /// getArgStdStr - Return the provided argument string specified by Idx.
868 const std::string &getArgStdStr(unsigned Idx) const {
869 assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
870 "invalid argument accessor!");
871 return DiagObj->DiagArgumentsStr[Idx];
874 /// getArgCStr - Return the specified C string argument.
875 const char *getArgCStr(unsigned Idx) const {
876 assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
877 "invalid argument accessor!");
878 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
881 /// getArgSInt - Return the specified signed integer argument.
882 int getArgSInt(unsigned Idx) const {
883 assert(getArgKind(Idx) == Diagnostic::ak_sint &&
884 "invalid argument accessor!");
885 return (int)DiagObj->DiagArgumentsVal[Idx];
888 /// getArgUInt - Return the specified unsigned integer argument.
889 unsigned getArgUInt(unsigned Idx) const {
890 assert(getArgKind(Idx) == Diagnostic::ak_uint &&
891 "invalid argument accessor!");
892 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
895 /// getArgIdentifier - Return the specified IdentifierInfo argument.
896 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
897 assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
898 "invalid argument accessor!");
899 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
902 /// getRawArg - Return the specified non-string argument in an opaque form.
903 intptr_t getRawArg(unsigned Idx) const {
904 assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
905 "invalid argument accessor!");
906 return DiagObj->DiagArgumentsVal[Idx];
910 /// getNumRanges - Return the number of source ranges associated with this
912 unsigned getNumRanges() const {
913 return DiagObj->NumDiagRanges;
916 const CharSourceRange &getRange(unsigned Idx) const {
917 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
918 return DiagObj->DiagRanges[Idx];
921 unsigned getNumFixItHints() const {
922 return DiagObj->NumFixItHints;
925 const FixItHint &getFixItHint(unsigned Idx) const {
926 return DiagObj->FixItHints[Idx];
929 const FixItHint *getFixItHints() const {
930 return DiagObj->NumFixItHints?
931 &DiagObj->FixItHints[0] : 0;
934 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
935 /// formal arguments into the %0 slots. The result is appended onto the Str
937 void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
939 /// FormatDiagnostic - Format the given format-string into the
940 /// output buffer using the arguments stored in this diagnostic.
941 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
942 llvm::SmallVectorImpl<char> &OutStr) const;
946 * \brief Represents a diagnostic in a form that can be retained until its
947 * corresponding source manager is destroyed.
949 class StoredDiagnostic {
951 Diagnostic::Level Level;
954 std::vector<CharSourceRange> Ranges;
955 std::vector<FixItHint> FixIts;
959 StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
960 StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
961 llvm::StringRef Message);
964 /// \brief Evaluates true when this object stores a diagnostic.
965 operator bool() const { return Message.size() > 0; }
967 unsigned getID() const { return ID; }
968 Diagnostic::Level getLevel() const { return Level; }
969 const FullSourceLoc &getLocation() const { return Loc; }
970 llvm::StringRef getMessage() const { return Message; }
972 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
974 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
975 range_iterator range_begin() const { return Ranges.begin(); }
976 range_iterator range_end() const { return Ranges.end(); }
977 unsigned range_size() const { return Ranges.size(); }
979 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
980 fixit_iterator fixit_begin() const { return FixIts.begin(); }
981 fixit_iterator fixit_end() const { return FixIts.end(); }
982 unsigned fixit_size() const { return FixIts.size(); }
985 /// DiagnosticClient - This is an abstract interface implemented by clients of
986 /// the front-end, which formats and prints fully processed diagnostics.
987 class DiagnosticClient {
989 unsigned NumWarnings; // Number of warnings reported
990 unsigned NumErrors; // Number of errors reported
993 DiagnosticClient() : NumWarnings(0), NumErrors(0) { }
995 unsigned getNumErrors() const { return NumErrors; }
996 unsigned getNumWarnings() const { return NumWarnings; }
998 virtual ~DiagnosticClient();
1000 /// BeginSourceFile - Callback to inform the diagnostic client that processing
1001 /// of a source file is beginning.
1003 /// Note that diagnostics may be emitted outside the processing of a source
1004 /// file, for example during the parsing of command line options. However,
1005 /// diagnostics with source range information are required to only be emitted
1006 /// in between BeginSourceFile() and EndSourceFile().
1008 /// \arg LO - The language options for the source file being processed.
1009 /// \arg PP - The preprocessor object being used for the source; this optional
1010 /// and may not be present, for example when processing AST source files.
1011 virtual void BeginSourceFile(const LangOptions &LangOpts,
1012 const Preprocessor *PP = 0) {}
1014 /// EndSourceFile - Callback to inform the diagnostic client that processing
1015 /// of a source file has ended. The diagnostic client should assume that any
1016 /// objects made available via \see BeginSourceFile() are inaccessible.
1017 virtual void EndSourceFile() {}
1019 /// IncludeInDiagnosticCounts - This method (whose default implementation
1020 /// returns true) indicates whether the diagnostics handled by this
1021 /// DiagnosticClient should be included in the number of diagnostics reported
1023 virtual bool IncludeInDiagnosticCounts() const;
1025 /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1026 /// capturing it to a log as needed.
1028 /// Default implementation just keeps track of the total number of warnings
1030 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1031 const DiagnosticInfo &Info);
1034 } // end namespace clang