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