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