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;
36 /// \brief Annotates a diagnostic with some code that should be
37 /// inserted, removed, or replaced to fix the problem.
39 /// This kind of hint should be used when we are certain that the
40 /// introduction, removal, or modification of a particular (small!)
41 /// amount of code will correct a compilation error. The compiler
42 /// should also provide full recovery from such errors, such that
43 /// suppressing the diagnostic output can still result in successful
47 /// \brief Code that should be replaced to correct the error. Empty for an
49 CharSourceRange RemoveRange;
51 /// \brief The actual code to insert at the insertion location, as a
53 std::string CodeToInsert;
55 /// \brief Empty code modification hint, indicating that no code
56 /// modification is known.
57 FixItHint() : RemoveRange() { }
60 return !RemoveRange.isValid();
63 /// \brief Create a code modification hint that inserts the given
64 /// code string at a specific location.
65 static FixItHint CreateInsertion(SourceLocation InsertionLoc,
66 llvm::StringRef Code) {
69 CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false);
70 Hint.CodeToInsert = Code;
74 /// \brief Create a code modification hint that removes the given
76 static FixItHint CreateRemoval(CharSourceRange RemoveRange) {
78 Hint.RemoveRange = RemoveRange;
81 static FixItHint CreateRemoval(SourceRange RemoveRange) {
82 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange));
85 /// \brief Create a code modification hint that replaces the given
86 /// source range with the given code string.
87 static FixItHint CreateReplacement(CharSourceRange RemoveRange,
88 llvm::StringRef Code) {
90 Hint.RemoveRange = RemoveRange;
91 Hint.CodeToInsert = Code;
95 static FixItHint CreateReplacement(SourceRange RemoveRange,
96 llvm::StringRef Code) {
97 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code);
101 /// Diagnostic - This concrete class is used by the front-end to report
102 /// problems and issues. It massages the diagnostics (e.g. handling things like
103 /// "report warnings as errors" and passes them off to the DiagnosticClient for
104 /// reporting to the user. Diagnostic is tied to one translation unit and
105 /// one SourceManager.
106 class Diagnostic : public llvm::RefCountedBase<Diagnostic> {
108 /// Level - The level of the diagnostic, after it has been through mapping.
110 Ignored = DiagnosticIDs::Ignored,
111 Note = DiagnosticIDs::Note,
112 Warning = DiagnosticIDs::Warning,
113 Error = DiagnosticIDs::Error,
114 Fatal = DiagnosticIDs::Fatal
117 /// ExtensionHandling - How do we handle otherwise-unmapped extension? This
118 /// is controlled by -pedantic and -pedantic-errors.
119 enum ExtensionHandling {
120 Ext_Ignore, Ext_Warn, Ext_Error
124 ak_std_string, // std::string
125 ak_c_string, // const char *
128 ak_identifierinfo, // IdentifierInfo
129 ak_qualtype, // QualType
130 ak_declarationname, // DeclarationName
131 ak_nameddecl, // NamedDecl *
132 ak_nestednamespec, // NestedNameSpecifier *
133 ak_declcontext // DeclContext *
136 /// Specifies which overload candidates to display when overload resolution
138 enum OverloadsShown {
139 Ovl_All, ///< Show all overloads.
140 Ovl_Best ///< Show just the "best" overload candidates.
143 /// ArgumentValue - This typedef represents on argument value, which is a
144 /// union discriminated by ArgumentKind, with a value.
145 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue;
148 unsigned char AllExtensionsSilenced; // Used by __extension__
149 bool IgnoreAllWarnings; // Ignore all warnings: -w
150 bool WarningsAsErrors; // Treat warnings like errors:
151 bool ErrorsAsFatal; // Treat errors like fatal errors.
152 bool SuppressSystemWarnings; // Suppress warnings in system headers.
153 bool SuppressAllDiagnostics; // Suppress all diagnostics.
154 OverloadsShown ShowOverloads; // Which overload candidates to show.
155 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit.
156 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack,
158 ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors?
159 llvm::IntrusiveRefCntPtr<DiagnosticIDs> Diags;
160 DiagnosticClient *Client;
162 SourceManager *SourceMgr;
164 /// \brief Mapping information for diagnostics. Mapping info is
165 /// packed into four bits per diagnostic. The low three bits are the mapping
166 /// (an instance of diag::Mapping), or zero if unset. The high bit is set
167 /// when the mapping was established as a user mapping. If the high bit is
168 /// clear, then the low bits are set to the default value, and should be
169 /// mapped with -pedantic, -Werror, etc.
171 /// A new DiagState is created and kept around when diagnostic pragmas modify
172 /// the state so that we know what is the diagnostic state at any given
175 llvm::DenseMap<unsigned, unsigned> DiagMap;
178 typedef llvm::DenseMap<unsigned, unsigned>::const_iterator iterator;
180 void setMapping(diag::kind Diag, unsigned Map) { DiagMap[Diag] = Map; }
182 diag::Mapping getMapping(diag::kind Diag) const {
183 iterator I = DiagMap.find(Diag);
184 if (I != DiagMap.end())
185 return (diag::Mapping)I->second;
186 return diag::Mapping();
189 iterator begin() const { return DiagMap.begin(); }
190 iterator end() const { return DiagMap.end(); }
193 /// \brief Keeps and automatically disposes all DiagStates that we create.
194 std::list<DiagState> DiagStates;
196 /// \brief Represents a point in source where the diagnostic state was
197 /// modified because of a pragma. 'Loc' can be null if the point represents
198 /// the diagnostic state modifications done through the command-line.
199 struct DiagStatePoint {
202 DiagStatePoint(DiagState *State, FullSourceLoc Loc)
203 : State(State), Loc(Loc) { }
205 bool operator<(const DiagStatePoint &RHS) const {
206 // If Loc is invalid it means it came from <command-line>, in which case
207 // we regard it as coming before any valid source location.
208 if (RHS.Loc.isInvalid())
212 return Loc.isBeforeInTranslationUnitThan(RHS.Loc);
216 /// \brief A vector of all DiagStatePoints representing changes in diagnostic
217 /// state due to diagnostic pragmas. The vector is always sorted according to
218 /// the SourceLocation of the DiagStatePoint.
219 typedef std::vector<DiagStatePoint> DiagStatePointsTy;
220 mutable DiagStatePointsTy DiagStatePoints;
222 /// \brief Keeps the DiagState that was active during each diagnostic 'push'
223 /// so we can get back at it when we 'pop'.
224 std::vector<DiagState *> DiagStateOnPushStack;
226 DiagState *GetCurDiagState() const {
227 assert(!DiagStatePoints.empty());
228 return DiagStatePoints.back().State;
231 void PushDiagStatePoint(DiagState *State, SourceLocation L) {
232 FullSourceLoc Loc(L, *SourceMgr);
233 // Make sure that DiagStatePoints is always sorted according to Loc.
234 assert((Loc.isValid() || DiagStatePoints.empty()) &&
235 "Adding invalid loc point after another point");
236 assert((Loc.isInvalid() || DiagStatePoints.empty() ||
237 DiagStatePoints.back().Loc.isInvalid() ||
238 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) &&
239 "Previous point loc comes after or is the same as new one");
240 DiagStatePoints.push_back(DiagStatePoint(State,
241 FullSourceLoc(Loc, *SourceMgr)));
244 /// \brief Finds the DiagStatePoint that contains the diagnostic state of
245 /// the given source location.
246 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const;
248 /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or
249 /// fatal error is emitted, and is sticky.
251 bool FatalErrorOccurred;
253 /// LastDiagLevel - This is the level of the last diagnostic emitted. This is
254 /// used to emit continuation diagnostics with the same level as the
255 /// diagnostic that they follow.
256 DiagnosticIDs::Level LastDiagLevel;
258 unsigned NumWarnings; // Number of warnings reported
259 unsigned NumErrors; // Number of errors reported
260 unsigned NumErrorsSuppressed; // Number of errors suppressed
262 /// ArgToStringFn - A function pointer that converts an opaque diagnostic
263 /// argument to a strings. This takes the modifiers and argument that was
264 /// present in the diagnostic.
266 /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
267 /// arguments formatted for this diagnostic. Implementations of this function
268 /// can use this information to avoid redundancy across arguments.
270 /// This is a hack to avoid a layering violation between libbasic and libsema.
271 typedef void (*ArgToStringFnTy)(ArgumentKind Kind, intptr_t Val,
272 const char *Modifier, unsigned ModifierLen,
273 const char *Argument, unsigned ArgumentLen,
274 const ArgumentValue *PrevArgs,
275 unsigned NumPrevArgs,
276 llvm::SmallVectorImpl<char> &Output,
278 void *ArgToStringCookie;
279 ArgToStringFnTy ArgToStringFn;
281 /// \brief ID of the "delayed" diagnostic, which is a (typically
282 /// fatal) diagnostic that had to be delayed because it was found
283 /// while emitting another diagnostic.
284 unsigned DelayedDiagID;
286 /// \brief First string argument for the delayed diagnostic.
287 std::string DelayedDiagArg1;
289 /// \brief Second string argument for the delayed diagnostic.
290 std::string DelayedDiagArg2;
293 explicit Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
294 DiagnosticClient *client = 0,
295 bool ShouldOwnClient = true);
298 const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
302 DiagnosticClient *getClient() { return Client; }
303 const DiagnosticClient *getClient() const { return Client; }
305 /// \brief Return the current diagnostic client along with ownership of that
307 DiagnosticClient *takeClient() {
308 OwnsDiagClient = false;
312 bool hasSourceManager() const { return SourceMgr != 0; }
313 SourceManager &getSourceManager() const {
314 assert(SourceMgr && "SourceManager not set!");
317 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
319 //===--------------------------------------------------------------------===//
320 // Diagnostic characterization methods, used by a client to customize how
321 // diagnostics are emitted.
324 /// pushMappings - Copies the current DiagMappings and pushes the new copy
325 /// onto the top of the stack.
326 void pushMappings(SourceLocation Loc);
328 /// popMappings - Pops the current DiagMappings off the top of the stack
329 /// causing the new top of the stack to be the active mappings. Returns
330 /// true if the pop happens, false if there is only one DiagMapping on the
332 bool popMappings(SourceLocation Loc);
334 /// \brief Set the diagnostic client associated with this diagnostic object.
336 /// \param ShouldOwnClient true if the diagnostic object should take
337 /// ownership of \c client.
338 void setClient(DiagnosticClient *client, bool ShouldOwnClient = true);
340 /// setErrorLimit - Specify a limit for the number of errors we should
341 /// emit before giving up. Zero disables the limit.
342 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
344 /// \brief Specify the maximum number of template instantiation
345 /// notes to emit along with a given diagnostic.
346 void setTemplateBacktraceLimit(unsigned Limit) {
347 TemplateBacktraceLimit = Limit;
350 /// \brief Retrieve the maximum number of template instantiation
351 /// nodes to emit along with a given diagnostic.
352 unsigned getTemplateBacktraceLimit() const {
353 return TemplateBacktraceLimit;
356 /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
357 /// ignored. If this and WarningsAsErrors are both set, then this one wins.
358 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
359 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
361 /// setWarningsAsErrors - When set to true, any warnings reported are issued
363 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
364 bool getWarningsAsErrors() const { return WarningsAsErrors; }
366 /// setErrorsAsFatal - When set to true, any error reported is made a
368 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
369 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
371 /// setSuppressSystemWarnings - When set to true mask warnings that
372 /// come from system headers.
373 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
374 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
376 /// \brief Suppress all diagnostics, to silence the front end when we
377 /// know that we don't want any more diagnostics to be passed along to the
379 void setSuppressAllDiagnostics(bool Val = true) {
380 SuppressAllDiagnostics = Val;
382 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
384 /// \brief Specify which overload candidates to show when overload resolution
385 /// fails. By default, we show all candidates.
386 void setShowOverloads(OverloadsShown Val) {
389 OverloadsShown getShowOverloads() const { return ShowOverloads; }
391 /// \brief Pretend that the last diagnostic issued was ignored. This can
392 /// be used by clients who suppress diagnostics themselves.
393 void setLastDiagnosticIgnored() {
394 LastDiagLevel = DiagnosticIDs::Ignored;
397 /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
398 /// extension diagnostics are mapped onto ignore/warning/error. This
399 /// corresponds to the GCC -pedantic and -pedantic-errors option.
400 void setExtensionHandlingBehavior(ExtensionHandling H) {
404 /// AllExtensionsSilenced - This is a counter bumped when an __extension__
405 /// block is encountered. When non-zero, all extension diagnostics are
406 /// entirely silenced, no matter how they are mapped.
407 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
408 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
409 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
411 /// \brief This allows the client to specify that certain
412 /// warnings are ignored. Notes can never be mapped, errors can only be
413 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
415 /// \param Loc The source location that this change of diagnostic state should
416 /// take affect. It can be null if we are setting the latest state.
417 void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
420 /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
421 /// "unknown-pragmas" to have the specified mapping. This returns true and
422 /// ignores the request if "Group" was unknown, false otherwise.
424 /// 'Loc' is the source location that this change of diagnostic state should
425 /// take affect. It can be null if we are setting the state from command-line.
426 bool setDiagnosticGroupMapping(const char *Group, diag::Mapping Map,
427 SourceLocation Loc = SourceLocation()) {
428 return Diags->setDiagnosticGroupMapping(Group, Map, Loc, *this);
431 bool hasErrorOccurred() const { return ErrorOccurred; }
432 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
434 unsigned getNumWarnings() const { return NumWarnings; }
436 void setNumWarnings(unsigned NumWarnings) {
437 this->NumWarnings = NumWarnings;
440 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
441 /// and level. If this is the first request for this diagnosic, it is
442 /// registered and created, otherwise the existing ID is returned.
443 unsigned getCustomDiagID(Level L, llvm::StringRef Message) {
444 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
447 /// ConvertArgToString - This method converts a diagnostic argument (as an
448 /// intptr_t) into the string that represents it.
449 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
450 const char *Modifier, unsigned ModLen,
451 const char *Argument, unsigned ArgLen,
452 const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
453 llvm::SmallVectorImpl<char> &Output) const {
454 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
455 PrevArgs, NumPrevArgs, Output, ArgToStringCookie);
458 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
460 ArgToStringCookie = Cookie;
463 /// \brief Reset the state of the diagnostic object to its initial
467 //===--------------------------------------------------------------------===//
468 // Diagnostic classification and reporting interfaces.
471 /// \brief Based on the way the client configured the Diagnostic
472 /// object, classify the specified diagnostic ID into a Level, consumable by
473 /// the DiagnosticClient.
475 /// \param Loc The source location we are interested in finding out the
476 /// diagnostic state. Can be null in order to query the latest state.
477 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
478 diag::Mapping *mapping = 0) const {
479 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this, mapping);
482 /// Report - Issue the message to the client. @c DiagID is a member of the
483 /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder
484 /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
485 /// @c Pos represents the source location associated with the diagnostic,
486 /// which can be an invalid location if no position information is available.
487 inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID);
488 inline DiagnosticBuilder Report(unsigned DiagID);
490 /// \brief Determine whethere there is already a diagnostic in flight.
491 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
493 /// \brief Set the "delayed" diagnostic that will be emitted once
494 /// the current diagnostic completes.
496 /// If a diagnostic is already in-flight but the front end must
497 /// report a problem (e.g., with an inconsistent file system
498 /// state), this routine sets a "delayed" diagnostic that will be
499 /// emitted after the current diagnostic completes. This should
500 /// only be used for fatal errors detected at inconvenient
501 /// times. If emitting a delayed diagnostic causes a second delayed
502 /// diagnostic to be introduced, that second delayed diagnostic
505 /// \param DiagID The ID of the diagnostic being delayed.
507 /// \param Arg1 A string argument that will be provided to the
508 /// diagnostic. A copy of this string will be stored in the
509 /// Diagnostic object itself.
511 /// \param Arg2 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.
514 void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "",
515 llvm::StringRef Arg2 = "");
517 /// \brief Clear out the current diagnostic.
518 void Clear() { CurDiagID = ~0U; }
521 /// \brief Report the delayed diagnostic.
522 void ReportDelayed();
525 /// getDiagnosticMappingInfo - Return the mapping info currently set for the
526 /// specified builtin diagnostic. This returns the high bit encoding, or zero
527 /// if the field is completely uninitialized.
528 diag::Mapping getDiagnosticMappingInfo(diag::kind Diag,
529 DiagState *State) const {
530 return State->getMapping(Diag);
533 void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
535 bool isUser, bool isPragma) const {
536 if (isUser) Map |= 8; // Set the high bit for user mappings.
537 if (isPragma) Map |= 0x10; // Set the bit for diagnostic pragma mappings.
538 State->setMapping((diag::kind)DiagId, Map);
541 // This is private state used by DiagnosticBuilder. We put it here instead of
542 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
543 // object. This implementation choice means that we can only have one
544 // diagnostic "in flight" at a time, but this seems to be a reasonable
545 // tradeoff to keep these objects small. Assertions verify that only one
546 // diagnostic is in flight at a time.
547 friend class DiagnosticIDs;
548 friend class DiagnosticBuilder;
549 friend class DiagnosticInfo;
550 friend class PartialDiagnostic;
551 friend class DiagnosticErrorTrap;
553 /// CurDiagLoc - This is the location of the current diagnostic that is in
555 SourceLocation CurDiagLoc;
557 /// CurDiagID - This is the ID of the current diagnostic that is in flight.
558 /// This is set to ~0U when there is no diagnostic in flight.
562 /// MaxArguments - The maximum number of arguments we can hold. We currently
563 /// only support up to 10 arguments (%0-%9). A single diagnostic with more
564 /// than that almost certainly has to be simplified anyway.
568 /// NumDiagArgs - This contains the number of entries in Arguments.
569 signed char NumDiagArgs;
570 /// NumRanges - This is the number of ranges in the DiagRanges array.
571 unsigned char NumDiagRanges;
572 /// \brief The number of code modifications hints in the
573 /// FixItHints array.
574 unsigned char NumFixItHints;
576 /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
577 /// values, with one for each argument. This specifies whether the argument
578 /// is in DiagArgumentsStr or in DiagArguments.
579 unsigned char DiagArgumentsKind[MaxArguments];
581 /// DiagArgumentsStr - This holds the values of each string argument for the
582 /// current diagnostic. This value is only used when the corresponding
583 /// ArgumentKind is ak_std_string.
584 std::string DiagArgumentsStr[MaxArguments];
586 /// DiagArgumentsVal - The values for the various substitution positions. This
587 /// is used when the argument is not an std::string. The specific value is
588 /// mangled into an intptr_t and the interpretation depends on exactly what
589 /// sort of argument kind it is.
590 intptr_t DiagArgumentsVal[MaxArguments];
592 /// DiagRanges - The list of ranges added to this diagnostic. It currently
593 /// only support 10 ranges, could easily be extended if needed.
594 CharSourceRange DiagRanges[10];
596 enum { MaxFixItHints = 3 };
598 /// FixItHints - If valid, provides a hint with some code
599 /// to insert, remove, or modify at a particular position.
600 FixItHint FixItHints[MaxFixItHints];
602 /// ProcessDiag - This is the method used to report a diagnostic that is
603 /// finally fully formed.
605 /// \returns true if the diagnostic was emitted, false if it was
608 return Diags->ProcessDiag(*this);
611 friend class ASTReader;
612 friend class ASTWriter;
615 /// \brief RAII class that determines when any errors have occurred
616 /// between the time the instance was created and the time it was
618 class DiagnosticErrorTrap {
623 explicit DiagnosticErrorTrap(Diagnostic &Diag)
624 : Diag(Diag), PrevErrors(Diag.NumErrors) {}
626 /// \brief Determine whether any errors have occurred since this
627 /// object instance was created.
628 bool hasErrorOccurred() const {
629 return Diag.NumErrors > PrevErrors;
632 // Set to initial state of "no errors occurred".
633 void reset() { PrevErrors = Diag.NumErrors; }
636 //===----------------------------------------------------------------------===//
638 //===----------------------------------------------------------------------===//
640 /// DiagnosticBuilder - This is a little helper class used to produce
641 /// diagnostics. This is constructed by the Diagnostic::Report method, and
642 /// allows insertion of extra information (arguments and source ranges) into the
643 /// currently "in flight" diagnostic. When the temporary for the builder is
644 /// destroyed, the diagnostic is issued.
646 /// Note that many of these will be created as temporary objects (many call
647 /// sites), so we want them to be small and we never want their address taken.
648 /// This ensures that compilers with somewhat reasonable optimizers will promote
649 /// the common fields to registers, eliminating increments of the NumArgs field,
651 class DiagnosticBuilder {
652 mutable Diagnostic *DiagObj;
653 mutable unsigned NumArgs, NumRanges, NumFixItHints;
655 void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
656 friend class Diagnostic;
657 explicit DiagnosticBuilder(Diagnostic *diagObj)
658 : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
660 friend class PartialDiagnostic;
666 /// Copy constructor. When copied, this "takes" the diagnostic info from the
667 /// input and neuters it.
668 DiagnosticBuilder(const DiagnosticBuilder &D) {
672 NumRanges = D.NumRanges;
673 NumFixItHints = D.NumFixItHints;
676 /// \brief Simple enumeration value used to give a name to the
677 /// suppress-diagnostic constructor.
678 enum SuppressKind { Suppress };
680 /// \brief Create an empty DiagnosticBuilder object that represents
681 /// no actual diagnostic.
682 explicit DiagnosticBuilder(SuppressKind)
683 : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
685 /// \brief Force the diagnostic builder to emit the diagnostic now.
687 /// Once this function has been called, the DiagnosticBuilder object
688 /// should not be used again before it is destroyed.
690 /// \returns true if a diagnostic was emitted, false if the
691 /// diagnostic was suppressed.
694 /// Destructor - The dtor emits the diagnostic if it hasn't already
696 ~DiagnosticBuilder() { Emit(); }
698 /// isActive - Determine whether this diagnostic is still active.
699 bool isActive() const { return DiagObj != 0; }
701 /// \brief Retrieve the active diagnostic ID.
703 /// \pre \c isActive()
704 unsigned getDiagID() const {
705 assert(isActive() && "Diagnostic is inactive");
706 return DiagObj->CurDiagID;
709 /// \brief Clear out the current diagnostic.
710 void Clear() { DiagObj = 0; }
712 /// Operator bool: conversion of DiagnosticBuilder to bool always returns
713 /// true. This allows is to be used in boolean error contexts like:
714 /// return Diag(...);
715 operator bool() const { return true; }
717 void AddString(llvm::StringRef S) const {
718 assert(NumArgs < Diagnostic::MaxArguments &&
719 "Too many arguments to diagnostic!");
721 DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
722 DiagObj->DiagArgumentsStr[NumArgs++] = S;
726 void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
727 assert(NumArgs < Diagnostic::MaxArguments &&
728 "Too many arguments to diagnostic!");
730 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
731 DiagObj->DiagArgumentsVal[NumArgs++] = V;
735 void AddSourceRange(const CharSourceRange &R) const {
737 sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
738 "Too many arguments to diagnostic!");
740 DiagObj->DiagRanges[NumRanges++] = R;
743 void AddFixItHint(const FixItHint &Hint) const {
744 assert(NumFixItHints < Diagnostic::MaxFixItHints &&
745 "Too many fix-it hints!");
747 DiagObj->FixItHints[NumFixItHints++] = Hint;
751 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
757 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
759 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
760 Diagnostic::ak_c_string);
764 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
765 DB.AddTaggedVal(I, Diagnostic::ak_sint);
769 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
770 DB.AddTaggedVal(I, Diagnostic::ak_sint);
774 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
776 DB.AddTaggedVal(I, Diagnostic::ak_uint);
780 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
781 const IdentifierInfo *II) {
782 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
783 Diagnostic::ak_identifierinfo);
787 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
788 // so that we only match those arguments that are (statically) DeclContexts;
789 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
793 typename llvm::enable_if<llvm::is_same<T, DeclContext>,
794 const DiagnosticBuilder &>::type
795 operator<<(const DiagnosticBuilder &DB, T *DC) {
796 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
797 Diagnostic::ak_declcontext);
801 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
802 const SourceRange &R) {
803 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
807 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
808 const CharSourceRange &R) {
809 DB.AddSourceRange(R);
813 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
814 const FixItHint &Hint) {
815 DB.AddFixItHint(Hint);
819 /// Report - Issue the message to the client. DiagID is a member of the
820 /// diag::kind enum. This actually returns a new instance of DiagnosticBuilder
821 /// which emits the diagnostics (through ProcessDiag) when it is destroyed.
822 inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc,
824 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
827 return DiagnosticBuilder(this);
829 inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
830 return Report(SourceLocation(), DiagID);
833 //===----------------------------------------------------------------------===//
835 //===----------------------------------------------------------------------===//
837 /// DiagnosticInfo - This is a little helper class (which is basically a smart
838 /// pointer that forward info from Diagnostic) that allows clients to enquire
839 /// about the currently in-flight diagnostic.
840 class DiagnosticInfo {
841 const Diagnostic *DiagObj;
843 explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
845 const Diagnostic *getDiags() const { return DiagObj; }
846 unsigned getID() const { return DiagObj->CurDiagID; }
847 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
848 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
849 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
851 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
853 /// getArgKind - Return the kind of the specified index. Based on the kind
854 /// of argument, the accessors below can be used to get the value.
855 Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
856 assert(Idx < getNumArgs() && "Argument index out of range!");
857 return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
860 /// getArgStdStr - Return the provided argument string specified by Idx.
861 const std::string &getArgStdStr(unsigned Idx) const {
862 assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
863 "invalid argument accessor!");
864 return DiagObj->DiagArgumentsStr[Idx];
867 /// getArgCStr - Return the specified C string argument.
868 const char *getArgCStr(unsigned Idx) const {
869 assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
870 "invalid argument accessor!");
871 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
874 /// getArgSInt - Return the specified signed integer argument.
875 int getArgSInt(unsigned Idx) const {
876 assert(getArgKind(Idx) == Diagnostic::ak_sint &&
877 "invalid argument accessor!");
878 return (int)DiagObj->DiagArgumentsVal[Idx];
881 /// getArgUInt - Return the specified unsigned integer argument.
882 unsigned getArgUInt(unsigned Idx) const {
883 assert(getArgKind(Idx) == Diagnostic::ak_uint &&
884 "invalid argument accessor!");
885 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
888 /// getArgIdentifier - Return the specified IdentifierInfo argument.
889 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
890 assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
891 "invalid argument accessor!");
892 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
895 /// getRawArg - Return the specified non-string argument in an opaque form.
896 intptr_t getRawArg(unsigned Idx) const {
897 assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
898 "invalid argument accessor!");
899 return DiagObj->DiagArgumentsVal[Idx];
903 /// getNumRanges - Return the number of source ranges associated with this
905 unsigned getNumRanges() const {
906 return DiagObj->NumDiagRanges;
909 const CharSourceRange &getRange(unsigned Idx) const {
910 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
911 return DiagObj->DiagRanges[Idx];
914 unsigned getNumFixItHints() const {
915 return DiagObj->NumFixItHints;
918 const FixItHint &getFixItHint(unsigned Idx) const {
919 return DiagObj->FixItHints[Idx];
922 const FixItHint *getFixItHints() const {
923 return DiagObj->NumFixItHints?
924 &DiagObj->FixItHints[0] : 0;
927 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
928 /// formal arguments into the %0 slots. The result is appended onto the Str
930 void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
932 /// FormatDiagnostic - Format the given format-string into the
933 /// output buffer using the arguments stored in this diagnostic.
934 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
935 llvm::SmallVectorImpl<char> &OutStr) const;
939 * \brief Represents a diagnostic in a form that can be retained until its
940 * corresponding source manager is destroyed.
942 class StoredDiagnostic {
944 Diagnostic::Level Level;
947 std::vector<CharSourceRange> Ranges;
948 std::vector<FixItHint> FixIts;
952 StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
953 StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
954 llvm::StringRef Message);
957 /// \brief Evaluates true when this object stores a diagnostic.
958 operator bool() const { return Message.size() > 0; }
960 unsigned getID() const { return ID; }
961 Diagnostic::Level getLevel() const { return Level; }
962 const FullSourceLoc &getLocation() const { return Loc; }
963 llvm::StringRef getMessage() const { return Message; }
965 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
967 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
968 range_iterator range_begin() const { return Ranges.begin(); }
969 range_iterator range_end() const { return Ranges.end(); }
970 unsigned range_size() const { return Ranges.size(); }
972 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
973 fixit_iterator fixit_begin() const { return FixIts.begin(); }
974 fixit_iterator fixit_end() const { return FixIts.end(); }
975 unsigned fixit_size() const { return FixIts.size(); }
978 /// DiagnosticClient - This is an abstract interface implemented by clients of
979 /// the front-end, which formats and prints fully processed diagnostics.
980 class DiagnosticClient {
982 unsigned NumWarnings; // Number of warnings reported
983 unsigned NumErrors; // Number of errors reported
986 DiagnosticClient() : NumWarnings(0), NumErrors(0) { }
988 unsigned getNumErrors() const { return NumErrors; }
989 unsigned getNumWarnings() const { return NumWarnings; }
991 virtual ~DiagnosticClient();
993 /// BeginSourceFile - Callback to inform the diagnostic client that processing
994 /// of a source file is beginning.
996 /// Note that diagnostics may be emitted outside the processing of a source
997 /// file, for example during the parsing of command line options. However,
998 /// diagnostics with source range information are required to only be emitted
999 /// in between BeginSourceFile() and EndSourceFile().
1001 /// \arg LO - The language options for the source file being processed.
1002 /// \arg PP - The preprocessor object being used for the source; this optional
1003 /// and may not be present, for example when processing AST source files.
1004 virtual void BeginSourceFile(const LangOptions &LangOpts,
1005 const Preprocessor *PP = 0) {}
1007 /// EndSourceFile - Callback to inform the diagnostic client that processing
1008 /// of a source file has ended. The diagnostic client should assume that any
1009 /// objects made available via \see BeginSourceFile() are inaccessible.
1010 virtual void EndSourceFile() {}
1012 /// IncludeInDiagnosticCounts - This method (whose default implementation
1013 /// returns true) indicates whether the diagnostics handled by this
1014 /// DiagnosticClient should be included in the number of diagnostics reported
1016 virtual bool IncludeInDiagnosticCounts() const;
1018 /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1019 /// capturing it to a log as needed.
1021 /// Default implementation just keeps track of the total number of warnings
1023 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1024 const DiagnosticInfo &Info);
1027 } // end namespace clang