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