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