Diagnostic.h revision 5b9268f26ac53a74d2c504279fe577d988d5615d
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/// \file 11/// \brief Defines the Diagnostic-related interfaces. 12/// 13//===----------------------------------------------------------------------===// 14 15#ifndef LLVM_CLANG_DIAGNOSTIC_H 16#define LLVM_CLANG_DIAGNOSTIC_H 17 18#include "clang/Basic/DiagnosticIDs.h" 19#include "clang/Basic/DiagnosticOptions.h" 20#include "clang/Basic/SourceLocation.h" 21#include "llvm/ADT/ArrayRef.h" 22#include "llvm/ADT/DenseMap.h" 23#include "llvm/ADT/IntrusiveRefCntPtr.h" 24#include "llvm/ADT/OwningPtr.h" 25#include "llvm/Support/type_traits.h" 26#include <list> 27#include <vector> 28 29namespace clang { 30 class DiagnosticConsumer; 31 class DiagnosticBuilder; 32 class DiagnosticOptions; 33 class IdentifierInfo; 34 class DeclContext; 35 class LangOptions; 36 class Preprocessor; 37 class DiagnosticErrorTrap; 38 class StoredDiagnostic; 39 40/// \brief Annotates a diagnostic with some code that should be 41/// inserted, removed, or replaced to fix the problem. 42/// 43/// This kind of hint should be used when we are certain that the 44/// introduction, removal, or modification of a particular (small!) 45/// amount of code will correct a compilation error. The compiler 46/// should also provide full recovery from such errors, such that 47/// suppressing the diagnostic output can still result in successful 48/// compilation. 49class FixItHint { 50public: 51 /// \brief Code that should be replaced to correct the error. Empty for an 52 /// insertion hint. 53 CharSourceRange RemoveRange; 54 55 /// \brief Code in the specific range that should be inserted in the insertion 56 /// location. 57 CharSourceRange InsertFromRange; 58 59 /// \brief The actual code to insert at the insertion location, as a 60 /// string. 61 std::string CodeToInsert; 62 63 bool BeforePreviousInsertions; 64 65 /// \brief Empty code modification hint, indicating that no code 66 /// modification is known. 67 FixItHint() : BeforePreviousInsertions(false) { } 68 69 bool isNull() const { 70 return !RemoveRange.isValid(); 71 } 72 73 /// \brief Create a code modification hint that inserts the given 74 /// code string at a specific location. 75 static FixItHint CreateInsertion(SourceLocation InsertionLoc, 76 StringRef Code, 77 bool BeforePreviousInsertions = false) { 78 FixItHint Hint; 79 Hint.RemoveRange = 80 CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false); 81 Hint.CodeToInsert = Code; 82 Hint.BeforePreviousInsertions = BeforePreviousInsertions; 83 return Hint; 84 } 85 86 /// \brief Create a code modification hint that inserts the given 87 /// code from \p FromRange at a specific location. 88 static FixItHint CreateInsertionFromRange(SourceLocation InsertionLoc, 89 CharSourceRange FromRange, 90 bool BeforePreviousInsertions = false) { 91 FixItHint Hint; 92 Hint.RemoveRange = 93 CharSourceRange(SourceRange(InsertionLoc, InsertionLoc), false); 94 Hint.InsertFromRange = FromRange; 95 Hint.BeforePreviousInsertions = BeforePreviousInsertions; 96 return Hint; 97 } 98 99 /// \brief Create a code modification hint that removes the given 100 /// source range. 101 static FixItHint CreateRemoval(CharSourceRange RemoveRange) { 102 FixItHint Hint; 103 Hint.RemoveRange = RemoveRange; 104 return Hint; 105 } 106 static FixItHint CreateRemoval(SourceRange RemoveRange) { 107 return CreateRemoval(CharSourceRange::getTokenRange(RemoveRange)); 108 } 109 110 /// \brief Create a code modification hint that replaces the given 111 /// source range with the given code string. 112 static FixItHint CreateReplacement(CharSourceRange RemoveRange, 113 StringRef Code) { 114 FixItHint Hint; 115 Hint.RemoveRange = RemoveRange; 116 Hint.CodeToInsert = Code; 117 return Hint; 118 } 119 120 static FixItHint CreateReplacement(SourceRange RemoveRange, 121 StringRef Code) { 122 return CreateReplacement(CharSourceRange::getTokenRange(RemoveRange), Code); 123 } 124}; 125 126/// \brief Concrete class used by the front-end to report problems and issues. 127/// 128/// This massages the diagnostics (e.g. handling things like "report warnings 129/// as errors" and passes them off to the DiagnosticConsumer for reporting to 130/// the user. DiagnosticsEngine is tied to one translation unit and one 131/// SourceManager. 132class DiagnosticsEngine : public RefCountedBase<DiagnosticsEngine> { 133public: 134 /// \brief The level of the diagnostic, after it has been through mapping. 135 enum Level { 136 Ignored = DiagnosticIDs::Ignored, 137 Note = DiagnosticIDs::Note, 138 Warning = DiagnosticIDs::Warning, 139 Error = DiagnosticIDs::Error, 140 Fatal = DiagnosticIDs::Fatal 141 }; 142 143 /// \brief How do we handle otherwise-unmapped extension? 144 /// 145 /// This is controlled by -pedantic and -pedantic-errors. 146 enum ExtensionHandling { 147 Ext_Ignore, Ext_Warn, Ext_Error 148 }; 149 150 enum ArgumentKind { 151 ak_std_string, ///< std::string 152 ak_c_string, ///< const char * 153 ak_sint, ///< int 154 ak_uint, ///< unsigned 155 ak_identifierinfo, ///< IdentifierInfo 156 ak_qualtype, ///< QualType 157 ak_declarationname, ///< DeclarationName 158 ak_nameddecl, ///< NamedDecl * 159 ak_nestednamespec, ///< NestedNameSpecifier * 160 ak_declcontext, ///< DeclContext * 161 ak_qualtype_pair ///< pair<QualType, QualType> 162 }; 163 164 /// \brief Represents on argument value, which is a union discriminated 165 /// by ArgumentKind, with a value. 166 typedef std::pair<ArgumentKind, intptr_t> ArgumentValue; 167 168private: 169 unsigned char AllExtensionsSilenced; // Used by __extension__ 170 bool IgnoreAllWarnings; // Ignore all warnings: -w 171 bool WarningsAsErrors; // Treat warnings like errors. 172 bool EnableAllWarnings; // Enable all warnings. 173 bool ErrorsAsFatal; // Treat errors like fatal errors. 174 bool SuppressSystemWarnings; // Suppress warnings in system headers. 175 bool SuppressAllDiagnostics; // Suppress all diagnostics. 176 bool ElideType; // Elide common types of templates. 177 bool PrintTemplateTree; // Print a tree when comparing templates. 178 bool ShowColors; // Color printing is enabled. 179 OverloadsShown ShowOverloads; // Which overload candidates to show. 180 unsigned ErrorLimit; // Cap of # errors emitted, 0 -> no limit. 181 unsigned TemplateBacktraceLimit; // Cap on depth of template backtrace stack, 182 // 0 -> no limit. 183 unsigned ConstexprBacktraceLimit; // Cap on depth of constexpr evaluation 184 // backtrace stack, 0 -> no limit. 185 ExtensionHandling ExtBehavior; // Map extensions onto warnings or errors? 186 IntrusiveRefCntPtr<DiagnosticIDs> Diags; 187 IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts; 188 DiagnosticConsumer *Client; 189 bool OwnsDiagClient; 190 SourceManager *SourceMgr; 191 192 /// \brief Mapping information for diagnostics. 193 /// 194 /// Mapping info is packed into four bits per diagnostic. The low three 195 /// bits are the mapping (an instance of diag::Mapping), or zero if unset. 196 /// The high bit is set when the mapping was established as a user mapping. 197 /// If the high bit is clear, then the low bits are set to the default 198 /// value, and should be mapped with -pedantic, -Werror, etc. 199 /// 200 /// A new DiagState is created and kept around when diagnostic pragmas modify 201 /// the state so that we know what is the diagnostic state at any given 202 /// source location. 203 class DiagState { 204 llvm::DenseMap<unsigned, DiagnosticMappingInfo> DiagMap; 205 206 public: 207 typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::iterator 208 iterator; 209 typedef llvm::DenseMap<unsigned, DiagnosticMappingInfo>::const_iterator 210 const_iterator; 211 212 void setMappingInfo(diag::kind Diag, DiagnosticMappingInfo Info) { 213 DiagMap[Diag] = Info; 214 } 215 216 DiagnosticMappingInfo &getOrAddMappingInfo(diag::kind Diag); 217 218 const_iterator begin() const { return DiagMap.begin(); } 219 const_iterator end() const { return DiagMap.end(); } 220 }; 221 222 /// \brief Keeps and automatically disposes all DiagStates that we create. 223 std::list<DiagState> DiagStates; 224 225 /// \brief Represents a point in source where the diagnostic state was 226 /// modified because of a pragma. 227 /// 228 /// 'Loc' can be null if the point represents the diagnostic state 229 /// modifications done through the command-line. 230 struct DiagStatePoint { 231 DiagState *State; 232 FullSourceLoc Loc; 233 DiagStatePoint(DiagState *State, FullSourceLoc Loc) 234 : State(State), Loc(Loc) { } 235 236 bool operator<(const DiagStatePoint &RHS) const { 237 // If Loc is invalid it means it came from <command-line>, in which case 238 // we regard it as coming before any valid source location. 239 if (RHS.Loc.isInvalid()) 240 return false; 241 if (Loc.isInvalid()) 242 return true; 243 return Loc.isBeforeInTranslationUnitThan(RHS.Loc); 244 } 245 }; 246 247 /// \brief A sorted vector of all DiagStatePoints representing changes in 248 /// diagnostic state due to diagnostic pragmas. 249 /// 250 /// The vector is always sorted according to the SourceLocation of the 251 /// DiagStatePoint. 252 typedef std::vector<DiagStatePoint> DiagStatePointsTy; 253 mutable DiagStatePointsTy DiagStatePoints; 254 255 /// \brief Keeps the DiagState that was active during each diagnostic 'push' 256 /// so we can get back at it when we 'pop'. 257 std::vector<DiagState *> DiagStateOnPushStack; 258 259 DiagState *GetCurDiagState() const { 260 assert(!DiagStatePoints.empty()); 261 return DiagStatePoints.back().State; 262 } 263 264 void PushDiagStatePoint(DiagState *State, SourceLocation L) { 265 FullSourceLoc Loc(L, getSourceManager()); 266 // Make sure that DiagStatePoints is always sorted according to Loc. 267 assert(Loc.isValid() && "Adding invalid loc point"); 268 assert(!DiagStatePoints.empty() && 269 (DiagStatePoints.back().Loc.isInvalid() || 270 DiagStatePoints.back().Loc.isBeforeInTranslationUnitThan(Loc)) && 271 "Previous point loc comes after or is the same as new one"); 272 DiagStatePoints.push_back(DiagStatePoint(State, Loc)); 273 } 274 275 /// \brief Finds the DiagStatePoint that contains the diagnostic state of 276 /// the given source location. 277 DiagStatePointsTy::iterator GetDiagStatePointForLoc(SourceLocation Loc) const; 278 279 /// \brief Sticky flag set to \c true when an error is emitted. 280 bool ErrorOccurred; 281 282 /// \brief Sticky flag set to \c true when an "uncompilable error" occurs. 283 /// I.e. an error that was not upgraded from a warning by -Werror. 284 bool UncompilableErrorOccurred; 285 286 /// \brief Sticky flag set to \c true when a fatal error is emitted. 287 bool FatalErrorOccurred; 288 289 /// \brief Indicates that an unrecoverable error has occurred. 290 bool UnrecoverableErrorOccurred; 291 292 /// \brief Counts for DiagnosticErrorTrap to check whether an error occurred 293 /// during a parsing section, e.g. during parsing a function. 294 unsigned TrapNumErrorsOccurred; 295 unsigned TrapNumUnrecoverableErrorsOccurred; 296 297 /// \brief The level of the last diagnostic emitted. 298 /// 299 /// This is used to emit continuation diagnostics with the same level as the 300 /// diagnostic that they follow. 301 DiagnosticIDs::Level LastDiagLevel; 302 303 unsigned NumWarnings; ///< Number of warnings reported 304 unsigned NumErrors; ///< Number of errors reported 305 unsigned NumErrorsSuppressed; ///< Number of errors suppressed 306 307 /// \brief A function pointer that converts an opaque diagnostic 308 /// argument to a strings. 309 /// 310 /// This takes the modifiers and argument that was present in the diagnostic. 311 /// 312 /// The PrevArgs array (whose length is NumPrevArgs) indicates the previous 313 /// arguments formatted for this diagnostic. Implementations of this function 314 /// can use this information to avoid redundancy across arguments. 315 /// 316 /// This is a hack to avoid a layering violation between libbasic and libsema. 317 typedef void (*ArgToStringFnTy)( 318 ArgumentKind Kind, intptr_t Val, 319 const char *Modifier, unsigned ModifierLen, 320 const char *Argument, unsigned ArgumentLen, 321 const ArgumentValue *PrevArgs, 322 unsigned NumPrevArgs, 323 SmallVectorImpl<char> &Output, 324 void *Cookie, 325 ArrayRef<intptr_t> QualTypeVals); 326 void *ArgToStringCookie; 327 ArgToStringFnTy ArgToStringFn; 328 329 /// \brief ID of the "delayed" diagnostic, which is a (typically 330 /// fatal) diagnostic that had to be delayed because it was found 331 /// while emitting another diagnostic. 332 unsigned DelayedDiagID; 333 334 /// \brief First string argument for the delayed diagnostic. 335 std::string DelayedDiagArg1; 336 337 /// \brief Second string argument for the delayed diagnostic. 338 std::string DelayedDiagArg2; 339 340public: 341 explicit DiagnosticsEngine( 342 const IntrusiveRefCntPtr<DiagnosticIDs> &Diags, 343 DiagnosticOptions *DiagOpts, 344 DiagnosticConsumer *client = 0, 345 bool ShouldOwnClient = true); 346 ~DiagnosticsEngine(); 347 348 const IntrusiveRefCntPtr<DiagnosticIDs> &getDiagnosticIDs() const { 349 return Diags; 350 } 351 352 /// \brief Retrieve the diagnostic options. 353 DiagnosticOptions &getDiagnosticOptions() const { return *DiagOpts; } 354 355 DiagnosticConsumer *getClient() { return Client; } 356 const DiagnosticConsumer *getClient() const { return Client; } 357 358 /// \brief Determine whether this \c DiagnosticsEngine object own its client. 359 bool ownsClient() const { return OwnsDiagClient; } 360 361 /// \brief Return the current diagnostic client along with ownership of that 362 /// client. 363 DiagnosticConsumer *takeClient() { 364 OwnsDiagClient = false; 365 return Client; 366 } 367 368 bool hasSourceManager() const { return SourceMgr != 0; } 369 SourceManager &getSourceManager() const { 370 assert(SourceMgr && "SourceManager not set!"); 371 return *SourceMgr; 372 } 373 void setSourceManager(SourceManager *SrcMgr) { SourceMgr = SrcMgr; } 374 375 //===--------------------------------------------------------------------===// 376 // DiagnosticsEngine characterization methods, used by a client to customize 377 // how diagnostics are emitted. 378 // 379 380 /// \brief Copies the current DiagMappings and pushes the new copy 381 /// onto the top of the stack. 382 void pushMappings(SourceLocation Loc); 383 384 /// \brief Pops the current DiagMappings off the top of the stack, 385 /// causing the new top of the stack to be the active mappings. 386 /// 387 /// \returns \c true if the pop happens, \c false if there is only one 388 /// DiagMapping on the stack. 389 bool popMappings(SourceLocation Loc); 390 391 /// \brief Set the diagnostic client associated with this diagnostic object. 392 /// 393 /// \param ShouldOwnClient true if the diagnostic object should take 394 /// ownership of \c client. 395 void setClient(DiagnosticConsumer *client, bool ShouldOwnClient = true); 396 397 /// \brief Specify a limit for the number of errors we should 398 /// emit before giving up. 399 /// 400 /// Zero disables the limit. 401 void setErrorLimit(unsigned Limit) { ErrorLimit = Limit; } 402 403 /// \brief Specify the maximum number of template instantiation 404 /// notes to emit along with a given diagnostic. 405 void setTemplateBacktraceLimit(unsigned Limit) { 406 TemplateBacktraceLimit = Limit; 407 } 408 409 /// \brief Retrieve the maximum number of template instantiation 410 /// notes to emit along with a given diagnostic. 411 unsigned getTemplateBacktraceLimit() const { 412 return TemplateBacktraceLimit; 413 } 414 415 /// \brief Specify the maximum number of constexpr evaluation 416 /// notes to emit along with a given diagnostic. 417 void setConstexprBacktraceLimit(unsigned Limit) { 418 ConstexprBacktraceLimit = Limit; 419 } 420 421 /// \brief Retrieve the maximum number of constexpr evaluation 422 /// notes to emit along with a given diagnostic. 423 unsigned getConstexprBacktraceLimit() const { 424 return ConstexprBacktraceLimit; 425 } 426 427 /// \brief When set to true, any unmapped warnings are ignored. 428 /// 429 /// If this and WarningsAsErrors are both set, then this one wins. 430 void setIgnoreAllWarnings(bool Val) { IgnoreAllWarnings = Val; } 431 bool getIgnoreAllWarnings() const { return IgnoreAllWarnings; } 432 433 /// \brief When set to true, any unmapped ignored warnings are no longer 434 /// ignored. 435 /// 436 /// If this and IgnoreAllWarnings are both set, then that one wins. 437 void setEnableAllWarnings(bool Val) { EnableAllWarnings = Val; } 438 bool getEnableAllWarnngs() const { return EnableAllWarnings; } 439 440 /// \brief When set to true, any warnings reported are issued as errors. 441 void setWarningsAsErrors(bool Val) { WarningsAsErrors = Val; } 442 bool getWarningsAsErrors() const { return WarningsAsErrors; } 443 444 /// \brief When set to true, any error reported is made a fatal error. 445 void setErrorsAsFatal(bool Val) { ErrorsAsFatal = Val; } 446 bool getErrorsAsFatal() const { return ErrorsAsFatal; } 447 448 /// \brief When set to true mask warnings that come from system headers. 449 void setSuppressSystemWarnings(bool Val) { SuppressSystemWarnings = Val; } 450 bool getSuppressSystemWarnings() const { return SuppressSystemWarnings; } 451 452 /// \brief Suppress all diagnostics, to silence the front end when we 453 /// know that we don't want any more diagnostics to be passed along to the 454 /// client 455 void setSuppressAllDiagnostics(bool Val = true) { 456 SuppressAllDiagnostics = Val; 457 } 458 bool getSuppressAllDiagnostics() const { return SuppressAllDiagnostics; } 459 460 /// \brief Set type eliding, to skip outputting same types occurring in 461 /// template types. 462 void setElideType(bool Val = true) { ElideType = Val; } 463 bool getElideType() { return ElideType; } 464 465 /// \brief Set tree printing, to outputting the template difference in a 466 /// tree format. 467 void setPrintTemplateTree(bool Val = false) { PrintTemplateTree = Val; } 468 bool getPrintTemplateTree() { return PrintTemplateTree; } 469 470 /// \brief Set color printing, so the type diffing will inject color markers 471 /// into the output. 472 void setShowColors(bool Val = false) { ShowColors = Val; } 473 bool getShowColors() { return ShowColors; } 474 475 /// \brief Specify which overload candidates to show when overload resolution 476 /// fails. 477 /// 478 /// By default, we show all candidates. 479 void setShowOverloads(OverloadsShown Val) { 480 ShowOverloads = Val; 481 } 482 OverloadsShown getShowOverloads() const { return ShowOverloads; } 483 484 /// \brief Pretend that the last diagnostic issued was ignored, so any 485 /// subsequent notes will be suppressed. 486 /// 487 /// This can be used by clients who suppress diagnostics themselves. 488 void setLastDiagnosticIgnored() { 489 if (LastDiagLevel == DiagnosticIDs::Fatal) 490 FatalErrorOccurred = true; 491 LastDiagLevel = DiagnosticIDs::Ignored; 492 } 493 494 /// \brief Controls whether otherwise-unmapped extension diagnostics are 495 /// mapped onto ignore/warning/error. 496 /// 497 /// This corresponds to the GCC -pedantic and -pedantic-errors option. 498 void setExtensionHandlingBehavior(ExtensionHandling H) { 499 ExtBehavior = H; 500 } 501 ExtensionHandling getExtensionHandlingBehavior() const { return ExtBehavior; } 502 503 /// \brief Counter bumped when an __extension__ block is/ encountered. 504 /// 505 /// When non-zero, all extension diagnostics are entirely silenced, no 506 /// matter how they are mapped. 507 void IncrementAllExtensionsSilenced() { ++AllExtensionsSilenced; } 508 void DecrementAllExtensionsSilenced() { --AllExtensionsSilenced; } 509 bool hasAllExtensionsSilenced() { return AllExtensionsSilenced != 0; } 510 511 /// \brief This allows the client to specify that certain warnings are 512 /// ignored. 513 /// 514 /// Notes can never be mapped, errors can only be mapped to fatal, and 515 /// WARNINGs and EXTENSIONs can be mapped arbitrarily. 516 /// 517 /// \param Loc The source location that this change of diagnostic state should 518 /// take affect. It can be null if we are setting the latest state. 519 void setDiagnosticMapping(diag::kind Diag, diag::Mapping Map, 520 SourceLocation Loc); 521 522 /// \brief Change an entire diagnostic group (e.g. "unknown-pragmas") to 523 /// have the specified mapping. 524 /// 525 /// \returns true (and ignores the request) if "Group" was unknown, false 526 /// otherwise. 527 /// 528 /// \param Loc The source location that this change of diagnostic state should 529 /// take affect. It can be null if we are setting the state from command-line. 530 bool setDiagnosticGroupMapping(StringRef Group, diag::Mapping Map, 531 SourceLocation Loc = SourceLocation()); 532 533 /// \brief Set the warning-as-error flag for the given diagnostic. 534 /// 535 /// This function always only operates on the current diagnostic state. 536 void setDiagnosticWarningAsError(diag::kind Diag, bool Enabled); 537 538 /// \brief Set the warning-as-error flag for the given diagnostic group. 539 /// 540 /// This function always only operates on the current diagnostic state. 541 /// 542 /// \returns True if the given group is unknown, false otherwise. 543 bool setDiagnosticGroupWarningAsError(StringRef Group, bool Enabled); 544 545 /// \brief Set the error-as-fatal flag for the given diagnostic. 546 /// 547 /// This function always only operates on the current diagnostic state. 548 void setDiagnosticErrorAsFatal(diag::kind Diag, bool Enabled); 549 550 /// \brief Set the error-as-fatal flag for the given diagnostic group. 551 /// 552 /// This function always only operates on the current diagnostic state. 553 /// 554 /// \returns True if the given group is unknown, false otherwise. 555 bool setDiagnosticGroupErrorAsFatal(StringRef Group, bool Enabled); 556 557 /// \brief Add the specified mapping to all diagnostics. 558 /// 559 /// Mainly to be used by -Wno-everything to disable all warnings but allow 560 /// subsequent -W options to enable specific warnings. 561 void setMappingToAllDiagnostics(diag::Mapping Map, 562 SourceLocation Loc = SourceLocation()); 563 564 bool hasErrorOccurred() const { return ErrorOccurred; } 565 566 /// \brief Errors that actually prevent compilation, not those that are 567 /// upgraded from a warning by -Werror. 568 bool hasUncompilableErrorOccurred() const { 569 return UncompilableErrorOccurred; 570 } 571 bool hasFatalErrorOccurred() const { return FatalErrorOccurred; } 572 573 /// \brief Determine whether any kind of unrecoverable error has occurred. 574 bool hasUnrecoverableErrorOccurred() const { 575 return FatalErrorOccurred || UnrecoverableErrorOccurred; 576 } 577 578 unsigned getNumWarnings() const { return NumWarnings; } 579 580 void setNumWarnings(unsigned NumWarnings) { 581 this->NumWarnings = NumWarnings; 582 } 583 584 /// \brief Return an ID for a diagnostic with the specified message and level. 585 /// 586 /// If this is the first request for this diagnosic, it is registered and 587 /// created, otherwise the existing ID is returned. 588 unsigned getCustomDiagID(Level L, StringRef Message) { 589 return Diags->getCustomDiagID((DiagnosticIDs::Level)L, Message); 590 } 591 592 /// \brief Converts a diagnostic argument (as an intptr_t) into the string 593 /// that represents it. 594 void ConvertArgToString(ArgumentKind Kind, intptr_t Val, 595 const char *Modifier, unsigned ModLen, 596 const char *Argument, unsigned ArgLen, 597 const ArgumentValue *PrevArgs, unsigned NumPrevArgs, 598 SmallVectorImpl<char> &Output, 599 ArrayRef<intptr_t> QualTypeVals) const { 600 ArgToStringFn(Kind, Val, Modifier, ModLen, Argument, ArgLen, 601 PrevArgs, NumPrevArgs, Output, ArgToStringCookie, 602 QualTypeVals); 603 } 604 605 void SetArgToStringFn(ArgToStringFnTy Fn, void *Cookie) { 606 ArgToStringFn = Fn; 607 ArgToStringCookie = Cookie; 608 } 609 610 /// \brief Note that the prior diagnostic was emitted by some other 611 /// \c DiagnosticsEngine, and we may be attaching a note to that diagnostic. 612 void notePriorDiagnosticFrom(const DiagnosticsEngine &Other) { 613 LastDiagLevel = Other.LastDiagLevel; 614 } 615 616 /// \brief Reset the state of the diagnostic object to its initial 617 /// configuration. 618 void Reset(); 619 620 //===--------------------------------------------------------------------===// 621 // DiagnosticsEngine classification and reporting interfaces. 622 // 623 624 /// \brief Based on the way the client configured the DiagnosticsEngine 625 /// object, classify the specified diagnostic ID into a Level, consumable by 626 /// the DiagnosticConsumer. 627 /// 628 /// \param Loc The source location we are interested in finding out the 629 /// diagnostic state. Can be null in order to query the latest state. 630 Level getDiagnosticLevel(unsigned DiagID, SourceLocation Loc) const { 631 return (Level)Diags->getDiagnosticLevel(DiagID, Loc, *this); 632 } 633 634 /// \brief Issue the message to the client. 635 /// 636 /// This actually returns an instance of DiagnosticBuilder which emits the 637 /// diagnostics (through @c ProcessDiag) when it is destroyed. 638 /// 639 /// \param DiagID A member of the @c diag::kind enum. 640 /// \param Loc Represents the source location associated with the diagnostic, 641 /// which can be an invalid location if no position information is available. 642 inline DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID); 643 inline DiagnosticBuilder Report(unsigned DiagID); 644 645 void Report(const StoredDiagnostic &storedDiag); 646 647 /// \brief Determine whethere there is already a diagnostic in flight. 648 bool isDiagnosticInFlight() const { return CurDiagID != ~0U; } 649 650 /// \brief Set the "delayed" diagnostic that will be emitted once 651 /// the current diagnostic completes. 652 /// 653 /// If a diagnostic is already in-flight but the front end must 654 /// report a problem (e.g., with an inconsistent file system 655 /// state), this routine sets a "delayed" diagnostic that will be 656 /// emitted after the current diagnostic completes. This should 657 /// only be used for fatal errors detected at inconvenient 658 /// times. If emitting a delayed diagnostic causes a second delayed 659 /// diagnostic to be introduced, that second delayed diagnostic 660 /// will be ignored. 661 /// 662 /// \param DiagID The ID of the diagnostic being delayed. 663 /// 664 /// \param Arg1 A string argument that will be provided to the 665 /// diagnostic. A copy of this string will be stored in the 666 /// DiagnosticsEngine object itself. 667 /// 668 /// \param Arg2 A string argument that will be provided to the 669 /// diagnostic. A copy of this string will be stored in the 670 /// DiagnosticsEngine object itself. 671 void SetDelayedDiagnostic(unsigned DiagID, StringRef Arg1 = "", 672 StringRef Arg2 = ""); 673 674 /// \brief Clear out the current diagnostic. 675 void Clear() { CurDiagID = ~0U; } 676 677private: 678 /// \brief Report the delayed diagnostic. 679 void ReportDelayed(); 680 681 // This is private state used by DiagnosticBuilder. We put it here instead of 682 // in DiagnosticBuilder in order to keep DiagnosticBuilder a small lightweight 683 // object. This implementation choice means that we can only have one 684 // diagnostic "in flight" at a time, but this seems to be a reasonable 685 // tradeoff to keep these objects small. Assertions verify that only one 686 // diagnostic is in flight at a time. 687 friend class DiagnosticIDs; 688 friend class DiagnosticBuilder; 689 friend class Diagnostic; 690 friend class PartialDiagnostic; 691 friend class DiagnosticErrorTrap; 692 693 /// \brief The location of the current diagnostic that is in flight. 694 SourceLocation CurDiagLoc; 695 696 /// \brief The ID of the current diagnostic that is in flight. 697 /// 698 /// This is set to ~0U when there is no diagnostic in flight. 699 unsigned CurDiagID; 700 701 enum { 702 /// \brief The maximum number of arguments we can hold. 703 /// 704 /// We currently only support up to 10 arguments (%0-%9). A single 705 /// diagnostic with more than that almost certainly has to be simplified 706 /// anyway. 707 MaxArguments = 10, 708 709 /// \brief The maximum number of ranges we can hold. 710 MaxRanges = 10, 711 712 /// \brief The maximum number of ranges we can hold. 713 MaxFixItHints = 10 714 }; 715 716 /// \brief The number of entries in Arguments. 717 signed char NumDiagArgs; 718 /// \brief The number of ranges in the DiagRanges array. 719 unsigned char NumDiagRanges; 720 /// \brief The number of hints in the DiagFixItHints array. 721 unsigned char NumDiagFixItHints; 722 723 /// \brief Specifies whether an argument is in DiagArgumentsStr or 724 /// in DiagArguments. 725 /// 726 /// This is an array of ArgumentKind::ArgumentKind enum values, one for each 727 /// argument. 728 unsigned char DiagArgumentsKind[MaxArguments]; 729 730 /// \brief Holds the values of each string argument for the current 731 /// diagnostic. 732 /// 733 /// This is only used when the corresponding ArgumentKind is ak_std_string. 734 std::string DiagArgumentsStr[MaxArguments]; 735 736 /// \brief The values for the various substitution positions. 737 /// 738 /// This is used when the argument is not an std::string. The specific 739 /// value is mangled into an intptr_t and the interpretation depends on 740 /// exactly what sort of argument kind it is. 741 intptr_t DiagArgumentsVal[MaxArguments]; 742 743 /// \brief The list of ranges added to this diagnostic. 744 CharSourceRange DiagRanges[MaxRanges]; 745 746 /// \brief If valid, provides a hint with some code to insert, remove, 747 /// or modify at a particular position. 748 FixItHint DiagFixItHints[MaxFixItHints]; 749 750 DiagnosticMappingInfo makeMappingInfo(diag::Mapping Map, SourceLocation L) { 751 bool isPragma = L.isValid(); 752 DiagnosticMappingInfo MappingInfo = DiagnosticMappingInfo::Make( 753 Map, /*IsUser=*/true, isPragma); 754 755 // If this is a pragma mapping, then set the diagnostic mapping flags so 756 // that we override command line options. 757 if (isPragma) { 758 MappingInfo.setNoWarningAsError(true); 759 MappingInfo.setNoErrorAsFatal(true); 760 } 761 762 return MappingInfo; 763 } 764 765 /// \brief Used to report a diagnostic that is finally fully formed. 766 /// 767 /// \returns true if the diagnostic was emitted, false if it was suppressed. 768 bool ProcessDiag() { 769 return Diags->ProcessDiag(*this); 770 } 771 772 /// @name Diagnostic Emission 773 /// @{ 774protected: 775 // Sema requires access to the following functions because the current design 776 // of SFINAE requires it to use its own SemaDiagnosticBuilder, which needs to 777 // access us directly to ensure we minimize the emitted code for the common 778 // Sema::Diag() patterns. 779 friend class Sema; 780 781 /// \brief Emit the current diagnostic and clear the diagnostic state. 782 /// 783 /// \param Force Emit the diagnostic regardless of suppression settings. 784 bool EmitCurrentDiagnostic(bool Force = false); 785 786 unsigned getCurrentDiagID() const { return CurDiagID; } 787 788 SourceLocation getCurrentDiagLoc() const { return CurDiagLoc; } 789 790 /// @} 791 792 friend class ASTReader; 793 friend class ASTWriter; 794}; 795 796/// \brief RAII class that determines when any errors have occurred 797/// between the time the instance was created and the time it was 798/// queried. 799class DiagnosticErrorTrap { 800 DiagnosticsEngine &Diag; 801 unsigned NumErrors; 802 unsigned NumUnrecoverableErrors; 803 804public: 805 explicit DiagnosticErrorTrap(DiagnosticsEngine &Diag) 806 : Diag(Diag) { reset(); } 807 808 /// \brief Determine whether any errors have occurred since this 809 /// object instance was created. 810 bool hasErrorOccurred() const { 811 return Diag.TrapNumErrorsOccurred > NumErrors; 812 } 813 814 /// \brief Determine whether any unrecoverable errors have occurred since this 815 /// object instance was created. 816 bool hasUnrecoverableErrorOccurred() const { 817 return Diag.TrapNumUnrecoverableErrorsOccurred > NumUnrecoverableErrors; 818 } 819 820 /// \brief Set to initial state of "no errors occurred". 821 void reset() { 822 NumErrors = Diag.TrapNumErrorsOccurred; 823 NumUnrecoverableErrors = Diag.TrapNumUnrecoverableErrorsOccurred; 824 } 825}; 826 827//===----------------------------------------------------------------------===// 828// DiagnosticBuilder 829//===----------------------------------------------------------------------===// 830 831/// \brief A little helper class used to produce diagnostics. 832/// 833/// This is constructed by the DiagnosticsEngine::Report method, and 834/// allows insertion of extra information (arguments and source ranges) into 835/// the currently "in flight" diagnostic. When the temporary for the builder 836/// is destroyed, the diagnostic is issued. 837/// 838/// Note that many of these will be created as temporary objects (many call 839/// sites), so we want them to be small and we never want their address taken. 840/// This ensures that compilers with somewhat reasonable optimizers will promote 841/// the common fields to registers, eliminating increments of the NumArgs field, 842/// for example. 843class DiagnosticBuilder { 844 mutable DiagnosticsEngine *DiagObj; 845 mutable unsigned NumArgs, NumRanges, NumFixits; 846 847 /// \brief Status variable indicating if this diagnostic is still active. 848 /// 849 // NOTE: This field is redundant with DiagObj (IsActive iff (DiagObj == 0)), 850 // but LLVM is not currently smart enough to eliminate the null check that 851 // Emit() would end up with if we used that as our status variable. 852 mutable bool IsActive; 853 854 /// \brief Flag indicating that this diagnostic is being emitted via a 855 /// call to ForceEmit. 856 mutable bool IsForceEmit; 857 858 void operator=(const DiagnosticBuilder &) LLVM_DELETED_FUNCTION; 859 friend class DiagnosticsEngine; 860 861 DiagnosticBuilder() 862 : DiagObj(0), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(false), 863 IsForceEmit(false) { } 864 865 explicit DiagnosticBuilder(DiagnosticsEngine *diagObj) 866 : DiagObj(diagObj), NumArgs(0), NumRanges(0), NumFixits(0), IsActive(true), 867 IsForceEmit(false) { 868 assert(diagObj && "DiagnosticBuilder requires a valid DiagnosticsEngine!"); 869 } 870 871 friend class PartialDiagnostic; 872 873protected: 874 void FlushCounts() { 875 DiagObj->NumDiagArgs = NumArgs; 876 DiagObj->NumDiagRanges = NumRanges; 877 DiagObj->NumDiagFixItHints = NumFixits; 878 } 879 880 /// \brief Clear out the current diagnostic. 881 void Clear() const { 882 DiagObj = 0; 883 IsActive = false; 884 IsForceEmit = false; 885 } 886 887 /// \brief Determine whether this diagnostic is still active. 888 bool isActive() const { return IsActive; } 889 890 /// \brief Force the diagnostic builder to emit the diagnostic now. 891 /// 892 /// Once this function has been called, the DiagnosticBuilder object 893 /// should not be used again before it is destroyed. 894 /// 895 /// \returns true if a diagnostic was emitted, false if the 896 /// diagnostic was suppressed. 897 bool Emit() { 898 // If this diagnostic is inactive, then its soul was stolen by the copy ctor 899 // (or by a subclass, as in SemaDiagnosticBuilder). 900 if (!isActive()) return false; 901 902 // When emitting diagnostics, we set the final argument count into 903 // the DiagnosticsEngine object. 904 FlushCounts(); 905 906 // Process the diagnostic. 907 bool Result = DiagObj->EmitCurrentDiagnostic(IsForceEmit); 908 909 // This diagnostic is dead. 910 Clear(); 911 912 return Result; 913 } 914 915public: 916 /// Copy constructor. When copied, this "takes" the diagnostic info from the 917 /// input and neuters it. 918 DiagnosticBuilder(const DiagnosticBuilder &D) { 919 DiagObj = D.DiagObj; 920 IsActive = D.IsActive; 921 IsForceEmit = D.IsForceEmit; 922 D.Clear(); 923 NumArgs = D.NumArgs; 924 NumRanges = D.NumRanges; 925 NumFixits = D.NumFixits; 926 } 927 928 /// \brief Retrieve an empty diagnostic builder. 929 static DiagnosticBuilder getEmpty() { 930 return DiagnosticBuilder(); 931 } 932 933 /// \brief Emits the diagnostic. 934 ~DiagnosticBuilder() { 935 Emit(); 936 } 937 938 /// \brief Forces the diagnostic to be emitted. 939 const DiagnosticBuilder &setForceEmit() const { 940 IsForceEmit = true; 941 return *this; 942 } 943 944 /// \brief Conversion of DiagnosticBuilder to bool always returns \c true. 945 /// 946 /// This allows is to be used in boolean error contexts (where \c true is 947 /// used to indicate that an error has occurred), like: 948 /// \code 949 /// return Diag(...); 950 /// \endcode 951 operator bool() const { return true; } 952 953 void AddString(StringRef S) const { 954 assert(isActive() && "Clients must not add to cleared diagnostic!"); 955 assert(NumArgs < DiagnosticsEngine::MaxArguments && 956 "Too many arguments to diagnostic!"); 957 DiagObj->DiagArgumentsKind[NumArgs] = DiagnosticsEngine::ak_std_string; 958 DiagObj->DiagArgumentsStr[NumArgs++] = S; 959 } 960 961 void AddTaggedVal(intptr_t V, DiagnosticsEngine::ArgumentKind Kind) const { 962 assert(isActive() && "Clients must not add to cleared diagnostic!"); 963 assert(NumArgs < DiagnosticsEngine::MaxArguments && 964 "Too many arguments to diagnostic!"); 965 DiagObj->DiagArgumentsKind[NumArgs] = Kind; 966 DiagObj->DiagArgumentsVal[NumArgs++] = V; 967 } 968 969 void AddSourceRange(const CharSourceRange &R) const { 970 assert(isActive() && "Clients must not add to cleared diagnostic!"); 971 assert(NumRanges < DiagnosticsEngine::MaxRanges && 972 "Too many arguments to diagnostic!"); 973 DiagObj->DiagRanges[NumRanges++] = R; 974 } 975 976 void AddFixItHint(const FixItHint &Hint) const { 977 assert(isActive() && "Clients must not add to cleared diagnostic!"); 978 assert(NumFixits < DiagnosticsEngine::MaxFixItHints && 979 "Too many arguments to diagnostic!"); 980 DiagObj->DiagFixItHints[NumFixits++] = Hint; 981 } 982 983 bool hasMaxRanges() const { 984 return NumRanges == DiagnosticsEngine::MaxRanges; 985 } 986}; 987 988inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 989 StringRef S) { 990 DB.AddString(S); 991 return DB; 992} 993 994inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 995 const char *Str) { 996 DB.AddTaggedVal(reinterpret_cast<intptr_t>(Str), 997 DiagnosticsEngine::ak_c_string); 998 return DB; 999} 1000 1001inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, int I) { 1002 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint); 1003 return DB; 1004} 1005 1006inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB,bool I) { 1007 DB.AddTaggedVal(I, DiagnosticsEngine::ak_sint); 1008 return DB; 1009} 1010 1011inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 1012 unsigned I) { 1013 DB.AddTaggedVal(I, DiagnosticsEngine::ak_uint); 1014 return DB; 1015} 1016 1017inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 1018 const IdentifierInfo *II) { 1019 DB.AddTaggedVal(reinterpret_cast<intptr_t>(II), 1020 DiagnosticsEngine::ak_identifierinfo); 1021 return DB; 1022} 1023 1024// Adds a DeclContext to the diagnostic. The enable_if template magic is here 1025// so that we only match those arguments that are (statically) DeclContexts; 1026// other arguments that derive from DeclContext (e.g., RecordDecls) will not 1027// match. 1028template<typename T> 1029inline 1030typename llvm::enable_if<llvm::is_same<T, DeclContext>, 1031 const DiagnosticBuilder &>::type 1032operator<<(const DiagnosticBuilder &DB, T *DC) { 1033 DB.AddTaggedVal(reinterpret_cast<intptr_t>(DC), 1034 DiagnosticsEngine::ak_declcontext); 1035 return DB; 1036} 1037 1038inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 1039 const SourceRange &R) { 1040 DB.AddSourceRange(CharSourceRange::getTokenRange(R)); 1041 return DB; 1042} 1043 1044inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 1045 const CharSourceRange &R) { 1046 DB.AddSourceRange(R); 1047 return DB; 1048} 1049 1050inline const DiagnosticBuilder &operator<<(const DiagnosticBuilder &DB, 1051 const FixItHint &Hint) { 1052 if (!Hint.isNull()) 1053 DB.AddFixItHint(Hint); 1054 return DB; 1055} 1056 1057inline DiagnosticBuilder DiagnosticsEngine::Report(SourceLocation Loc, 1058 unsigned DiagID){ 1059 assert(CurDiagID == ~0U && "Multiple diagnostics in flight at once!"); 1060 CurDiagLoc = Loc; 1061 CurDiagID = DiagID; 1062 return DiagnosticBuilder(this); 1063} 1064inline DiagnosticBuilder DiagnosticsEngine::Report(unsigned DiagID) { 1065 return Report(SourceLocation(), DiagID); 1066} 1067 1068//===----------------------------------------------------------------------===// 1069// Diagnostic 1070//===----------------------------------------------------------------------===// 1071 1072/// A little helper class (which is basically a smart pointer that forwards 1073/// info from DiagnosticsEngine) that allows clients to enquire about the 1074/// currently in-flight diagnostic. 1075class Diagnostic { 1076 const DiagnosticsEngine *DiagObj; 1077 StringRef StoredDiagMessage; 1078public: 1079 explicit Diagnostic(const DiagnosticsEngine *DO) : DiagObj(DO) {} 1080 Diagnostic(const DiagnosticsEngine *DO, StringRef storedDiagMessage) 1081 : DiagObj(DO), StoredDiagMessage(storedDiagMessage) {} 1082 1083 const DiagnosticsEngine *getDiags() const { return DiagObj; } 1084 unsigned getID() const { return DiagObj->CurDiagID; } 1085 const SourceLocation &getLocation() const { return DiagObj->CurDiagLoc; } 1086 bool hasSourceManager() const { return DiagObj->hasSourceManager(); } 1087 SourceManager &getSourceManager() const { return DiagObj->getSourceManager();} 1088 1089 unsigned getNumArgs() const { return DiagObj->NumDiagArgs; } 1090 1091 /// \brief Return the kind of the specified index. 1092 /// 1093 /// Based on the kind of argument, the accessors below can be used to get 1094 /// the value. 1095 /// 1096 /// \pre Idx < getNumArgs() 1097 DiagnosticsEngine::ArgumentKind getArgKind(unsigned Idx) const { 1098 assert(Idx < getNumArgs() && "Argument index out of range!"); 1099 return (DiagnosticsEngine::ArgumentKind)DiagObj->DiagArgumentsKind[Idx]; 1100 } 1101 1102 /// \brief Return the provided argument string specified by \p Idx. 1103 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_std_string 1104 const std::string &getArgStdStr(unsigned Idx) const { 1105 assert(getArgKind(Idx) == DiagnosticsEngine::ak_std_string && 1106 "invalid argument accessor!"); 1107 return DiagObj->DiagArgumentsStr[Idx]; 1108 } 1109 1110 /// \brief Return the specified C string argument. 1111 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_c_string 1112 const char *getArgCStr(unsigned Idx) const { 1113 assert(getArgKind(Idx) == DiagnosticsEngine::ak_c_string && 1114 "invalid argument accessor!"); 1115 return reinterpret_cast<const char*>(DiagObj->DiagArgumentsVal[Idx]); 1116 } 1117 1118 /// \brief Return the specified signed integer argument. 1119 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_sint 1120 int getArgSInt(unsigned Idx) const { 1121 assert(getArgKind(Idx) == DiagnosticsEngine::ak_sint && 1122 "invalid argument accessor!"); 1123 return (int)DiagObj->DiagArgumentsVal[Idx]; 1124 } 1125 1126 /// \brief Return the specified unsigned integer argument. 1127 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_uint 1128 unsigned getArgUInt(unsigned Idx) const { 1129 assert(getArgKind(Idx) == DiagnosticsEngine::ak_uint && 1130 "invalid argument accessor!"); 1131 return (unsigned)DiagObj->DiagArgumentsVal[Idx]; 1132 } 1133 1134 /// \brief Return the specified IdentifierInfo argument. 1135 /// \pre getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo 1136 const IdentifierInfo *getArgIdentifier(unsigned Idx) const { 1137 assert(getArgKind(Idx) == DiagnosticsEngine::ak_identifierinfo && 1138 "invalid argument accessor!"); 1139 return reinterpret_cast<IdentifierInfo*>(DiagObj->DiagArgumentsVal[Idx]); 1140 } 1141 1142 /// \brief Return the specified non-string argument in an opaque form. 1143 /// \pre getArgKind(Idx) != DiagnosticsEngine::ak_std_string 1144 intptr_t getRawArg(unsigned Idx) const { 1145 assert(getArgKind(Idx) != DiagnosticsEngine::ak_std_string && 1146 "invalid argument accessor!"); 1147 return DiagObj->DiagArgumentsVal[Idx]; 1148 } 1149 1150 /// \brief Return the number of source ranges associated with this diagnostic. 1151 unsigned getNumRanges() const { 1152 return DiagObj->NumDiagRanges; 1153 } 1154 1155 /// \pre Idx < getNumRanges() 1156 const CharSourceRange &getRange(unsigned Idx) const { 1157 assert(Idx < DiagObj->NumDiagRanges && "Invalid diagnostic range index!"); 1158 return DiagObj->DiagRanges[Idx]; 1159 } 1160 1161 /// \brief Return an array reference for this diagnostic's ranges. 1162 ArrayRef<CharSourceRange> getRanges() const { 1163 return llvm::makeArrayRef(DiagObj->DiagRanges, DiagObj->NumDiagRanges); 1164 } 1165 1166 unsigned getNumFixItHints() const { 1167 return DiagObj->NumDiagFixItHints; 1168 } 1169 1170 const FixItHint &getFixItHint(unsigned Idx) const { 1171 assert(Idx < getNumFixItHints() && "Invalid index!"); 1172 return DiagObj->DiagFixItHints[Idx]; 1173 } 1174 1175 const FixItHint *getFixItHints() const { 1176 return getNumFixItHints()? DiagObj->DiagFixItHints : 0; 1177 } 1178 1179 /// \brief Format this diagnostic into a string, substituting the 1180 /// formal arguments into the %0 slots. 1181 /// 1182 /// The result is appended onto the \p OutStr array. 1183 void FormatDiagnostic(SmallVectorImpl<char> &OutStr) const; 1184 1185 /// \brief Format the given format-string into the output buffer using the 1186 /// arguments stored in this diagnostic. 1187 void FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 1188 SmallVectorImpl<char> &OutStr) const; 1189}; 1190 1191/** 1192 * \brief Represents a diagnostic in a form that can be retained until its 1193 * corresponding source manager is destroyed. 1194 */ 1195class StoredDiagnostic { 1196 unsigned ID; 1197 DiagnosticsEngine::Level Level; 1198 FullSourceLoc Loc; 1199 std::string Message; 1200 std::vector<CharSourceRange> Ranges; 1201 std::vector<FixItHint> FixIts; 1202 1203public: 1204 StoredDiagnostic(); 1205 StoredDiagnostic(DiagnosticsEngine::Level Level, const Diagnostic &Info); 1206 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 1207 StringRef Message); 1208 StoredDiagnostic(DiagnosticsEngine::Level Level, unsigned ID, 1209 StringRef Message, FullSourceLoc Loc, 1210 ArrayRef<CharSourceRange> Ranges, 1211 ArrayRef<FixItHint> Fixits); 1212 ~StoredDiagnostic(); 1213 1214 /// \brief Evaluates true when this object stores a diagnostic. 1215 operator bool() const { return Message.size() > 0; } 1216 1217 unsigned getID() const { return ID; } 1218 DiagnosticsEngine::Level getLevel() const { return Level; } 1219 const FullSourceLoc &getLocation() const { return Loc; } 1220 StringRef getMessage() const { return Message; } 1221 1222 void setLocation(FullSourceLoc Loc) { this->Loc = Loc; } 1223 1224 typedef std::vector<CharSourceRange>::const_iterator range_iterator; 1225 range_iterator range_begin() const { return Ranges.begin(); } 1226 range_iterator range_end() const { return Ranges.end(); } 1227 unsigned range_size() const { return Ranges.size(); } 1228 1229 ArrayRef<CharSourceRange> getRanges() const { 1230 return llvm::makeArrayRef(Ranges); 1231 } 1232 1233 1234 typedef std::vector<FixItHint>::const_iterator fixit_iterator; 1235 fixit_iterator fixit_begin() const { return FixIts.begin(); } 1236 fixit_iterator fixit_end() const { return FixIts.end(); } 1237 unsigned fixit_size() const { return FixIts.size(); } 1238 1239 ArrayRef<FixItHint> getFixIts() const { 1240 return llvm::makeArrayRef(FixIts); 1241 } 1242}; 1243 1244/// \brief Abstract interface, implemented by clients of the front-end, which 1245/// formats and prints fully processed diagnostics. 1246class DiagnosticConsumer { 1247protected: 1248 unsigned NumWarnings; ///< Number of warnings reported 1249 unsigned NumErrors; ///< Number of errors reported 1250 1251public: 1252 DiagnosticConsumer() : NumWarnings(0), NumErrors(0) { } 1253 1254 unsigned getNumErrors() const { return NumErrors; } 1255 unsigned getNumWarnings() const { return NumWarnings; } 1256 virtual void clear() { NumWarnings = NumErrors = 0; } 1257 1258 virtual ~DiagnosticConsumer(); 1259 1260 /// \brief Callback to inform the diagnostic client that processing 1261 /// of a source file is beginning. 1262 /// 1263 /// Note that diagnostics may be emitted outside the processing of a source 1264 /// file, for example during the parsing of command line options. However, 1265 /// diagnostics with source range information are required to only be emitted 1266 /// in between BeginSourceFile() and EndSourceFile(). 1267 /// 1268 /// \param LangOpts The language options for the source file being processed. 1269 /// \param PP The preprocessor object being used for the source; this is 1270 /// optional, e.g., it may not be present when processing AST source files. 1271 virtual void BeginSourceFile(const LangOptions &LangOpts, 1272 const Preprocessor *PP = 0) {} 1273 1274 /// \brief Callback to inform the diagnostic client that processing 1275 /// of a source file has ended. 1276 /// 1277 /// The diagnostic client should assume that any objects made available via 1278 /// BeginSourceFile() are inaccessible. 1279 virtual void EndSourceFile() {} 1280 1281 /// \brief Callback to inform the diagnostic client that processing of all 1282 /// source files has ended. 1283 virtual void finish() {} 1284 1285 /// \brief Indicates whether the diagnostics handled by this 1286 /// DiagnosticConsumer should be included in the number of diagnostics 1287 /// reported by DiagnosticsEngine. 1288 /// 1289 /// The default implementation returns true. 1290 virtual bool IncludeInDiagnosticCounts() const; 1291 1292 /// \brief Handle this diagnostic, reporting it to the user or 1293 /// capturing it to a log as needed. 1294 /// 1295 /// The default implementation just keeps track of the total number of 1296 /// warnings and errors. 1297 virtual void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 1298 const Diagnostic &Info); 1299 1300 /// \brief Clone the diagnostic consumer, producing an equivalent consumer 1301 /// that can be used in a different context. 1302 virtual DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const = 0; 1303}; 1304 1305/// \brief A diagnostic client that ignores all diagnostics. 1306class IgnoringDiagConsumer : public DiagnosticConsumer { 1307 virtual void anchor(); 1308 void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, 1309 const Diagnostic &Info) { 1310 // Just ignore it. 1311 } 1312 DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { 1313 return new IgnoringDiagConsumer(); 1314 } 1315}; 1316 1317// Struct used for sending info about how a type should be printed. 1318struct TemplateDiffTypes { 1319 intptr_t FromType; 1320 intptr_t ToType; 1321 unsigned PrintTree : 1; 1322 unsigned PrintFromType : 1; 1323 unsigned ElideType : 1; 1324 unsigned ShowColors : 1; 1325 // The printer sets this variable to true if the template diff was used. 1326 unsigned TemplateDiffUsed : 1; 1327}; 1328 1329/// Special character that the diagnostic printer will use to toggle the bold 1330/// attribute. The character itself will be not be printed. 1331const char ToggleHighlight = 127; 1332 1333} // end namespace clang 1334 1335#endif 1336