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