Diagnostic.h revision 3ffe6293123b8fe59bd9d6ed8e3ec755d68e7fac
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 getNumWarnings() const { return NumWarnings; } 375 376 void setNumWarnings(unsigned NumWarnings) { 377 this->NumWarnings = NumWarnings; 378 } 379 380 /// getCustomDiagID - Return an ID for a diagnostic with the specified message 381 /// and level. If this is the first request for this diagnosic, it is 382 /// registered and created, otherwise the existing ID is returned. 383 unsigned getCustomDiagID(Level L, llvm::StringRef Message) { 384 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message); 385 } 386 387 /// ConvertArgToString - This method converts a diagnostic argument (as an 388 /// intptr_t) into the string that represents it. 389 void ConvertArgToString(ArgumentKind Kind, intptr_t Val, 390 const char *Modifier, unsigned ModLen, 391 const char *Argument, unsigned ArgLen, 392 const ArgumentValue *PrevArgs, unsigned NumPrevArgs, 393 llvm::SmallVectorImpl<char> &Output) const { 394 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen, 395 PrevArgs, NumPrevArgs, Output, ArgToStringCookie); 396 } 397 398 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) { 399 ArgToStringFn = Fn; 400 ArgToStringCookie = Cookie; 401 } 402 403 /// \brief Reset the state of the diagnostic object to its initial 404 /// configuration. 405 void Reset(); 406 407 //===--------------------------------------------------------------------===// 408 // Diagnostic classification and reporting interfaces. 409 // 410 411 /// getDiagnosticLevel - Based on the way the client configured the Diagnostic 412 /// object, classify the specified diagnostic ID into a Level, consumable by 413 /// the DiagnosticClient. 414 Level getDiagnosticLevel(unsigned DiagID) const { 415 return (Level)Diags->getDiagnosticLevel(DiagID, *this); 416 } 417 418 /// Report - Issue the message to the client. @c DiagID is a member of the 419 /// @c diag::kind enum. This actually returns aninstance of DiagnosticBuilder 420 /// which emits the diagnostics (through @c ProcessDiag) when it is destroyed. 421 /// @c Pos represents the source location associated with the diagnostic, 422 /// which can be an invalid location if no position information is available. 423 inline DiagnosticBuilder Report(SourceLocation Pos, unsigned DiagID); 424 inline DiagnosticBuilder Report(unsigned DiagID); 425 426 /// \brief Determine whethere there is already a diagnostic in flight. 427 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; } 428 429 /// \brief Set the "delayed" diagnostic that will be emitted once 430 /// the current diagnostic completes. 431 /// 432 /// If a diagnostic is already in-flight but the front end must 433 /// report a problem (e.g., with an inconsistent file system 434 /// state), this routine sets a "delayed" diagnostic that will be 435 /// emitted after the current diagnostic completes. This should 436 /// only be used for fatal errors detected at inconvenient 437 /// times. If emitting a delayed diagnostic causes a second delayed 438 /// diagnostic to be introduced, that second delayed diagnostic 439 /// will be ignored. 440 /// 441 /// \param DiagID The ID of the diagnostic being delayed. 442 /// 443 /// \param Arg1 A string argument that will be provided to the 444 /// diagnostic. A copy of this string will be stored in the 445 /// Diagnostic object itself. 446 /// 447 /// \param Arg2 A string argument that will be provided to the 448 /// diagnostic. A copy of this string will be stored in the 449 /// Diagnostic object itself. 450 void SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1 = "", 451 llvm::StringRef Arg2 = ""); 452 453 /// \brief Clear out the current diagnostic. 454 void Clear() { CurDiagID = ~0U; } 455 456private: 457 /// \brief Report the delayed diagnostic. 458 void ReportDelayed(); 459 460 461 /// getDiagnosticMappingInfo - Return the mapping info currently set for the 462 /// specified builtin diagnostic. This returns the high bit encoding, or zero 463 /// if the field is completely uninitialized. 464 diag::Mapping getDiagnosticMappingInfo(diag::kind Diag) const { 465 return DiagMappingsStack.back().getMapping(Diag); 466 } 467 468 void setDiagnosticMappingInternal(unsigned DiagId, unsigned Map, 469 bool isUser) const { 470 if (isUser) Map |= 8; // Set the high bit for user mappings. 471 DiagMappingsStack.back().setMapping((diag::kind)DiagId, Map); 472 } 473 474 // This is private state used by DiagnosticBuilder. We put it here instead of 475 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight 476 // object. This implementation choice means that we can only have one 477 // diagnostic "in flight" at a time, but this seems to be a reasonable 478 // tradeoff to keep these objects small. Assertions verify that only one 479 // diagnostic is in flight at a time. 480 friend class DiagnosticIDs; 481 friend class DiagnosticBuilder; 482 friend class DiagnosticInfo; 483 friend class PartialDiagnostic; 484 friend class DiagnosticErrorTrap; 485 486 /// CurDiagLoc - This is the location of the current diagnostic that is in 487 /// flight. 488 SourceLocation CurDiagLoc; 489 490 /// CurDiagID - This is the ID of the current diagnostic that is in flight. 491 /// This is set to ~0U when there is no diagnostic in flight. 492 unsigned CurDiagID; 493 494 enum { 495 /// MaxArguments - The maximum number of arguments we can hold. We currently 496 /// only support up to 10 arguments (%0-%9). A single diagnostic with more 497 /// than that almost certainly has to be simplified anyway. 498 MaxArguments = 10 499 }; 500 501 /// NumDiagArgs - This contains the number of entries in Arguments. 502 signed char NumDiagArgs; 503 /// NumRanges - This is the number of ranges in the DiagRanges array. 504 unsigned char NumDiagRanges; 505 /// \brief The number of code modifications hints in the 506 /// FixItHints array. 507 unsigned char NumFixItHints; 508 509 /// DiagArgumentsKind - This is an array of ArgumentKind::ArgumentKind enum 510 /// values, with one for each argument. This specifies whether the argument 511 /// is in DiagArgumentsStr or in DiagArguments. 512 unsigned char DiagArgumentsKind[MaxArguments]; 513 514 /// DiagArgumentsStr - This holds the values of each string argument for the 515 /// current diagnostic. This value is only used when the corresponding 516 /// ArgumentKind is ak_std_string. 517 std::string DiagArgumentsStr[MaxArguments]; 518 519 /// DiagArgumentsVal - The values for the various substitution positions. This 520 /// is used when the argument is not an std::string. The specific value is 521 /// mangled into an intptr_t and the intepretation depends on exactly what 522 /// sort of argument kind it is. 523 intptr_t DiagArgumentsVal[MaxArguments]; 524 525 /// DiagRanges - The list of ranges added to this diagnostic. It currently 526 /// only support 10 ranges, could easily be extended if needed. 527 CharSourceRange DiagRanges[10]; 528 529 enum { MaxFixItHints = 3 }; 530 531 /// FixItHints - If valid, provides a hint with some code 532 /// to insert, remove, or modify at a particular position. 533 FixItHint FixItHints[MaxFixItHints]; 534 535 /// ProcessDiag - This is the method used to report a diagnostic that is 536 /// finally fully formed. 537 /// 538 /// \returns true if the diagnostic was emitted, false if it was 539 /// suppressed. 540 bool ProcessDiag() { 541 return Diags->ProcessDiag(*this); 542 } 543 544 friend class ASTReader; 545 friend class ASTWriter; 546}; 547 548/// \brief RAII class that determines when any errors have occurred 549/// between the time the instance was created and the time it was 550/// queried. 551class DiagnosticErrorTrap { 552 Diagnostic &Diag; 553 unsigned PrevErrors; 554 555public: 556 explicit DiagnosticErrorTrap(Diagnostic &Diag) 557 : Diag(Diag), PrevErrors(Diag.NumErrors) {} 558 559 /// \brief Determine whether any errors have occurred since this 560 /// object instance was created. 561 bool hasErrorOccurred() const { 562 return Diag.NumErrors > PrevErrors; 563 } 564 565 // Set to initial state of "no errors occurred". 566 void reset() { PrevErrors = Diag.NumErrors; } 567}; 568 569//===----------------------------------------------------------------------===// 570// DiagnosticBuilder 571//===----------------------------------------------------------------------===// 572 573/// DiagnosticBuilder - This is a little helper class used to produce 574/// diagnostics. This is constructed by the Diagnostic::Report method, and 575/// allows insertion of extra information (arguments and source ranges) into the 576/// currently "in flight" diagnostic. When the temporary for the builder is 577/// destroyed, the diagnostic is issued. 578/// 579/// Note that many of these will be created as temporary objects (many call 580/// sites), so we want them to be small and we never want their address taken. 581/// This ensures that compilers with somewhat reasonable optimizers will promote 582/// the common fields to registers, eliminating increments of the NumArgs field, 583/// for example. 584class DiagnosticBuilder { 585 mutable Diagnostic *DiagObj; 586 mutable unsigned NumArgs, NumRanges, NumFixItHints; 587 588 void operator=(const DiagnosticBuilder&); // DO NOT IMPLEMENT 589 friend class Diagnostic; 590 explicit DiagnosticBuilder(Diagnostic *diagObj) 591 : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixItHints(0) {} 592 593 friend class PartialDiagnostic; 594 595protected: 596 void FlushCounts(); 597 598public: 599 /// Copy constructor. When copied, this "takes" the diagnostic info from the 600 /// input and neuters it. 601 DiagnosticBuilder(const DiagnosticBuilder &D) { 602 DiagObj = D.DiagObj; 603 D.DiagObj = 0; 604 NumArgs = D.NumArgs; 605 NumRanges = D.NumRanges; 606 NumFixItHints = D.NumFixItHints; 607 } 608 609 /// \brief Simple enumeration value used to give a name to the 610 /// suppress-diagnostic constructor. 611 enum SuppressKind { Suppress }; 612 613 /// \brief Create an empty DiagnosticBuilder object that represents 614 /// no actual diagnostic. 615 explicit DiagnosticBuilder(SuppressKind) 616 : DiagObj(0), NumArgs(0), NumRanges(0), NumFixItHints(0) { } 617 618 /// \brief Force the diagnostic builder to emit the diagnostic now. 619 /// 620 /// Once this function has been called, the DiagnosticBuilder object 621 /// should not be used again before it is destroyed. 622 /// 623 /// \returns true if a diagnostic was emitted, false if the 624 /// diagnostic was suppressed. 625 bool Emit(); 626 627 /// Destructor - The dtor emits the diagnostic if it hasn't already 628 /// been emitted. 629 ~DiagnosticBuilder() { Emit(); } 630 631 /// isActive - Determine whether this diagnostic is still active. 632 bool isActive() const { return DiagObj != 0; } 633 634 /// \brief Retrieve the active diagnostic ID. 635 /// 636 /// \pre \c isActive() 637 unsigned getDiagID() const { 638 assert(isActive() && "Diagnostic is inactive"); 639 return DiagObj->CurDiagID; 640 } 641 642 /// \brief Clear out the current diagnostic. 643 void Clear() { DiagObj = 0; } 644 645 /// Operator bool: conversion of DiagnosticBuilder to bool always returns 646 /// true. This allows is to be used in boolean error contexts like: 647 /// return Diag(...); 648 operator bool() const { return true; } 649 650 void AddString(llvm::StringRef S) const { 651 assert(NumArgs < Diagnostic::MaxArguments && 652 "Too many arguments to diagnostic!"); 653 if (DiagObj) { 654 DiagObj->DiagArgumentsKind[NumArgs] = Diagnostic::ak_std_string; 655 DiagObj->DiagArgumentsStr[NumArgs++] = S; 656 } 657 } 658 659 void AddTaggedVal(intptr_t V, Diagnostic::ArgumentKind Kind) const { 660 assert(NumArgs < Diagnostic::MaxArguments && 661 "Too many arguments to diagnostic!"); 662 if (DiagObj) { 663 DiagObj->DiagArgumentsKind[NumArgs] = Kind; 664 DiagObj->DiagArgumentsVal[NumArgs++] = V; 665 } 666 } 667 668 void AddSourceRange(const CharSourceRange &R) const { 669 assert(NumRanges < 670 sizeof(DiagObj->DiagRanges)/sizeof(DiagObj->DiagRanges[0]) && 671 "Too many arguments to diagnostic!"); 672 if (DiagObj) 673 DiagObj->DiagRanges[NumRanges++] = R; 674 } 675 676 void AddFixItHint(const FixItHint &Hint) const { 677 if (Hint.isNull()) 678 return; 679 680 assert(NumFixItHints < Diagnostic::MaxFixItHints && 681 "Too many fix-it hints!"); 682 if (DiagObj) 683 DiagObj->FixItHints[NumFixItHints++] = Hint; 684 } 685}; 686 687inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 688 llvm::StringRef S) { 689 DB.AddString(S); 690 return DB; 691} 692 693inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 694 const char *Str) { 695 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str), 696 Diagnostic::ak_c_string); 697 return DB; 698} 699 700inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) { 701 DB.AddTaggedVal(I, Diagnostic::ak_sint); 702 return DB; 703} 704 705inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) { 706 DB.AddTaggedVal(I, Diagnostic::ak_sint); 707 return DB; 708} 709 710inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 711 unsigned I) { 712 DB.AddTaggedVal(I, Diagnostic::ak_uint); 713 return DB; 714} 715 716inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 717 const IdentifierInfo *II) { 718 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II), 719 Diagnostic::ak_identifierinfo); 720 return DB; 721} 722 723// Adds a DeclContext to the diagnostic. The enable_if template magic is here 724// so that we only match those arguments that are (statically) DeclContexts; 725// other arguments that derive from DeclContext (e.g., RecordDecls) will not 726// match. 727template<typename T> 728inline 729typename llvm::enable_if<llvm::is_same<T, DeclContext>, 730 const DiagnosticBuilder &>::type 731operator<<(const DiagnosticBuilder &DB, T *DC) { 732 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC), 733 Diagnostic::ak_declcontext); 734 return DB; 735} 736 737inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 738 const SourceRange &R) { 739 DB.AddSourceRange(CharSourceRange::getTokenRange(R)); 740 return DB; 741} 742 743inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 744 const CharSourceRange &R) { 745 DB.AddSourceRange(R); 746 return DB; 747} 748 749inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 750 const FixItHint &Hint) { 751 DB.AddFixItHint(Hint); 752 return DB; 753} 754 755/// Report - Issue the message to the client. DiagID is a member of the 756/// diag::kind enum. This actually returns a new instance of DiagnosticBuilder 757/// which emits the diagnostics (through ProcessDiag) when it is destroyed. 758inline DiagnosticBuilder Diagnostic::Report(SourceLocation Loc, 759 unsigned DiagID){ 760 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 761 CurDiagLoc = Loc; 762 CurDiagID = DiagID; 763 return DiagnosticBuilder(this); 764} 765inline DiagnosticBuilder Diagnostic::Report(unsigned DiagID) { 766 return Report(SourceLocation(), DiagID); 767} 768 769//===----------------------------------------------------------------------===// 770// DiagnosticInfo 771//===----------------------------------------------------------------------===// 772 773/// DiagnosticInfo - This is a little helper class (which is basically a smart 774/// pointer that forward info from Diagnostic) that allows clients to enquire 775/// about the currently in-flight diagnostic. 776class DiagnosticInfo { 777 const Diagnostic *DiagObj; 778public: 779 explicit DiagnosticInfo(const Diagnostic *DO) : DiagObj(DO) {} 780 781 const Diagnostic *getDiags() const { return DiagObj; } 782 unsigned getID() const { return DiagObj->CurDiagID; } 783 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; } 784 bool hasSourceManager() const { return DiagObj->hasSourceManager(); } 785 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();} 786 787 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; } 788 789 /// getArgKind - Return the kind of the specified index. Based on the kind 790 /// of argument, the accessors below can be used to get the value. 791 Diagnostic::ArgumentKind getArgKind(unsigned Idx) const { 792 assert(Idx < getNumArgs() && "Argument index out of range!"); 793 return (Diagnostic::ArgumentKind)DiagObj->DiagArgumentsKind[Idx]; 794 } 795 796 /// getArgStdStr - Return the provided argument string specified by Idx. 797 const std::string &getArgStdStr(unsigned Idx) const { 798 assert(getArgKind(Idx) == Diagnostic::ak_std_string && 799 "invalid argument accessor!"); 800 return DiagObj->DiagArgumentsStr[Idx]; 801 } 802 803 /// getArgCStr - Return the specified C string argument. 804 const char *getArgCStr(unsigned Idx) const { 805 assert(getArgKind(Idx) == Diagnostic::ak_c_string && 806 "invalid argument accessor!"); 807 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]); 808 } 809 810 /// getArgSInt - Return the specified signed integer argument. 811 int getArgSInt(unsigned Idx) const { 812 assert(getArgKind(Idx) == Diagnostic::ak_sint && 813 "invalid argument accessor!"); 814 return (int)DiagObj->DiagArgumentsVal[Idx]; 815 } 816 817 /// getArgUInt - Return the specified unsigned integer argument. 818 unsigned getArgUInt(unsigned Idx) const { 819 assert(getArgKind(Idx) == Diagnostic::ak_uint && 820 "invalid argument accessor!"); 821 return (unsigned)DiagObj->DiagArgumentsVal[Idx]; 822 } 823 824 /// getArgIdentifier - Return the specified IdentifierInfo argument. 825 const IdentifierInfo *getArgIdentifier(unsigned Idx) const { 826 assert(getArgKind(Idx) == Diagnostic::ak_identifierinfo && 827 "invalid argument accessor!"); 828 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]); 829 } 830 831 /// getRawArg - Return the specified non-string argument in an opaque form. 832 intptr_t getRawArg(unsigned Idx) const { 833 assert(getArgKind(Idx) != Diagnostic::ak_std_string && 834 "invalid argument accessor!"); 835 return DiagObj->DiagArgumentsVal[Idx]; 836 } 837 838 839 /// getNumRanges - Return the number of source ranges associated with this 840 /// diagnostic. 841 unsigned getNumRanges() const { 842 return DiagObj->NumDiagRanges; 843 } 844 845 const CharSourceRange &getRange(unsigned Idx) const { 846 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!"); 847 return DiagObj->DiagRanges[Idx]; 848 } 849 850 unsigned getNumFixItHints() const { 851 return DiagObj->NumFixItHints; 852 } 853 854 const FixItHint &getFixItHint(unsigned Idx) const { 855 return DiagObj->FixItHints[Idx]; 856 } 857 858 const FixItHint *getFixItHints() const { 859 return DiagObj->NumFixItHints? 860 &DiagObj->FixItHints[0] : 0; 861 } 862 863 /// FormatDiagnostic - Format this diagnostic into a string, substituting the 864 /// formal arguments into the %0 slots. The result is appended onto the Str 865 /// array. 866 void FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const; 867 868 /// FormatDiagnostic - Format the given format-string into the 869 /// output buffer using the arguments stored in this diagnostic. 870 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 871 llvm::SmallVectorImpl<char> &OutStr) const; 872}; 873 874/** 875 * \brief Represents a diagnostic in a form that can be retained until its 876 * corresponding source manager is destroyed. 877 */ 878class StoredDiagnostic { 879 Diagnostic::Level Level; 880 FullSourceLoc Loc; 881 std::string Message; 882 std::vector<CharSourceRange> Ranges; 883 std::vector<FixItHint> FixIts; 884 885public: 886 StoredDiagnostic(); 887 StoredDiagnostic(Diagnostic::Level Level, const DiagnosticInfo &Info); 888 StoredDiagnostic(Diagnostic::Level Level, llvm::StringRef Message); 889 ~StoredDiagnostic(); 890 891 /// \brief Evaluates true when this object stores a diagnostic. 892 operator bool() const { return Message.size() > 0; } 893 894 Diagnostic::Level getLevel() const { return Level; } 895 const FullSourceLoc &getLocation() const { return Loc; } 896 llvm::StringRef getMessage() const { return Message; } 897 898 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; } 899 900 typedef std::vector<CharSourceRange>::const_iterator range_iterator; 901 range_iterator range_begin() const { return Ranges.begin(); } 902 range_iterator range_end() const { return Ranges.end(); } 903 unsigned range_size() const { return Ranges.size(); } 904 905 typedef std::vector<FixItHint>::const_iterator fixit_iterator; 906 fixit_iterator fixit_begin() const { return FixIts.begin(); } 907 fixit_iterator fixit_end() const { return FixIts.end(); } 908 unsigned fixit_size() const { return FixIts.size(); } 909}; 910 911/// DiagnosticClient - This is an abstract interface implemented by clients of 912/// the front-end, which formats and prints fully processed diagnostics. 913class DiagnosticClient { 914protected: 915 unsigned NumWarnings; // Number of warnings reported 916 unsigned NumErrors; // Number of errors reported 917 918public: 919 DiagnosticClient() : NumWarnings(0), NumErrors(0) { } 920 921 unsigned getNumErrors() const { return NumErrors; } 922 unsigned getNumWarnings() const { return NumWarnings; } 923 924 virtual ~DiagnosticClient(); 925 926 /// BeginSourceFile - Callback to inform the diagnostic client that processing 927 /// of a source file is beginning. 928 /// 929 /// Note that diagnostics may be emitted outside the processing of a source 930 /// file, for example during the parsing of command line options. However, 931 /// diagnostics with source range information are required to only be emitted 932 /// in between BeginSourceFile() and EndSourceFile(). 933 /// 934 /// \arg LO - The language options for the source file being processed. 935 /// \arg PP - The preprocessor object being used for the source; this optional 936 /// and may not be present, for example when processing AST source files. 937 virtual void BeginSourceFile(const LangOptions &LangOpts, 938 const Preprocessor *PP = 0) {} 939 940 /// EndSourceFile - Callback to inform the diagnostic client that processing 941 /// of a source file has ended. The diagnostic client should assume that any 942 /// objects made available via \see BeginSourceFile() are inaccessible. 943 virtual void EndSourceFile() {} 944 945 /// IncludeInDiagnosticCounts - This method (whose default implementation 946 /// returns true) indicates whether the diagnostics handled by this 947 /// DiagnosticClient should be included in the number of diagnostics reported 948 /// by Diagnostic. 949 virtual bool IncludeInDiagnosticCounts() const; 950 951 /// HandleDiagnostic - Handle this diagnostic, reporting it to the user or 952 /// capturing it to a log as needed. 953 /// 954 /// Default implementation just keeps track of the total number of warnings 955 /// and errors. 956 virtual void HandleDiagnostic(Diagnostic::Level DiagLevel, 957 const DiagnosticInfo &Info); 958}; 959 960} // end namespace clang 961 962#endif 963