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