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