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