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