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