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 /// \brief Indicates that an unrecoverable error has occurred.
255 bool UnrecoverableErrorOccurred;
257 /// \brief Toggles for DiagnosticErrorTrap to check whether an error occurred
258 /// during a parsing section, e.g. during parsing a function.
259 bool TrapErrorOccurred;
260 bool TrapUnrecoverableErrorOccurred;
262 /// LastDiagLevel - This is the level of the last diagnostic emitted. This is
263 /// used to emit continuation diagnostics with the same level as the
264 /// diagnostic that they follow.
265 DiagnosticIDs::Level LastDiagLevel;
267 unsigned NumWarnings; // Number of warnings reported
268 unsigned NumErrors; // Number of errors reported
269 unsigned NumErrorsSuppressed; // Number of errors suppressed
271 /// ArgToStringFn - A function pointer that converts an opaque diagnostic
272 /// argument to a strings. This takes the modifiers and argument that was
273 /// present in the diagnostic.
275 /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous
276 /// arguments formatted for this diagnostic. Implementations of this function
277 /// can use this information to avoid redundancy across arguments.
279 /// This is a hack to avoid a layering violation between libbasic and libsema.
280 typedef void (*ArgToStringFnTy)(
281 ArgumentKind Kind, intptr_t Val,
282 const char *Modifier, unsigned ModifierLen,
283 const char *Argument, unsigned ArgumentLen,
284 const ArgumentValue *PrevArgs,
285 unsigned NumPrevArgs,
286 llvm::SmallVectorImpl<char> &Output,
288 llvm::SmallVectorImpl<intptr_t> &QualTypeVals);
289 void *ArgToStringCookie;
290 ArgToStringFnTy ArgToStringFn;
292 /// \brief ID of the "delayed" diagnostic, which is a (typically
293 /// fatal) diagnostic that had to be delayed because it was found
294 /// while emitting another diagnostic.
295 unsigned DelayedDiagID;
297 /// \brief First string argument for the delayed diagnostic.
298 std::string DelayedDiagArg1;
300 /// \brief Second string argument for the delayed diagnostic.
301 std::string DelayedDiagArg2;
304 explicit Diagnostic(const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &Diags,
305 DiagnosticClient *client = 0,
306 bool ShouldOwnClient = true);
309 const llvm::IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const {
313 DiagnosticClient *getClient() { return Client; }
314 const DiagnosticClient *getClient() const { return Client; }
316 /// \brief Return the current diagnostic client along with ownership of that
318 DiagnosticClient *takeClient() {
319 OwnsDiagClient = false;
323 bool hasSourceManager() const { return SourceMgr != 0; }
324 SourceManager &getSourceManager() const {
325 assert(SourceMgr && "SourceManager not set!");
328 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; }
330 //===--------------------------------------------------------------------===//
331 // Diagnostic characterization methods, used by a client to customize how
332 // diagnostics are emitted.
335 /// pushMappings - Copies the current DiagMappings and pushes the new copy
336 /// onto the top of the stack.
337 void pushMappings(SourceLocation Loc);
339 /// popMappings - Pops the current DiagMappings off the top of the stack
340 /// causing the new top of the stack to be the active mappings. Returns
341 /// true if the pop happens, false if there is only one DiagMapping on the
343 bool popMappings(SourceLocation Loc);
345 /// \brief Set the diagnostic client associated with this diagnostic object.
347 /// \param ShouldOwnClient true if the diagnostic object should take
348 /// ownership of \c client.
349 void setClient(DiagnosticClient *client, bool ShouldOwnClient = true);
351 /// setErrorLimit - Specify a limit for the number of errors we should
352 /// emit before giving up. Zero disables the limit.
353 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; }
355 /// \brief Specify the maximum number of template instantiation
356 /// notes to emit along with a given diagnostic.
357 void setTemplateBacktraceLimit(unsigned Limit) {
358 TemplateBacktraceLimit = Limit;
361 /// \brief Retrieve the maximum number of template instantiation
362 /// nodes to emit along with a given diagnostic.
363 unsigned getTemplateBacktraceLimit() const {
364 return TemplateBacktraceLimit;
367 /// setIgnoreAllWarnings - When set to true, any unmapped warnings are
368 /// ignored. If this and WarningsAsErrors are both set, then this one wins.
369 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; }
370 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; }
372 /// setWarningsAsErrors - When set to true, any warnings reported are issued
374 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; }
375 bool getWarningsAsErrors() const { return WarningsAsErrors; }
377 /// setErrorsAsFatal - When set to true, any error reported is made a
379 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; }
380 bool getErrorsAsFatal() const { return ErrorsAsFatal; }
382 /// setSuppressSystemWarnings - When set to true mask warnings that
383 /// come from system headers.
384 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; }
385 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; }
387 /// \brief Suppress all diagnostics, to silence the front end when we
388 /// know that we don't want any more diagnostics to be passed along to the
390 void setSuppressAllDiagnostics(bool Val = true) {
391 SuppressAllDiagnostics = Val;
393 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; }
395 /// \brief Specify which overload candidates to show when overload resolution
396 /// fails. By default, we show all candidates.
397 void setShowOverloads(OverloadsShown Val) {
400 OverloadsShown getShowOverloads() const { return ShowOverloads; }
402 /// \brief Pretend that the last diagnostic issued was ignored. This can
403 /// be used by clients who suppress diagnostics themselves.
404 void setLastDiagnosticIgnored() {
405 LastDiagLevel = DiagnosticIDs::Ignored;
408 /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped
409 /// extension diagnostics are mapped onto ignore/warning/error. This
410 /// corresponds to the GCC -pedantic and -pedantic-errors option.
411 void setExtensionHandlingBehavior(ExtensionHandling H) {
414 ExtensionHandling getExtensionHandlingBehavior() const { return ExtBehavior; }
416 /// AllExtensionsSilenced - This is a counter bumped when an __extension__
417 /// block is encountered. When non-zero, all extension diagnostics are
418 /// entirely silenced, no matter how they are mapped.
419 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; }
420 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; }
421 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; }
423 /// \brief This allows the client to specify that certain
424 /// warnings are ignored. Notes can never be mapped, errors can only be
425 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily.
427 /// \param Loc The source location that this change of diagnostic state should
428 /// take affect. It can be null if we are setting the latest state.
429 void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map,
432 /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g.
433 /// "unknown-pragmas" to have the specified mapping. This returns true and
434 /// ignores the request if "Group" was unknown, false otherwise.
436 /// 'Loc' is the source location that this change of diagnostic state should
437 /// take affect. It can be null if we are setting the state from command-line.
438 bool setDiagnosticGroupMapping(llvm::StringRef Group, diag::Mapping Map,
439 SourceLocation Loc = SourceLocation()) {
440 return Diags->setDiagnosticGroupMapping(Group, Map, Loc, *this);
443 bool hasErrorOccurred() const { return ErrorOccurred; }
444 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; }
446 /// \brief Determine whether any kind of unrecoverable error has occurred.
447 bool hasUnrecoverableErrorOccurred() const {
448 return FatalErrorOccurred || UnrecoverableErrorOccurred;
451 unsigned getNumWarnings() const { return NumWarnings; }
453 void setNumWarnings(unsigned NumWarnings) {
454 this->NumWarnings = NumWarnings;
457 /// getCustomDiagID - Return an ID for a diagnostic with the specified message
458 /// and level. If this is the first request for this diagnosic, it is
459 /// registered and created, otherwise the existing ID is returned.
460 unsigned getCustomDiagID(Level L, llvm::StringRef Message) {
461 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message);
464 /// ConvertArgToString - This method converts a diagnostic argument (as an
465 /// intptr_t) into the string that represents it.
466 void ConvertArgToString(ArgumentKind Kind, intptr_t Val,
467 const char *Modifier, unsigned ModLen,
468 const char *Argument, unsigned ArgLen,
469 const ArgumentValue *PrevArgs, unsigned NumPrevArgs,
470 llvm::SmallVectorImpl<char> &Output,
471 llvm::SmallVectorImpl<intptr_t> &QualTypeVals) const {
472 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen,
473 PrevArgs, NumPrevArgs, Output, ArgToStringCookie,
477 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) {
479 ArgToStringCookie = Cookie;
482 /// \brief Reset the state of the diagnostic object to its initial
486 //===--------------------------------------------------------------------===//
487 // Diagnostic classification and reporting interfaces.
490 /// \brief Based on the way the client configured the Diagnostic
491 /// object, classify the specified diagnostic ID into a Level, consumable by
492 /// the DiagnosticClient.
494 /// \param Loc The source location we are interested in finding out the
495 /// diagnostic state. Can be null in order to query the latest state.
496 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc,
497 diag::Mapping *mapping = 0) const {
498 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this, mapping);
501 /// Report - Issue the message to the client. @c DiagID is a member of the
502 /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder
503 /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed.
504 /// @c Pos represents the source location associated with the diagnostic,
505 /// which can be an invalid location if no position information is available.
506 inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID);
507 inline DiagnosticBuilder Report(unsigned DiagID);
509 void Report(const StoredDiagnostic &storedDiag);
511 /// \brief Determine whethere there is already a diagnostic in flight.
512 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; }
514 /// \brief Set the "delayed" diagnostic that will be emitted once
515 /// the current diagnostic completes.
517 /// If a diagnostic is already in-flight but the front end must
518 /// report a problem (e.g., with an inconsistent file system
519 /// state), this routine sets a "delayed" diagnostic that will be
520 /// emitted after the current diagnostic completes. This should
521 /// only be used for fatal errors detected at inconvenient
522 /// times. If emitting a delayed diagnostic causes a second delayed
523 /// diagnostic to be introduced, that second delayed diagnostic
526 /// \param DiagID The ID of the diagnostic being delayed.
528 /// \param Arg1 A string argument that will be provided to the
529 /// diagnostic. A copy of this string will be stored in the
530 /// Diagnostic object itself.
532 /// \param Arg2 A string argument that will be provided to the
533 /// diagnostic. A copy of this string will be stored in the
534 /// Diagnostic object itself.
535 void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "",
536 llvm::StringRef Arg2 = "");
538 /// \brief Clear out the current diagnostic.
539 void Clear() { CurDiagID = ~0U; }
542 /// \brief Report the delayed diagnostic.
543 void ReportDelayed();
546 /// getDiagnosticMappingInfo - Return the mapping info currently set for the
547 /// specified builtin diagnostic. This returns the high bit encoding, or zero
548 /// if the field is completely uninitialized.
549 diag::Mapping getDiagnosticMappingInfo(diag::kind Diag,
550 DiagState *State) const {
551 return State->getMapping(Diag);
554 void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map,
556 bool isUser, bool isPragma) const {
557 if (isUser) Map |= 8; // Set the high bit for user mappings.
558 if (isPragma) Map |= 0x10; // Set the bit for diagnostic pragma mappings.
559 State->setMapping((diag::kind)DiagId, Map);
562 // This is private state used by DiagnosticBuilder. We put it here instead of
563 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight
564 // object. This implementation choice means that we can only have one
565 // diagnostic "in flight" at a time, but this seems to be a reasonable
566 // tradeoff to keep these objects small. Assertions verify that only one
567 // diagnostic is in flight at a time.
568 friend class DiagnosticIDs;
569 friend class DiagnosticBuilder;
570 friend class DiagnosticInfo;
571 friend class PartialDiagnostic;
572 friend class DiagnosticErrorTrap;
574 /// CurDiagLoc - This is the location of the current diagnostic that is in
576 SourceLocation CurDiagLoc;
578 /// CurDiagID - This is the ID of the current diagnostic that is in flight.
579 /// This is set to ~0U when there is no diagnostic in flight.
583 /// MaxArguments - The maximum number of arguments we can hold. We currently
584 /// only support up to 10 arguments (%0-%9). A single diagnostic with more
585 /// than that almost certainly has to be simplified anyway.
589 /// NumDiagArgs - This contains the number of entries in Arguments.
590 signed char NumDiagArgs;
591 /// NumRanges - This is the number of ranges in the DiagRanges array.
592 unsigned char NumDiagRanges;
593 /// \brief The number of code modifications hints in the
594 /// FixItHints array.
595 unsigned char NumFixItHints;
597 /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum
598 /// values, with one for each argument. This specifies whether the argument
599 /// is in DiagArgumentsStr or in DiagArguments.
600 unsigned char DiagArgumentsKind[MaxArguments];
602 /// DiagArgumentsStr - This holds the values of each string argument for the
603 /// current diagnostic. This value is only used when the corresponding
604 /// ArgumentKind is ak_std_string.
605 std::string DiagArgumentsStr[MaxArguments];
607 /// DiagArgumentsVal - The values for the various substitution positions. This
608 /// is used when the argument is not an std::string. The specific value is
609 /// mangled into an intptr_t and the interpretation depends on exactly what
610 /// sort of argument kind it is.
611 intptr_t DiagArgumentsVal[MaxArguments];
613 /// DiagRanges - The list of ranges added to this diagnostic. It currently
614 /// only support 10 ranges, could easily be extended if needed.
615 CharSourceRange DiagRanges[10];
617 enum { MaxFixItHints = 3 };
619 /// FixItHints - If valid, provides a hint with some code
620 /// to insert, remove, or modify at a particular position.
621 FixItHint FixItHints[MaxFixItHints];
623 /// ProcessDiag - This is the method used to report a diagnostic that is
624 /// finally fully formed.
626 /// \returns true if the diagnostic was emitted, false if it was
629 return Diags->ProcessDiag(*this);
632 friend class ASTReader;
633 friend class ASTWriter;
636 /// \brief RAII class that determines when any errors have occurred
637 /// between the time the instance was created and the time it was
639 class DiagnosticErrorTrap {
643 explicit DiagnosticErrorTrap(Diagnostic &Diag)
644 : Diag(Diag) { reset(); }
646 /// \brief Determine whether any errors have occurred since this
647 /// object instance was created.
648 bool hasErrorOccurred() const {
649 return Diag.TrapErrorOccurred;
652 /// \brief Determine whether any unrecoverable errors have occurred since this
653 /// object instance was created.
654 bool hasUnrecoverableErrorOccurred() const {
655 return Diag.TrapUnrecoverableErrorOccurred;
658 // Set to initial state of "no errors occurred".
660 Diag.TrapErrorOccurred = false;
661 Diag.TrapUnrecoverableErrorOccurred = false;
665 //===----------------------------------------------------------------------===//
667 //===----------------------------------------------------------------------===//
669 /// DiagnosticBuilder - This is a little helper class used to produce
670 /// diagnostics. This is constructed by the Diagnostic::Report method, and
671 /// allows insertion of extra information (arguments and source ranges) into the
672 /// currently "in flight" diagnostic. When the temporary for the builder is
673 /// destroyed, the diagnostic is issued.
675 /// Note that many of these will be created as temporary objects (many call
676 /// sites), so we want them to be small and we never want their address taken.
677 /// This ensures that compilers with somewhat reasonable optimizers will promote
678 /// the common fields to registers, eliminating increments of the NumArgs field,
680 class DiagnosticBuilder {
681 mutable Diagnostic *DiagObj;
682 mutable unsigned NumArgs, NumRanges, NumFixItHints;
684 void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT
685 friend class Diagnostic;
686 explicit DiagnosticBuilder(Diagnostic *diagObj)
687 : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {}
689 friend class PartialDiagnostic;
695 /// Copy constructor. When copied, this "takes" the diagnostic info from the
696 /// input and neuters it.
697 DiagnosticBuilder(const DiagnosticBuilder &D) {
701 NumRanges = D.NumRanges;
702 NumFixItHints = D.NumFixItHints;
705 /// \brief Simple enumeration value used to give a name to the
706 /// suppress-diagnostic constructor.
707 enum SuppressKind { Suppress };
709 /// \brief Create an empty DiagnosticBuilder object that represents
710 /// no actual diagnostic.
711 explicit DiagnosticBuilder(SuppressKind)
712 : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { }
714 /// \brief Force the diagnostic builder to emit the diagnostic now.
716 /// Once this function has been called, the DiagnosticBuilder object
717 /// should not be used again before it is destroyed.
719 /// \returns true if a diagnostic was emitted, false if the
720 /// diagnostic was suppressed.
723 /// Destructor - The dtor emits the diagnostic if it hasn't already
725 ~DiagnosticBuilder() { Emit(); }
727 /// isActive - Determine whether this diagnostic is still active.
728 bool isActive() const { return DiagObj != 0; }
730 /// \brief Retrieve the active diagnostic ID.
732 /// \pre \c isActive()
733 unsigned getDiagID() const {
734 assert(isActive() && "Diagnostic is inactive");
735 return DiagObj->CurDiagID;
738 /// \brief Clear out the current diagnostic.
739 void Clear() { DiagObj = 0; }
741 /// Operator bool: conversion of DiagnosticBuilder to bool always returns
742 /// true. This allows is to be used in boolean error contexts like:
743 /// return Diag(...);
744 operator bool() const { return true; }
746 void AddString(llvm::StringRef S) const {
747 assert(NumArgs < Diagnostic::MaxArguments &&
748 "Too many arguments to diagnostic!");
750 DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string;
751 DiagObj->DiagArgumentsStr[NumArgs++] = S;
755 void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const {
756 assert(NumArgs < Diagnostic::MaxArguments &&
757 "Too many arguments to diagnostic!");
759 DiagObj->DiagArgumentsKind[NumArgs] = Kind;
760 DiagObj->DiagArgumentsVal[NumArgs++] = V;
764 void AddSourceRange(const CharSourceRange &R) const {
766 sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) &&
767 "Too many arguments to diagnostic!");
769 DiagObj->DiagRanges[NumRanges++] = R;
772 void AddFixItHint(const FixItHint &Hint) const {
773 assert(NumFixItHints < Diagnostic::MaxFixItHints &&
774 "Too many fix-it hints!");
776 DiagObj->FixItHints[NumFixItHints++] = Hint;
780 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
786 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
788 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str),
789 Diagnostic::ak_c_string);
793 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) {
794 DB.AddTaggedVal(I, Diagnostic::ak_sint);
798 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) {
799 DB.AddTaggedVal(I, Diagnostic::ak_sint);
803 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
805 DB.AddTaggedVal(I, Diagnostic::ak_uint);
809 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
810 const IdentifierInfo *II) {
811 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II),
812 Diagnostic::ak_identifierinfo);
816 // Adds a DeclContext to the diagnostic. The enable_if template magic is here
817 // so that we only match those arguments that are (statically) DeclContexts;
818 // other arguments that derive from DeclContext (e.g., RecordDecls) will not
822 typename llvm::enable_if<llvm::is_same<T, DeclContext>,
823 const DiagnosticBuilder &>::type
824 operator<<(const DiagnosticBuilder &DB, T *DC) {
825 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC),
826 Diagnostic::ak_declcontext);
830 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
831 const SourceRange &R) {
832 DB.AddSourceRange(CharSourceRange::getTokenRange(R));
836 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
837 const CharSourceRange &R) {
838 DB.AddSourceRange(R);
842 inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,
843 const FixItHint &Hint) {
844 DB.AddFixItHint(Hint);
848 /// Report - Issue the message to the client. DiagID is a member of the
849 /// diag::kind enum. This actually returns a new instance of DiagnosticBuilder
850 /// which emits the diagnostics (through ProcessDiag) when it is destroyed.
851 inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc,
853 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!");
856 return DiagnosticBuilder(this);
858 inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) {
859 return Report(SourceLocation(), DiagID);
862 //===----------------------------------------------------------------------===//
864 //===----------------------------------------------------------------------===//
866 /// DiagnosticInfo - This is a little helper class (which is basically a smart
867 /// pointer that forward info from Diagnostic) that allows clients to enquire
868 /// about the currently in-flight diagnostic.
869 class DiagnosticInfo {
870 const Diagnostic *DiagObj;
871 llvm::StringRef StoredDiagMessage;
873 explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {}
874 DiagnosticInfo(const Diagnostic *DO, llvm::StringRef storedDiagMessage)
875 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {}
877 const Diagnostic *getDiags() const { return DiagObj; }
878 unsigned getID() const { return DiagObj->CurDiagID; }
879 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; }
880 bool hasSourceManager() const { return DiagObj->hasSourceManager(); }
881 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();}
883 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; }
885 /// getArgKind - Return the kind of the specified index. Based on the kind
886 /// of argument, the accessors below can be used to get the value.
887 Diagnostic::ArgumentKind getArgKind(unsigned Idx) const {
888 assert(Idx < getNumArgs() && "Argument index out of range!");
889 return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx];
892 /// getArgStdStr - Return the provided argument string specified by Idx.
893 const std::string &getArgStdStr(unsigned Idx) const {
894 assert(getArgKind(Idx) == Diagnostic::ak_std_string &&
895 "invalid argument accessor!");
896 return DiagObj->DiagArgumentsStr[Idx];
899 /// getArgCStr - Return the specified C string argument.
900 const char *getArgCStr(unsigned Idx) const {
901 assert(getArgKind(Idx) == Diagnostic::ak_c_string &&
902 "invalid argument accessor!");
903 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]);
906 /// getArgSInt - Return the specified signed integer argument.
907 int getArgSInt(unsigned Idx) const {
908 assert(getArgKind(Idx) == Diagnostic::ak_sint &&
909 "invalid argument accessor!");
910 return (int)DiagObj->DiagArgumentsVal[Idx];
913 /// getArgUInt - Return the specified unsigned integer argument.
914 unsigned getArgUInt(unsigned Idx) const {
915 assert(getArgKind(Idx) == Diagnostic::ak_uint &&
916 "invalid argument accessor!");
917 return (unsigned)DiagObj->DiagArgumentsVal[Idx];
920 /// getArgIdentifier - Return the specified IdentifierInfo argument.
921 const IdentifierInfo *getArgIdentifier(unsigned Idx) const {
922 assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo &&
923 "invalid argument accessor!");
924 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]);
927 /// getRawArg - Return the specified non-string argument in an opaque form.
928 intptr_t getRawArg(unsigned Idx) const {
929 assert(getArgKind(Idx) != Diagnostic::ak_std_string &&
930 "invalid argument accessor!");
931 return DiagObj->DiagArgumentsVal[Idx];
935 /// getNumRanges - Return the number of source ranges associated with this
937 unsigned getNumRanges() const {
938 return DiagObj->NumDiagRanges;
941 const CharSourceRange &getRange(unsigned Idx) const {
942 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!");
943 return DiagObj->DiagRanges[Idx];
946 unsigned getNumFixItHints() const {
947 return DiagObj->NumFixItHints;
950 const FixItHint &getFixItHint(unsigned Idx) const {
951 return DiagObj->FixItHints[Idx];
954 const FixItHint *getFixItHints() const {
955 return DiagObj->NumFixItHints?
956 &DiagObj->FixItHints[0] : 0;
959 /// FormatDiagnostic - Format this diagnostic into a string, substituting the
960 /// formal arguments into the %0 slots. The result is appended onto the Str
962 void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const;
964 /// FormatDiagnostic - Format the given format-string into the
965 /// output buffer using the arguments stored in this diagnostic.
966 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd,
967 llvm::SmallVectorImpl<char> &OutStr) const;
971 * \brief Represents a diagnostic in a form that can be retained until its
972 * corresponding source manager is destroyed.
974 class StoredDiagnostic {
976 Diagnostic::Level Level;
979 std::vector<CharSourceRange> Ranges;
980 std::vector<FixItHint> FixIts;
984 StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info);
985 StoredDiagnostic(Diagnostic::Level Level, unsigned ID,
986 llvm::StringRef Message);
989 /// \brief Evaluates true when this object stores a diagnostic.
990 operator bool() const { return Message.size() > 0; }
992 unsigned getID() const { return ID; }
993 Diagnostic::Level getLevel() const { return Level; }
994 const FullSourceLoc &getLocation() const { return Loc; }
995 llvm::StringRef getMessage() const { return Message; }
997 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; }
999 typedef std::vector<CharSourceRange>::const_iterator range_iterator;
1000 range_iterator range_begin() const { return Ranges.begin(); }
1001 range_iterator range_end() const { return Ranges.end(); }
1002 unsigned range_size() const { return Ranges.size(); }
1004 typedef std::vector<FixItHint>::const_iterator fixit_iterator;
1005 fixit_iterator fixit_begin() const { return FixIts.begin(); }
1006 fixit_iterator fixit_end() const { return FixIts.end(); }
1007 unsigned fixit_size() const { return FixIts.size(); }
1010 /// DiagnosticClient - This is an abstract interface implemented by clients of
1011 /// the front-end, which formats and prints fully processed diagnostics.
1012 class DiagnosticClient {
1014 unsigned NumWarnings; // Number of warnings reported
1015 unsigned NumErrors; // Number of errors reported
1018 DiagnosticClient() : NumWarnings(0), NumErrors(0) { }
1020 unsigned getNumErrors() const { return NumErrors; }
1021 unsigned getNumWarnings() const { return NumWarnings; }
1023 virtual ~DiagnosticClient();
1025 /// BeginSourceFile - Callback to inform the diagnostic client that processing
1026 /// of a source file is beginning.
1028 /// Note that diagnostics may be emitted outside the processing of a source
1029 /// file, for example during the parsing of command line options. However,
1030 /// diagnostics with source range information are required to only be emitted
1031 /// in between BeginSourceFile() and EndSourceFile().
1033 /// \arg LO - The language options for the source file being processed.
1034 /// \arg PP - The preprocessor object being used for the source; this optional
1035 /// and may not be present, for example when processing AST source files.
1036 virtual void BeginSourceFile(const LangOptions &LangOpts,
1037 const Preprocessor *PP = 0) {}
1039 /// EndSourceFile - Callback to inform the diagnostic client that processing
1040 /// of a source file has ended. The diagnostic client should assume that any
1041 /// objects made available via \see BeginSourceFile() are inaccessible.
1042 virtual void EndSourceFile() {}
1044 /// IncludeInDiagnosticCounts - This method (whose default implementation
1045 /// returns true) indicates whether the diagnostics handled by this
1046 /// DiagnosticClient should be included in the number of diagnostics reported
1048 virtual bool IncludeInDiagnosticCounts() const;
1050 /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or
1051 /// capturing it to a log as needed.
1053 /// Default implementation just keeps track of the total number of warnings
1055 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel,
1056 const DiagnosticInfo &Info);
1059 } // end namespace clang