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