Diagnostic.h revision 341785ec52f87c0803ba52dc88faac4e136f8593
1//===--- Diagnostic.h - C Language Family Diagnostic Handling ---*- C++ -*-===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file defines the Diagnostic-related interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#ifndef LLVM_CLANG_DIAGNOSTIC_H 15#define LLVM_CLANG_DIAGNOSTIC_H 16 17#include "clang/Basic/DiagnosticIDs.h" 18#include "clang/Basic/SourceLocation.h" 19#include "llvm/ADT/ArrayRef.h" 20#include "llvm/ADT/DenseMap.h" 21#include "llvm/ADT/IntrusiveRefCntPtr.h" 22#include "llvm/ADT/OwningPtr.h" 23#include "llvm/Support/type_traits.h" 24 25#include <vector> 26#include <list> 27 28namespace clang { 29 class DiagnosticConsumer; 30 class DiagnosticBuilder; 31 class IdentifierInfo; 32 class DeclContext; 33 class LangOptions; 34 class Preprocessor; 35 class DiagnosticErrorTrap; 36 class StoredDiagnostic; 37 38/// \brief Annotates a diagnostic with some code that should be 39/// inserted, removed, or replaced to fix the problem. 40/// 41/// This kind of hint should be used when we are certain that the 42/// introduction, removal, or modification of a particular (small!) 43/// amount of code will correct a compilation error. The compiler 44/// should also provide full recovery from such errors, such that 45/// suppressing the diagnostic output can still result in successful 46/// compilation. 47class FixItHint { 48public: 49 /// \brief Code that should be replaced to correct the error. Empty for an 50 /// insertion hint. 51 CharSourceRange RemoveRange; 52 53 /// \brief The actual code to insert at the insertion location, as a 54 /// string. 55 std::string CodeToInsert; 56 57 /// \brief Empty code modification hint, indicating that no code 58 /// modification is known. 59 FixItHint() : RemoveRange() { } 60 61 bool isNull() const { 62 return !RemoveRange.isValid(); 63 } 64 65 /// \brief Create a code modification hint that inserts the given 66 /// code string at a specific location. 67 static FixItHint CreateInsertion(SourceLocation InsertionLoc, 68 StringRef Code) { 69 FixItHint Hint; 70 Hint.RemoveRange = 71 CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false); 72 Hint.CodeToInsert = Code; 73 return Hint; 74 } 75 76 /// \brief Create a code modification hint that removes the given 77 /// source range. 78 static FixItHint CreateRemoval(CharSourceRange RemoveRange) { 79 FixItHint Hint; 80 Hint.RemoveRange = RemoveRange; 81 return Hint; 82 } 83 static FixItHint CreateRemoval(SourceRange RemoveRange) { 84 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange)); 85 } 86 87 /// \brief Create a code modification hint that replaces the given 88 /// source range with the given code string. 89 static FixItHint CreateReplacement(CharSourceRange RemoveRange, 90 StringRef Code) { 91 FixItHint Hint; 92 Hint.RemoveRange = RemoveRange; 93 Hint.CodeToInsert = Code; 94 return Hint; 95 } 96 97 static FixItHint CreateReplacement(SourceRange RemoveRange, 98 StringRef Code) { 99 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code); 100 } 101}; 102 103/// DiagnosticsEngine - This concrete class is used by the front-end to report 104/// problems and issues. It massages the diagnostics (e.g. handling things like 105/// "report warnings as errors" and passes them off to the DiagnosticConsumer 106/// for reporting to the user. DiagnosticsEngine is tied to one translation unit 107/// and one SourceManager. 108class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> { 109public: 110 /// Level - The level of the diagnostic, after it has been through mapping. 111 enum Level { 112 Ignored = DiagnosticIDs::Ignored, 113 Note = DiagnosticIDs::Note, 114 Warning = DiagnosticIDs::Warning, 115 Error = DiagnosticIDs::Error, 116 Fatal = DiagnosticIDs::Fatal 117 }; 118 119 /// ExtensionHandling - How do we handle otherwise-unmapped extension? This 120 /// is controlled by -pedantic and -pedantic-errors. 121 enum ExtensionHandling { 122 Ext_Ignore, Ext_Warn, Ext_Error 123 }; 124 125 enum ArgumentKind { 126 ak_std_string, // std::string 127 ak_c_string, // const char * 128 ak_sint, // int 129 ak_uint, // unsigned 130 ak_identifierinfo, // IdentifierInfo 131 ak_qualtype, // QualType 132 ak_declarationname, // DeclarationName 133 ak_nameddecl, // NamedDecl * 134 ak_nestednamespec, // NestedNameSpecifier * 135 ak_declcontext // DeclContext * 136 }; 137 138 /// Specifies which overload candidates to display when overload resolution 139 /// fails. 140 enum OverloadsShown { 141 Ovl_All, ///< Show all overloads. 142 Ovl_Best ///< Show just the "best" overload candidates. 143 }; 144 145 /// ArgumentValue - This typedef represents on argument value, which is a 146 /// union discriminated by ArgumentKind, with a value. 147 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue; 148 149private: 150 unsigned char AllExtensionsSilenced; // Used by __extension__ 151 bool IgnoreAllWarnings; // Ignore all warnings: -w 152 bool WarningsAsErrors; // Treat warnings like errors. 153 bool EnableAllWarnings; // Enable all warnings. 154 bool ErrorsAsFatal; // Treat errors like fatal errors. 155 bool SuppressSystemWarnings; // Suppress warnings in system headers. 156 bool SuppressAllDiagnostics; // Suppress all diagnostics. 157 OverloadsShown ShowOverloads; // Which overload candidates to show. 158 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit. 159 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack, 160 // 0 -> no limit. 161 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation 162 // backtrace stack, 0 -> no limit. 163 ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors? 164 IntrusiveRefCntPtr<DiagnosticIDs> Diags; 165 DiagnosticConsumer *Client; 166 bool OwnsDiagClient; 167 SourceManager *SourceMgr; 168 169 /// \brief Mapping information for diagnostics. Mapping info is 170 /// packed into four bits per diagnostic. The low three bits are the mapping 171 /// (an instance of diag::Mapping), or zero if unset. The high bit is set 172 /// when the mapping was established as a user mapping. If the high bit is 173 /// clear, then the low bits are set to the default value, and should be 174 /// mapped with -pedantic, -Werror, etc. 175 /// 176 /// A new DiagState is created and kept around when diagnostic pragmas modify 177 /// the state so that we know what is the diagnostic state at any given 178 /// source location. 179 class DiagState { 180 llvm::DenseMap<unsigned, DiagnosticMappingInfo> DiagMap; 181 182 public: 183 typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::iterator 184 iterator; 185 typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::const_iterator 186 const_iterator; 187 188 void setMappingInfo(diag::kind Diag, DiagnosticMappingInfo Info) { 189 DiagMap[Diag] = Info; 190 } 191 192 DiagnosticMappingInfo &getOrAddMappingInfo(diag::kind Diag); 193 194 const_iterator begin() const { return DiagMap.begin(); } 195 const_iterator end() const { return DiagMap.end(); } 196 }; 197 198 /// \brief Keeps and automatically disposes all DiagStates that we create. 199 std::list<DiagState> DiagStates; 200 201 /// \brief Represents a point in source where the diagnostic state was 202 /// modified because of a pragma. 'Loc' can be null if the point represents 203 /// the diagnostic state modifications done through the command-line. 204 struct DiagStatePoint { 205 DiagState *State; 206 FullSourceLoc Loc; 207 DiagStatePoint(DiagState *State, FullSourceLoc Loc) 208 : State(State), Loc(Loc) { } 209 210 bool operator<(const DiagStatePoint &RHS) const { 211 // If Loc is invalid it means it came from <command-line>, in which case 212 // we regard it as coming before any valid source location. 213 if (RHS.Loc.isInvalid()) 214 return false; 215 if (Loc.isInvalid()) 216 return true; 217 return Loc.isBeforeInTranslationUnitThan(RHS.Loc); 218 } 219 }; 220 221 /// \brief A vector of all DiagStatePoints representing changes in diagnostic 222 /// state due to diagnostic pragmas. The vector is always sorted according to 223 /// the SourceLocation of the DiagStatePoint. 224 typedef std::vector<DiagStatePoint> DiagStatePointsTy; 225 mutable DiagStatePointsTy DiagStatePoints; 226 227 /// \brief Keeps the DiagState that was active during each diagnostic 'push' 228 /// so we can get back at it when we 'pop'. 229 std::vector<DiagState *> DiagStateOnPushStack; 230 231 DiagState *GetCurDiagState() const { 232 assert(!DiagStatePoints.empty()); 233 return DiagStatePoints.back().State; 234 } 235 236 void PushDiagStatePoint(DiagState *State, SourceLocation L) { 237 FullSourceLoc Loc(L, *SourceMgr); 238 // Make sure that DiagStatePoints is always sorted according to Loc. 239 assert((Loc.isValid() || DiagStatePoints.empty()) && 240 "Adding invalid loc point after another point"); 241 assert((Loc.isInvalid() || DiagStatePoints.empty() || 242 DiagStatePoints.back().Loc.isInvalid() || 243 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) && 244 "Previous point loc comes after or is the same as new one"); 245 DiagStatePoints.push_back(DiagStatePoint(State, 246 FullSourceLoc(Loc, *SourceMgr))); 247 } 248 249 /// \brief Finds the DiagStatePoint that contains the diagnostic state of 250 /// the given source location. 251 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const; 252 253 /// ErrorOccurred / FatalErrorOccurred - This is set to true when an error or 254 /// fatal error is emitted, and is sticky. 255 bool ErrorOccurred; 256 bool FatalErrorOccurred; 257 258 /// \brief Indicates that an unrecoverable error has occurred. 259 bool UnrecoverableErrorOccurred; 260 261 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred 262 /// during a parsing section, e.g. during parsing a function. 263 unsigned TrapNumErrorsOccurred; 264 unsigned TrapNumUnrecoverableErrorsOccurred; 265 266 /// LastDiagLevel - This is the level of the last diagnostic emitted. This is 267 /// used to emit continuation diagnostics with the same level as the 268 /// diagnostic that they follow. 269 DiagnosticIDs::Level LastDiagLevel; 270 271 unsigned NumWarnings; // Number of warnings reported 272 unsigned NumErrors; // Number of errors reported 273 unsigned NumErrorsSuppressed; // Number of errors suppressed 274 275 /// ArgToStringFn - A function pointer that converts an opaque diagnostic 276 /// argument to a strings. This takes the modifiers and argument that was 277 /// present in the diagnostic. 278 /// 279 /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous 280 /// arguments formatted for this diagnostic. Implementations of this function 281 /// can use this information to avoid redundancy across arguments. 282 /// 283 /// This is a hack to avoid a layering violation between libbasic and libsema. 284 typedef void (*ArgToStringFnTy)( 285 ArgumentKind Kind, intptr_t Val, 286 const char *Modifier, unsigned ModifierLen, 287 const char *Argument, unsigned ArgumentLen, 288 const ArgumentValue *PrevArgs, 289 unsigned NumPrevArgs, 290 SmallVectorImpl<char> &Output, 291 void *Cookie, 292 ArrayRef<intptr_t> QualTypeVals); 293 void *ArgToStringCookie; 294 ArgToStringFnTy ArgToStringFn; 295 296 /// \brief ID of the "delayed" diagnostic, which is a (typically 297 /// fatal) diagnostic that had to be delayed because it was found 298 /// while emitting another diagnostic. 299 unsigned DelayedDiagID; 300 301 /// \brief First string argument for the delayed diagnostic. 302 std::string DelayedDiagArg1; 303 304 /// \brief Second string argument for the delayed diagnostic. 305 std::string DelayedDiagArg2; 306 307public: 308 explicit DiagnosticsEngine( 309 const IntrusiveRefCntPtr<DiagnosticIDs> &Diags, 310 DiagnosticConsumer *client = 0, 311 bool ShouldOwnClient = true); 312 ~DiagnosticsEngine(); 313 314 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const { 315 return Diags; 316 } 317 318 DiagnosticConsumer *getClient() { return Client; } 319 const DiagnosticConsumer *getClient() const { return Client; } 320 321 /// \brief Determine whether this \c DiagnosticsEngine object own its client. 322 bool ownsClient() const { return OwnsDiagClient; } 323 324 /// \brief Return the current diagnostic client along with ownership of that 325 /// client. 326 DiagnosticConsumer *takeClient() { 327 OwnsDiagClient = false; 328 return Client; 329 } 330 331 bool hasSourceManager() const { return SourceMgr != 0; } 332 SourceManager &getSourceManager() const { 333 assert(SourceMgr && "SourceManager not set!"); 334 return *SourceMgr; 335 } 336 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; } 337 338 //===--------------------------------------------------------------------===// 339 // DiagnosticsEngine characterization methods, used by a client to customize 340 // how diagnostics are emitted. 341 // 342 343 /// pushMappings - Copies the current DiagMappings and pushes the new copy 344 /// onto the top of the stack. 345 void pushMappings(SourceLocation Loc); 346 347 /// popMappings - Pops the current DiagMappings off the top of the stack 348 /// causing the new top of the stack to be the active mappings. Returns 349 /// true if the pop happens, false if there is only one DiagMapping on the 350 /// stack. 351 bool popMappings(SourceLocation Loc); 352 353 /// \brief Set the diagnostic client associated with this diagnostic object. 354 /// 355 /// \param ShouldOwnClient true if the diagnostic object should take 356 /// ownership of \c client. 357 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true); 358 359 /// setErrorLimit - Specify a limit for the number of errors we should 360 /// emit before giving up. Zero disables the limit. 361 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; } 362 363 /// \brief Specify the maximum number of template instantiation 364 /// notes to emit along with a given diagnostic. 365 void setTemplateBacktraceLimit(unsigned Limit) { 366 TemplateBacktraceLimit = Limit; 367 } 368 369 /// \brief Retrieve the maximum number of template instantiation 370 /// notes to emit along with a given diagnostic. 371 unsigned getTemplateBacktraceLimit() const { 372 return TemplateBacktraceLimit; 373 } 374 375 /// \brief Specify the maximum number of constexpr evaluation 376 /// notes to emit along with a given diagnostic. 377 void setConstexprBacktraceLimit(unsigned Limit) { 378 ConstexprBacktraceLimit = Limit; 379 } 380 381 /// \brief Retrieve the maximum number of constexpr evaluation 382 /// notes to emit along with a given diagnostic. 383 unsigned getConstexprBacktraceLimit() const { 384 return ConstexprBacktraceLimit; 385 } 386 387 /// setIgnoreAllWarnings - When set to true, any unmapped warnings are 388 /// ignored. If this and WarningsAsErrors are both set, then this one wins. 389 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; } 390 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; } 391 392 /// setEnableAllWarnings - When set to true, any unmapped ignored warnings 393 /// are no longer ignored. If this and IgnoreAllWarnings are both set, 394 /// then that one wins. 395 void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; } 396 bool getEnableAllWarnngs() const { return EnableAllWarnings; } 397 398 /// setWarningsAsErrors - When set to true, any warnings reported are issued 399 /// as errors. 400 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; } 401 bool getWarningsAsErrors() const { return WarningsAsErrors; } 402 403 /// setErrorsAsFatal - When set to true, any error reported is made a 404 /// fatal error. 405 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; } 406 bool getErrorsAsFatal() const { return ErrorsAsFatal; } 407 408 /// setSuppressSystemWarnings - When set to true mask warnings that 409 /// come from system headers. 410 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; } 411 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; } 412 413 /// \brief Suppress all diagnostics, to silence the front end when we 414 /// know that we don't want any more diagnostics to be passed along to the 415 /// client 416 void setSuppressAllDiagnostics(bool Val = true) { 417 SuppressAllDiagnostics = Val; 418 } 419 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; } 420 421 /// \brief Specify which overload candidates to show when overload resolution 422 /// fails. By default, we show all candidates. 423 void setShowOverloads(OverloadsShown Val) { 424 ShowOverloads = Val; 425 } 426 OverloadsShown getShowOverloads() const { return ShowOverloads; } 427 428 /// \brief Pretend that the last diagnostic issued was ignored. This can 429 /// be used by clients who suppress diagnostics themselves. 430 void setLastDiagnosticIgnored() { 431 LastDiagLevel = DiagnosticIDs::Ignored; 432 } 433 434 /// setExtensionHandlingBehavior - This controls whether otherwise-unmapped 435 /// extension diagnostics are mapped onto ignore/warning/error. This 436 /// corresponds to the GCC -pedantic and -pedantic-errors option. 437 void setExtensionHandlingBehavior(ExtensionHandling H) { 438 ExtBehavior = H; 439 } 440 ExtensionHandling getExtensionHandlingBehavior() const { return ExtBehavior; } 441 442 /// AllExtensionsSilenced - This is a counter bumped when an __extension__ 443 /// block is encountered. When non-zero, all extension diagnostics are 444 /// entirely silenced, no matter how they are mapped. 445 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; } 446 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; } 447 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; } 448 449 /// \brief This allows the client to specify that certain 450 /// warnings are ignored. Notes can never be mapped, errors can only be 451 /// mapped to fatal, and WARNINGs and EXTENSIONs can be mapped arbitrarily. 452 /// 453 /// \param Loc The source location that this change of diagnostic state should 454 /// take affect. It can be null if we are setting the latest state. 455 void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map, 456 SourceLocation Loc); 457 458 /// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g. 459 /// "unknown-pragmas" to have the specified mapping. This returns true and 460 /// ignores the request if "Group" was unknown, false otherwise. 461 /// 462 /// 'Loc' is the source location that this change of diagnostic state should 463 /// take affect. It can be null if we are setting the state from command-line. 464 bool setDiagnosticGroupMapping(StringRef Group, diag::Mapping Map, 465 SourceLocation Loc = SourceLocation()); 466 467 /// \brief Set the warning-as-error flag for the given diagnostic. This 468 /// function always only operates on the current diagnostic state. 469 void setDiagnosticWarningAsError(diag::kind Diag, bool Enabled); 470 471 /// \brief Set the warning-as-error flag for the given diagnostic group. This 472 /// function always only operates on the current diagnostic state. 473 /// 474 /// \returns True if the given group is unknown, false otherwise. 475 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled); 476 477 /// \brief Set the error-as-fatal flag for the given diagnostic. This function 478 /// always only operates on the current diagnostic state. 479 void setDiagnosticErrorAsFatal(diag::kind Diag, bool Enabled); 480 481 /// \brief Set the error-as-fatal flag for the given diagnostic group. This 482 /// function always only operates on the current diagnostic state. 483 /// 484 /// \returns True if the given group is unknown, false otherwise. 485 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled); 486 487 /// \brief Add the specified mapping to all diagnostics. Mainly to be used 488 /// by -Wno-everything to disable all warnings but allow subsequent -W options 489 /// to enable specific warnings. 490 void setMappingToAllDiagnostics(diag::Mapping Map, 491 SourceLocation Loc = SourceLocation()); 492 493 bool hasErrorOccurred() const { return ErrorOccurred; } 494 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; } 495 496 /// \brief Determine whether any kind of unrecoverable error has occurred. 497 bool hasUnrecoverableErrorOccurred() const { 498 return FatalErrorOccurred || UnrecoverableErrorOccurred; 499 } 500 501 unsigned getNumWarnings() const { return NumWarnings; } 502 503 void setNumWarnings(unsigned NumWarnings) { 504 this->NumWarnings = NumWarnings; 505 } 506 507 /// getCustomDiagID - Return an ID for a diagnostic with the specified message 508 /// and level. If this is the first request for this diagnosic, it is 509 /// registered and created, otherwise the existing ID is returned. 510 unsigned getCustomDiagID(Level L, StringRef Message) { 511 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message); 512 } 513 514 /// ConvertArgToString - This method converts a diagnostic argument (as an 515 /// intptr_t) into the string that represents it. 516 void ConvertArgToString(ArgumentKind Kind, intptr_t Val, 517 const char *Modifier, unsigned ModLen, 518 const char *Argument, unsigned ArgLen, 519 const ArgumentValue *PrevArgs, unsigned NumPrevArgs, 520 SmallVectorImpl<char> &Output, 521 SmallVectorImpl<intptr_t> &QualTypeVals) const { 522 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen, 523 PrevArgs, NumPrevArgs, Output, ArgToStringCookie, 524 QualTypeVals); 525 } 526 527 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) { 528 ArgToStringFn = Fn; 529 ArgToStringCookie = Cookie; 530 } 531 532 /// \brief Reset the state of the diagnostic object to its initial 533 /// configuration. 534 void Reset(); 535 536 //===--------------------------------------------------------------------===// 537 // DiagnosticsEngine classification and reporting interfaces. 538 // 539 540 /// \brief Based on the way the client configured the DiagnosticsEngine 541 /// object, classify the specified diagnostic ID into a Level, consumable by 542 /// the DiagnosticConsumer. 543 /// 544 /// \param Loc The source location we are interested in finding out the 545 /// diagnostic state. Can be null in order to query the latest state. 546 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const { 547 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this); 548 } 549 550 /// Report - Issue the message to the client. @c DiagID is a member of the 551 /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder 552 /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed. 553 /// @c Pos represents the source location associated with the diagnostic, 554 /// which can be an invalid location if no position information is available. 555 inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID); 556 inline DiagnosticBuilder Report(unsigned DiagID); 557 558 void Report(const StoredDiagnostic &storedDiag); 559 560 /// \brief Determine whethere there is already a diagnostic in flight. 561 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; } 562 563 /// \brief Set the "delayed" diagnostic that will be emitted once 564 /// the current diagnostic completes. 565 /// 566 /// If a diagnostic is already in-flight but the front end must 567 /// report a problem (e.g., with an inconsistent file system 568 /// state), this routine sets a "delayed" diagnostic that will be 569 /// emitted after the current diagnostic completes. This should 570 /// only be used for fatal errors detected at inconvenient 571 /// times. If emitting a delayed diagnostic causes a second delayed 572 /// diagnostic to be introduced, that second delayed diagnostic 573 /// will be ignored. 574 /// 575 /// \param DiagID The ID of the diagnostic being delayed. 576 /// 577 /// \param Arg1 A string argument that will be provided to the 578 /// diagnostic. A copy of this string will be stored in the 579 /// DiagnosticsEngine object itself. 580 /// 581 /// \param Arg2 A string argument that will be provided to the 582 /// diagnostic. A copy of this string will be stored in the 583 /// DiagnosticsEngine object itself. 584 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "", 585 StringRef Arg2 = ""); 586 587 /// \brief Clear out the current diagnostic. 588 void Clear() { CurDiagID = ~0U; } 589 590private: 591 /// \brief Report the delayed diagnostic. 592 void ReportDelayed(); 593 594 // This is private state used by DiagnosticBuilder. We put it here instead of 595 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight 596 // object. This implementation choice means that we can only have one 597 // diagnostic "in flight" at a time, but this seems to be a reasonable 598 // tradeoff to keep these objects small. Assertions verify that only one 599 // diagnostic is in flight at a time. 600 friend class DiagnosticIDs; 601 friend class DiagnosticBuilder; 602 friend class Diagnostic; 603 friend class PartialDiagnostic; 604 friend class DiagnosticErrorTrap; 605 606 /// CurDiagLoc - This is the location of the current diagnostic that is in 607 /// flight. 608 SourceLocation CurDiagLoc; 609 610 /// CurDiagID - This is the ID of the current diagnostic that is in flight. 611 /// This is set to ~0U when there is no diagnostic in flight. 612 unsigned CurDiagID; 613 614 enum { 615 /// MaxArguments - The maximum number of arguments we can hold. We currently 616 /// only support up to 10 arguments (%0-%9). A single diagnostic with more 617 /// than that almost certainly has to be simplified anyway. 618 MaxArguments = 10 619 }; 620 621 /// NumDiagArgs - This contains the number of entries in Arguments. 622 signed char NumDiagArgs; 623 /// NumRanges - This is the number of ranges in the DiagRanges array. 624 unsigned char NumDiagRanges; 625 626 /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum 627 /// values, with one for each argument. This specifies whether the argument 628 /// is in DiagArgumentsStr or in DiagArguments. 629 unsigned char DiagArgumentsKind[MaxArguments]; 630 631 /// DiagArgumentsStr - This holds the values of each string argument for the 632 /// current diagnostic. This value is only used when the corresponding 633 /// ArgumentKind is ak_std_string. 634 std::string DiagArgumentsStr[MaxArguments]; 635 636 /// DiagArgumentsVal - The values for the various substitution positions. This 637 /// is used when the argument is not an std::string. The specific value is 638 /// mangled into an intptr_t and the interpretation depends on exactly what 639 /// sort of argument kind it is. 640 intptr_t DiagArgumentsVal[MaxArguments]; 641 642 /// DiagRanges - The list of ranges added to this diagnostic. It currently 643 /// only support 10 ranges, could easily be extended if needed. 644 CharSourceRange DiagRanges[10]; 645 646 /// FixItHints - If valid, provides a hint with some code 647 /// to insert, remove, or modify at a particular position. 648 SmallVector<FixItHint, 6> FixItHints; 649 650 DiagnosticMappingInfo makeMappingInfo(diag::Mapping Map, SourceLocation L) { 651 bool isPragma = L.isValid(); 652 DiagnosticMappingInfo MappingInfo = DiagnosticMappingInfo::Make( 653 Map, /*IsUser=*/true, isPragma); 654 655 // If this is a pragma mapping, then set the diagnostic mapping flags so 656 // that we override command line options. 657 if (isPragma) { 658 MappingInfo.setNoWarningAsError(true); 659 MappingInfo.setNoErrorAsFatal(true); 660 } 661 662 return MappingInfo; 663 } 664 665 /// ProcessDiag - This is the method used to report a diagnostic that is 666 /// finally fully formed. 667 /// 668 /// \returns true if the diagnostic was emitted, false if it was 669 /// suppressed. 670 bool ProcessDiag() { 671 return Diags->ProcessDiag(*this); 672 } 673 674 friend class ASTReader; 675 friend class ASTWriter; 676}; 677 678/// \brief RAII class that determines when any errors have occurred 679/// between the time the instance was created and the time it was 680/// queried. 681class DiagnosticErrorTrap { 682 DiagnosticsEngine &Diag; 683 unsigned NumErrors; 684 unsigned NumUnrecoverableErrors; 685 686public: 687 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag) 688 : Diag(Diag) { reset(); } 689 690 /// \brief Determine whether any errors have occurred since this 691 /// object instance was created. 692 bool hasErrorOccurred() const { 693 return Diag.TrapNumErrorsOccurred > NumErrors; 694 } 695 696 /// \brief Determine whether any unrecoverable errors have occurred since this 697 /// object instance was created. 698 bool hasUnrecoverableErrorOccurred() const { 699 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors; 700 } 701 702 // Set to initial state of "no errors occurred". 703 void reset() { 704 NumErrors = Diag.TrapNumErrorsOccurred; 705 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred; 706 } 707}; 708 709//===----------------------------------------------------------------------===// 710// DiagnosticBuilder 711//===----------------------------------------------------------------------===// 712 713/// DiagnosticBuilder - This is a little helper class used to produce 714/// diagnostics. This is constructed by the DiagnosticsEngine::Report method, 715/// and allows insertion of extra information (arguments and source ranges) into 716/// the currently "in flight" diagnostic. When the temporary for the builder is 717/// destroyed, the diagnostic is issued. 718/// 719/// Note that many of these will be created as temporary objects (many call 720/// sites), so we want them to be small and we never want their address taken. 721/// This ensures that compilers with somewhat reasonable optimizers will promote 722/// the common fields to registers, eliminating increments of the NumArgs field, 723/// for example. 724class DiagnosticBuilder { 725 mutable DiagnosticsEngine *DiagObj; 726 mutable unsigned NumArgs, NumRanges; 727 728 void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT 729 friend class DiagnosticsEngine; 730 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj) 731 : DiagObj(diagObj), NumArgs(0), NumRanges(0) { 732 DiagObj->FixItHints.clear(); 733 } 734 735 friend class PartialDiagnostic; 736 737protected: 738 void FlushCounts(); 739 740public: 741 /// Copy constructor. When copied, this "takes" the diagnostic info from the 742 /// input and neuters it. 743 DiagnosticBuilder(const DiagnosticBuilder &D) { 744 DiagObj = D.DiagObj; 745 D.DiagObj = 0; 746 NumArgs = D.NumArgs; 747 NumRanges = D.NumRanges; 748 } 749 750 /// \brief Simple enumeration value used to give a name to the 751 /// suppress-diagnostic constructor. 752 enum SuppressKind { Suppress }; 753 754 /// \brief Create an empty DiagnosticBuilder object that represents 755 /// no actual diagnostic. 756 explicit DiagnosticBuilder(SuppressKind) 757 : DiagObj(0), NumArgs(0), NumRanges(0) { } 758 759 /// \brief Force the diagnostic builder to emit the diagnostic now. 760 /// 761 /// Once this function has been called, the DiagnosticBuilder object 762 /// should not be used again before it is destroyed. 763 /// 764 /// \returns true if a diagnostic was emitted, false if the 765 /// diagnostic was suppressed. 766 bool Emit(); 767 768 /// Destructor - The dtor emits the diagnostic if it hasn't already 769 /// been emitted. 770 ~DiagnosticBuilder() { Emit(); } 771 772 /// isActive - Determine whether this diagnostic is still active. 773 bool isActive() const { return DiagObj != 0; } 774 775 /// \brief Retrieve the active diagnostic ID. 776 /// 777 /// \pre \c isActive() 778 unsigned getDiagID() const { 779 assert(isActive() && "DiagnosticsEngine is inactive"); 780 return DiagObj->CurDiagID; 781 } 782 783 /// \brief Retrieve the active diagnostic's location. 784 /// 785 /// \pre \c isActive() 786 SourceLocation getLocation() const { return DiagObj->CurDiagLoc; } 787 788 /// \brief Clear out the current diagnostic. 789 void Clear() { DiagObj = 0; } 790 791 /// Operator bool: conversion of DiagnosticBuilder to bool always returns 792 /// true. This allows is to be used in boolean error contexts like: 793 /// return Diag(...); 794 operator bool() const { return true; } 795 796 void AddString(StringRef S) const { 797 assert(NumArgs < DiagnosticsEngine::MaxArguments && 798 "Too many arguments to diagnostic!"); 799 if (DiagObj) { 800 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string; 801 DiagObj->DiagArgumentsStr[NumArgs++] = S; 802 } 803 } 804 805 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const { 806 assert(NumArgs < DiagnosticsEngine::MaxArguments && 807 "Too many arguments to diagnostic!"); 808 if (DiagObj) { 809 DiagObj->DiagArgumentsKind[NumArgs] = Kind; 810 DiagObj->DiagArgumentsVal[NumArgs++] = V; 811 } 812 } 813 814 void AddSourceRange(const CharSourceRange &R) const { 815 assert(NumRanges < 816 sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) && 817 "Too many arguments to diagnostic!"); 818 if (DiagObj) 819 DiagObj->DiagRanges[NumRanges++] = R; 820 } 821 822 void AddFixItHint(const FixItHint &Hint) const { 823 if (DiagObj) 824 DiagObj->FixItHints.push_back(Hint); 825 } 826}; 827 828inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 829 StringRef S) { 830 DB.AddString(S); 831 return DB; 832} 833 834inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 835 const char *Str) { 836 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str), 837 DiagnosticsEngine::ak_c_string); 838 return DB; 839} 840 841inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) { 842 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint); 843 return DB; 844} 845 846inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) { 847 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint); 848 return DB; 849} 850 851inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 852 unsigned I) { 853 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint); 854 return DB; 855} 856 857inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 858 const IdentifierInfo *II) { 859 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II), 860 DiagnosticsEngine::ak_identifierinfo); 861 return DB; 862} 863 864// Adds a DeclContext to the diagnostic. The enable_if template magic is here 865// so that we only match those arguments that are (statically) DeclContexts; 866// other arguments that derive from DeclContext (e.g., RecordDecls) will not 867// match. 868template<typename T> 869inline 870typename llvm::enable_if<llvm::is_same<T, DeclContext>, 871 const DiagnosticBuilder &>::type 872operator<<(const DiagnosticBuilder &DB, T *DC) { 873 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC), 874 DiagnosticsEngine::ak_declcontext); 875 return DB; 876} 877 878inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 879 const SourceRange &R) { 880 DB.AddSourceRange(CharSourceRange::getTokenRange(R)); 881 return DB; 882} 883 884inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 885 const CharSourceRange &R) { 886 DB.AddSourceRange(R); 887 return DB; 888} 889 890inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 891 const FixItHint &Hint) { 892 DB.AddFixItHint(Hint); 893 return DB; 894} 895 896/// Report - Issue the message to the client. DiagID is a member of the 897/// diag::kind enum. This actually returns a new instance of DiagnosticBuilder 898/// which emits the diagnostics (through ProcessDiag) when it is destroyed. 899inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc, 900 unsigned DiagID){ 901 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 902 CurDiagLoc = Loc; 903 CurDiagID = DiagID; 904 return DiagnosticBuilder(this); 905} 906inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) { 907 return Report(SourceLocation(), DiagID); 908} 909 910//===----------------------------------------------------------------------===// 911// Diagnostic 912//===----------------------------------------------------------------------===// 913 914/// Diagnostic - This is a little helper class (which is basically a smart 915/// pointer that forward info from DiagnosticsEngine) that allows clients to 916/// enquire about the currently in-flight diagnostic. 917class Diagnostic { 918 const DiagnosticsEngine *DiagObj; 919 StringRef StoredDiagMessage; 920public: 921 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {} 922 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage) 923 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {} 924 925 const DiagnosticsEngine *getDiags() const { return DiagObj; } 926 unsigned getID() const { return DiagObj->CurDiagID; } 927 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; } 928 bool hasSourceManager() const { return DiagObj->hasSourceManager(); } 929 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();} 930 931 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; } 932 933 /// getArgKind - Return the kind of the specified index. Based on the kind 934 /// of argument, the accessors below can be used to get the value. 935 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const { 936 assert(Idx < getNumArgs() && "Argument index out of range!"); 937 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx]; 938 } 939 940 /// getArgStdStr - Return the provided argument string specified by Idx. 941 const std::string &getArgStdStr(unsigned Idx) const { 942 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string && 943 "invalid argument accessor!"); 944 return DiagObj->DiagArgumentsStr[Idx]; 945 } 946 947 /// getArgCStr - Return the specified C string argument. 948 const char *getArgCStr(unsigned Idx) const { 949 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string && 950 "invalid argument accessor!"); 951 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]); 952 } 953 954 /// getArgSInt - Return the specified signed integer argument. 955 int getArgSInt(unsigned Idx) const { 956 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint && 957 "invalid argument accessor!"); 958 return (int)DiagObj->DiagArgumentsVal[Idx]; 959 } 960 961 /// getArgUInt - Return the specified unsigned integer argument. 962 unsigned getArgUInt(unsigned Idx) const { 963 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint && 964 "invalid argument accessor!"); 965 return (unsigned)DiagObj->DiagArgumentsVal[Idx]; 966 } 967 968 /// getArgIdentifier - Return the specified IdentifierInfo argument. 969 const IdentifierInfo *getArgIdentifier(unsigned Idx) const { 970 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo && 971 "invalid argument accessor!"); 972 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]); 973 } 974 975 /// getRawArg - Return the specified non-string argument in an opaque form. 976 intptr_t getRawArg(unsigned Idx) const { 977 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string && 978 "invalid argument accessor!"); 979 return DiagObj->DiagArgumentsVal[Idx]; 980 } 981 982 983 /// getNumRanges - Return the number of source ranges associated with this 984 /// diagnostic. 985 unsigned getNumRanges() const { 986 return DiagObj->NumDiagRanges; 987 } 988 989 const CharSourceRange &getRange(unsigned Idx) const { 990 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!"); 991 return DiagObj->DiagRanges[Idx]; 992 } 993 994 /// \brief Return an array reference for this diagnostic's ranges. 995 ArrayRef<CharSourceRange> getRanges() const { 996 return llvm::makeArrayRef(DiagObj->DiagRanges, DiagObj->NumDiagRanges); 997 } 998 999 unsigned getNumFixItHints() const { 1000 return DiagObj->FixItHints.size(); 1001 } 1002 1003 const FixItHint &getFixItHint(unsigned Idx) const { 1004 return DiagObj->FixItHints[Idx]; 1005 } 1006 1007 const FixItHint *getFixItHints() const { 1008 return getNumFixItHints()? 1009 DiagObj->FixItHints.data() : 0; 1010 } 1011 1012 /// FormatDiagnostic - Format this diagnostic into a string, substituting the 1013 /// formal arguments into the %0 slots. The result is appended onto the Str 1014 /// array. 1015 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const; 1016 1017 /// FormatDiagnostic - Format the given format-string into the 1018 /// output buffer using the arguments stored in this diagnostic. 1019 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 1020 SmallVectorImpl<char> &OutStr) const; 1021}; 1022 1023/** 1024 * \brief Represents a diagnostic in a form that can be retained until its 1025 * corresponding source manager is destroyed. 1026 */ 1027class StoredDiagnostic { 1028 unsigned ID; 1029 DiagnosticsEngine::Level Level; 1030 FullSourceLoc Loc; 1031 std::string Message; 1032 std::vector<CharSourceRange> Ranges; 1033 std::vector<FixItHint> FixIts; 1034 1035public: 1036 StoredDiagnostic(); 1037 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info); 1038 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 1039 StringRef Message); 1040 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 1041 StringRef Message, FullSourceLoc Loc, 1042 ArrayRef<CharSourceRange> Ranges, 1043 ArrayRef<FixItHint> Fixits); 1044 ~StoredDiagnostic(); 1045 1046 /// \brief Evaluates true when this object stores a diagnostic. 1047 operator bool() const { return Message.size() > 0; } 1048 1049 unsigned getID() const { return ID; } 1050 DiagnosticsEngine::Level getLevel() const { return Level; } 1051 const FullSourceLoc &getLocation() const { return Loc; } 1052 StringRef getMessage() const { return Message; } 1053 1054 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; } 1055 1056 typedef std::vector<CharSourceRange>::const_iterator range_iterator; 1057 range_iterator range_begin() const { return Ranges.begin(); } 1058 range_iterator range_end() const { return Ranges.end(); } 1059 unsigned range_size() const { return Ranges.size(); } 1060 1061 ArrayRef<CharSourceRange> getRanges() const { 1062 return llvm::makeArrayRef(Ranges); 1063 } 1064 1065 1066 typedef std::vector<FixItHint>::const_iterator fixit_iterator; 1067 fixit_iterator fixit_begin() const { return FixIts.begin(); } 1068 fixit_iterator fixit_end() const { return FixIts.end(); } 1069 unsigned fixit_size() const { return FixIts.size(); } 1070 1071 ArrayRef<FixItHint> getFixIts() const { 1072 return llvm::makeArrayRef(FixIts); 1073 } 1074}; 1075 1076/// DiagnosticConsumer - This is an abstract interface implemented by clients of 1077/// the front-end, which formats and prints fully processed diagnostics. 1078class DiagnosticConsumer { 1079protected: 1080 unsigned NumWarnings; // Number of warnings reported 1081 unsigned NumErrors; // Number of errors reported 1082 1083public: 1084 DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { } 1085 1086 unsigned getNumErrors() const { return NumErrors; } 1087 unsigned getNumWarnings() const { return NumWarnings; } 1088 virtual void clear() { NumWarnings = NumErrors = 0; } 1089 1090 virtual ~DiagnosticConsumer(); 1091 1092 /// BeginSourceFile - Callback to inform the diagnostic client that processing 1093 /// of a source file is beginning. 1094 /// 1095 /// Note that diagnostics may be emitted outside the processing of a source 1096 /// file, for example during the parsing of command line options. However, 1097 /// diagnostics with source range information are required to only be emitted 1098 /// in between BeginSourceFile() and EndSourceFile(). 1099 /// 1100 /// \arg LO - The language options for the source file being processed. 1101 /// \arg PP - The preprocessor object being used for the source; this optional 1102 /// and may not be present, for example when processing AST source files. 1103 virtual void BeginSourceFile(const LangOptions &LangOpts, 1104 const Preprocessor *PP = 0) {} 1105 1106 /// EndSourceFile - Callback to inform the diagnostic client that processing 1107 /// of a source file has ended. The diagnostic client should assume that any 1108 /// objects made available via \see BeginSourceFile() are inaccessible. 1109 virtual void EndSourceFile() {} 1110 1111 /// \brief Callback to inform the diagnostic client that processing of all 1112 /// source files has ended. 1113 virtual void finish() {} 1114 1115 /// IncludeInDiagnosticCounts - This method (whose default implementation 1116 /// returns true) indicates whether the diagnostics handled by this 1117 /// DiagnosticConsumer should be included in the number of diagnostics 1118 /// reported by DiagnosticsEngine. 1119 virtual bool IncludeInDiagnosticCounts() const; 1120 1121 /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or 1122 /// capturing it to a log as needed. 1123 /// 1124 /// Default implementation just keeps track of the total number of warnings 1125 /// and errors. 1126 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 1127 const Diagnostic &Info); 1128 1129 /// \brief Clone the diagnostic consumer, producing an equivalent consumer 1130 /// that can be used in a different context. 1131 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const = 0; 1132}; 1133 1134/// IgnoringDiagConsumer - This is a diagnostic client that just ignores all 1135/// diags. 1136class IgnoringDiagConsumer : public DiagnosticConsumer { 1137 virtual void anchor(); 1138 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 1139 const Diagnostic &Info) { 1140 // Just ignore it. 1141 } 1142 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { 1143 return new IgnoringDiagConsumer(); 1144 } 1145}; 1146 1147} // end namespace clang 1148 1149#endif 1150