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