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