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