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