Diagnostic.cpp revision 3c2d3016adec79c81c4efff64e208fd3ecdd92ae
1//===--- Diagnostic.cpp - C Language Family Diagnostic Handling -----------===// 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// This file implements the Diagnostic-related interfaces. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/ASTDiagnostic.h" 15#include "clang/Analysis/AnalysisDiagnostic.h" 16#include "clang/Basic/Diagnostic.h" 17#include "clang/Basic/FileManager.h" 18#include "clang/Basic/IdentifierTable.h" 19#include "clang/Basic/PartialDiagnostic.h" 20#include "clang/Basic/SourceLocation.h" 21#include "clang/Basic/SourceManager.h" 22#include "clang/Driver/DriverDiagnostic.h" 23#include "clang/Frontend/FrontendDiagnostic.h" 24#include "clang/Lex/LexDiagnostic.h" 25#include "clang/Parse/ParseDiagnostic.h" 26#include "clang/Sema/SemaDiagnostic.h" 27#include "llvm/ADT/SmallVector.h" 28#include "llvm/ADT/StringExtras.h" 29#include "llvm/Support/MemoryBuffer.h" 30#include "llvm/Support/raw_ostream.h" 31 32#include <vector> 33#include <map> 34#include <cstring> 35using namespace clang; 36 37//===----------------------------------------------------------------------===// 38// Builtin Diagnostic information 39//===----------------------------------------------------------------------===// 40 41// Diagnostic classes. 42enum { 43 CLASS_NOTE = 0x01, 44 CLASS_WARNING = 0x02, 45 CLASS_EXTENSION = 0x03, 46 CLASS_ERROR = 0x04 47}; 48 49struct StaticDiagInfoRec { 50 unsigned short DiagID; 51 unsigned Mapping : 3; 52 unsigned Class : 3; 53 bool SFINAE : 1; 54 unsigned Category : 5; 55 56 const char *Description; 57 const char *OptionGroup; 58 59 bool operator<(const StaticDiagInfoRec &RHS) const { 60 return DiagID < RHS.DiagID; 61 } 62 bool operator>(const StaticDiagInfoRec &RHS) const { 63 return DiagID > RHS.DiagID; 64 } 65}; 66 67static const StaticDiagInfoRec StaticDiagInfo[] = { 68#define DIAG(ENUM,CLASS,DEFAULT_MAPPING,DESC,GROUP,SFINAE, CATEGORY) \ 69 { diag::ENUM, DEFAULT_MAPPING, CLASS, SFINAE, CATEGORY, DESC, GROUP }, 70#include "clang/Basic/DiagnosticCommonKinds.inc" 71#include "clang/Basic/DiagnosticDriverKinds.inc" 72#include "clang/Basic/DiagnosticFrontendKinds.inc" 73#include "clang/Basic/DiagnosticLexKinds.inc" 74#include "clang/Basic/DiagnosticParseKinds.inc" 75#include "clang/Basic/DiagnosticASTKinds.inc" 76#include "clang/Basic/DiagnosticSemaKinds.inc" 77#include "clang/Basic/DiagnosticAnalysisKinds.inc" 78 { 0, 0, 0, 0, 0, 0, 0} 79}; 80#undef DIAG 81 82/// GetDiagInfo - Return the StaticDiagInfoRec entry for the specified DiagID, 83/// or null if the ID is invalid. 84static const StaticDiagInfoRec *GetDiagInfo(unsigned DiagID) { 85 unsigned NumDiagEntries = sizeof(StaticDiagInfo)/sizeof(StaticDiagInfo[0])-1; 86 87 // If assertions are enabled, verify that the StaticDiagInfo array is sorted. 88#ifndef NDEBUG 89 static bool IsFirst = true; 90 if (IsFirst) { 91 for (unsigned i = 1; i != NumDiagEntries; ++i) { 92 assert(StaticDiagInfo[i-1].DiagID != StaticDiagInfo[i].DiagID && 93 "Diag ID conflict, the enums at the start of clang::diag (in " 94 "Diagnostic.h) probably need to be increased"); 95 96 assert(StaticDiagInfo[i-1] < StaticDiagInfo[i] && 97 "Improperly sorted diag info"); 98 } 99 IsFirst = false; 100 } 101#endif 102 103 // Search the diagnostic table with a binary search. 104 StaticDiagInfoRec Find = { DiagID, 0, 0, 0, 0, 0, 0 }; 105 106 const StaticDiagInfoRec *Found = 107 std::lower_bound(StaticDiagInfo, StaticDiagInfo + NumDiagEntries, Find); 108 if (Found == StaticDiagInfo + NumDiagEntries || 109 Found->DiagID != DiagID) 110 return 0; 111 112 return Found; 113} 114 115static unsigned GetDefaultDiagMapping(unsigned DiagID) { 116 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 117 return Info->Mapping; 118 return diag::MAP_FATAL; 119} 120 121/// getWarningOptionForDiag - Return the lowest-level warning option that 122/// enables the specified diagnostic. If there is no -Wfoo flag that controls 123/// the diagnostic, this returns null. 124const char *Diagnostic::getWarningOptionForDiag(unsigned DiagID) { 125 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 126 return Info->OptionGroup; 127 return 0; 128} 129 130/// getWarningOptionForDiag - Return the category number that a specified 131/// DiagID belongs to, or 0 if no category. 132unsigned Diagnostic::getCategoryNumberForDiag(unsigned DiagID) { 133 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 134 return Info->Category; 135 return 0; 136} 137 138/// getCategoryNameFromID - Given a category ID, return the name of the 139/// category, an empty string if CategoryID is zero, or null if CategoryID is 140/// invalid. 141const char *Diagnostic::getCategoryNameFromID(unsigned CategoryID) { 142 // Second the table of options, sorted by name for fast binary lookup. 143 static const char *CategoryNameTable[] = { 144#define GET_CATEGORY_TABLE 145#define CATEGORY(X) X, 146#include "clang/Basic/DiagnosticGroups.inc" 147#undef GET_CATEGORY_TABLE 148 "<<END>>" 149 }; 150 static const size_t CategoryNameTableSize = 151 sizeof(CategoryNameTable) / sizeof(CategoryNameTable[0])-1; 152 153 if (CategoryID >= CategoryNameTableSize) return 0; 154 return CategoryNameTable[CategoryID]; 155} 156 157 158 159Diagnostic::SFINAEResponse 160Diagnostic::getDiagnosticSFINAEResponse(unsigned DiagID) { 161 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) { 162 if (!Info->SFINAE) 163 return SFINAE_Report; 164 165 if (Info->Class == CLASS_ERROR) 166 return SFINAE_SubstitutionFailure; 167 168 // Suppress notes, warnings, and extensions; 169 return SFINAE_Suppress; 170 } 171 172 return SFINAE_Report; 173} 174 175/// getDiagClass - Return the class field of the diagnostic. 176/// 177static unsigned getBuiltinDiagClass(unsigned DiagID) { 178 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 179 return Info->Class; 180 return ~0U; 181} 182 183//===----------------------------------------------------------------------===// 184// Custom Diagnostic information 185//===----------------------------------------------------------------------===// 186 187namespace clang { 188 namespace diag { 189 class CustomDiagInfo { 190 typedef std::pair<Diagnostic::Level, std::string> DiagDesc; 191 std::vector<DiagDesc> DiagInfo; 192 std::map<DiagDesc, unsigned> DiagIDs; 193 public: 194 195 /// getDescription - Return the description of the specified custom 196 /// diagnostic. 197 const char *getDescription(unsigned DiagID) const { 198 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() && 199 "Invalid diagnosic ID"); 200 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].second.c_str(); 201 } 202 203 /// getLevel - Return the level of the specified custom diagnostic. 204 Diagnostic::Level getLevel(unsigned DiagID) const { 205 assert(this && DiagID-DIAG_UPPER_LIMIT < DiagInfo.size() && 206 "Invalid diagnosic ID"); 207 return DiagInfo[DiagID-DIAG_UPPER_LIMIT].first; 208 } 209 210 unsigned getOrCreateDiagID(Diagnostic::Level L, llvm::StringRef Message, 211 Diagnostic &Diags) { 212 DiagDesc D(L, Message); 213 // Check to see if it already exists. 214 std::map<DiagDesc, unsigned>::iterator I = DiagIDs.lower_bound(D); 215 if (I != DiagIDs.end() && I->first == D) 216 return I->second; 217 218 // If not, assign a new ID. 219 unsigned ID = DiagInfo.size()+DIAG_UPPER_LIMIT; 220 DiagIDs.insert(std::make_pair(D, ID)); 221 DiagInfo.push_back(D); 222 return ID; 223 } 224 }; 225 226 } // end diag namespace 227} // end clang namespace 228 229 230//===----------------------------------------------------------------------===// 231// Common Diagnostic implementation 232//===----------------------------------------------------------------------===// 233 234static void DummyArgToStringFn(Diagnostic::ArgumentKind AK, intptr_t QT, 235 const char *Modifier, unsigned ML, 236 const char *Argument, unsigned ArgLen, 237 const Diagnostic::ArgumentValue *PrevArgs, 238 unsigned NumPrevArgs, 239 llvm::SmallVectorImpl<char> &Output, 240 void *Cookie) { 241 const char *Str = "<can't format argument>"; 242 Output.append(Str, Str+strlen(Str)); 243} 244 245 246Diagnostic::Diagnostic(DiagnosticClient *client) : Client(client) { 247 ArgToStringFn = DummyArgToStringFn; 248 ArgToStringCookie = 0; 249 250 Reset(); 251} 252 253Diagnostic::~Diagnostic() { 254 delete CustomDiagInfo; 255} 256 257 258void Diagnostic::pushMappings() { 259 // Avoids undefined behavior when the stack has to resize. 260 DiagMappingsStack.reserve(DiagMappingsStack.size() + 1); 261 DiagMappingsStack.push_back(DiagMappingsStack.back()); 262} 263 264bool Diagnostic::popMappings() { 265 if (DiagMappingsStack.size() == 1) 266 return false; 267 268 DiagMappingsStack.pop_back(); 269 return true; 270} 271 272/// getCustomDiagID - Return an ID for a diagnostic with the specified message 273/// and level. If this is the first request for this diagnosic, it is 274/// registered and created, otherwise the existing ID is returned. 275unsigned Diagnostic::getCustomDiagID(Level L, llvm::StringRef Message) { 276 if (CustomDiagInfo == 0) 277 CustomDiagInfo = new diag::CustomDiagInfo(); 278 return CustomDiagInfo->getOrCreateDiagID(L, Message, *this); 279} 280 281 282/// isBuiltinWarningOrExtension - Return true if the unmapped diagnostic 283/// level of the specified diagnostic ID is a Warning or Extension. 284/// This only works on builtin diagnostics, not custom ones, and is not legal to 285/// call on NOTEs. 286bool Diagnostic::isBuiltinWarningOrExtension(unsigned DiagID) { 287 return DiagID < diag::DIAG_UPPER_LIMIT && 288 getBuiltinDiagClass(DiagID) != CLASS_ERROR; 289} 290 291/// \brief Determine whether the given built-in diagnostic ID is a 292/// Note. 293bool Diagnostic::isBuiltinNote(unsigned DiagID) { 294 return DiagID < diag::DIAG_UPPER_LIMIT && 295 getBuiltinDiagClass(DiagID) == CLASS_NOTE; 296} 297 298/// isBuiltinExtensionDiag - Determine whether the given built-in diagnostic 299/// ID is for an extension of some sort. This also returns EnabledByDefault, 300/// which is set to indicate whether the diagnostic is ignored by default (in 301/// which case -pedantic enables it) or treated as a warning/error by default. 302/// 303bool Diagnostic::isBuiltinExtensionDiag(unsigned DiagID, 304 bool &EnabledByDefault) { 305 if (DiagID >= diag::DIAG_UPPER_LIMIT || 306 getBuiltinDiagClass(DiagID) != CLASS_EXTENSION) 307 return false; 308 309 EnabledByDefault = StaticDiagInfo[DiagID].Mapping != diag::MAP_IGNORE; 310 return true; 311} 312 313void Diagnostic::Reset() { 314 AllExtensionsSilenced = 0; 315 IgnoreAllWarnings = false; 316 WarningsAsErrors = false; 317 ErrorsAsFatal = false; 318 SuppressSystemWarnings = false; 319 SuppressAllDiagnostics = false; 320 ShowOverloads = Ovl_All; 321 ExtBehavior = Ext_Ignore; 322 323 ErrorOccurred = false; 324 FatalErrorOccurred = false; 325 ErrorLimit = 0; 326 TemplateBacktraceLimit = 0; 327 328 NumWarnings = 0; 329 NumErrors = 0; 330 NumErrorsSuppressed = 0; 331 CustomDiagInfo = 0; 332 CurDiagID = ~0U; 333 LastDiagLevel = Ignored; 334 DelayedDiagID = 0; 335 336 // Set all mappings to 'unset'. 337 DiagMappingsStack.clear(); 338 DiagMappingsStack.push_back(DiagMappings()); 339} 340 341/// getDescription - Given a diagnostic ID, return a description of the 342/// issue. 343const char *Diagnostic::getDescription(unsigned DiagID) const { 344 if (const StaticDiagInfoRec *Info = GetDiagInfo(DiagID)) 345 return Info->Description; 346 return CustomDiagInfo->getDescription(DiagID); 347} 348 349void Diagnostic::SetDelayedDiagnostic(unsigned DiagID, llvm::StringRef Arg1, 350 llvm::StringRef Arg2) { 351 if (DelayedDiagID) 352 return; 353 354 DelayedDiagID = DiagID; 355 DelayedDiagArg1 = Arg1.str(); 356 DelayedDiagArg2 = Arg2.str(); 357} 358 359void Diagnostic::ReportDelayed() { 360 Report(DelayedDiagID) << DelayedDiagArg1 << DelayedDiagArg2; 361 DelayedDiagID = 0; 362 DelayedDiagArg1.clear(); 363 DelayedDiagArg2.clear(); 364} 365 366/// getDiagnosticLevel - Based on the way the client configured the Diagnostic 367/// object, classify the specified diagnostic ID into a Level, consumable by 368/// the DiagnosticClient. 369Diagnostic::Level Diagnostic::getDiagnosticLevel(unsigned DiagID) const { 370 // Handle custom diagnostics, which cannot be mapped. 371 if (DiagID >= diag::DIAG_UPPER_LIMIT) 372 return CustomDiagInfo->getLevel(DiagID); 373 374 unsigned DiagClass = getBuiltinDiagClass(DiagID); 375 assert(DiagClass != CLASS_NOTE && "Cannot get diagnostic level of a note!"); 376 return getDiagnosticLevel(DiagID, DiagClass); 377} 378 379/// getDiagnosticLevel - Based on the way the client configured the Diagnostic 380/// object, classify the specified diagnostic ID into a Level, consumable by 381/// the DiagnosticClient. 382Diagnostic::Level 383Diagnostic::getDiagnosticLevel(unsigned DiagID, unsigned DiagClass) const { 384 // Specific non-error diagnostics may be mapped to various levels from ignored 385 // to error. Errors can only be mapped to fatal. 386 Diagnostic::Level Result = Diagnostic::Fatal; 387 388 // Get the mapping information, if unset, compute it lazily. 389 unsigned MappingInfo = getDiagnosticMappingInfo((diag::kind)DiagID); 390 if (MappingInfo == 0) { 391 MappingInfo = GetDefaultDiagMapping(DiagID); 392 setDiagnosticMappingInternal(DiagID, MappingInfo, false); 393 } 394 395 switch (MappingInfo & 7) { 396 default: assert(0 && "Unknown mapping!"); 397 case diag::MAP_IGNORE: 398 // Ignore this, unless this is an extension diagnostic and we're mapping 399 // them onto warnings or errors. 400 if (!isBuiltinExtensionDiag(DiagID) || // Not an extension 401 ExtBehavior == Ext_Ignore || // Extensions ignored anyway 402 (MappingInfo & 8) != 0) // User explicitly mapped it. 403 return Diagnostic::Ignored; 404 Result = Diagnostic::Warning; 405 if (ExtBehavior == Ext_Error) Result = Diagnostic::Error; 406 if (Result == Diagnostic::Error && ErrorsAsFatal) 407 Result = Diagnostic::Fatal; 408 break; 409 case diag::MAP_ERROR: 410 Result = Diagnostic::Error; 411 if (ErrorsAsFatal) 412 Result = Diagnostic::Fatal; 413 break; 414 case diag::MAP_FATAL: 415 Result = Diagnostic::Fatal; 416 break; 417 case diag::MAP_WARNING: 418 // If warnings are globally mapped to ignore or error, do it. 419 if (IgnoreAllWarnings) 420 return Diagnostic::Ignored; 421 422 Result = Diagnostic::Warning; 423 424 // If this is an extension diagnostic and we're in -pedantic-error mode, and 425 // if the user didn't explicitly map it, upgrade to an error. 426 if (ExtBehavior == Ext_Error && 427 (MappingInfo & 8) == 0 && 428 isBuiltinExtensionDiag(DiagID)) 429 Result = Diagnostic::Error; 430 431 if (WarningsAsErrors) 432 Result = Diagnostic::Error; 433 if (Result == Diagnostic::Error && ErrorsAsFatal) 434 Result = Diagnostic::Fatal; 435 break; 436 437 case diag::MAP_WARNING_NO_WERROR: 438 // Diagnostics specified with -Wno-error=foo should be set to warnings, but 439 // not be adjusted by -Werror or -pedantic-errors. 440 Result = Diagnostic::Warning; 441 442 // If warnings are globally mapped to ignore or error, do it. 443 if (IgnoreAllWarnings) 444 return Diagnostic::Ignored; 445 446 break; 447 448 case diag::MAP_ERROR_NO_WFATAL: 449 // Diagnostics specified as -Wno-fatal-error=foo should be errors, but 450 // unaffected by -Wfatal-errors. 451 Result = Diagnostic::Error; 452 break; 453 } 454 455 // Okay, we're about to return this as a "diagnostic to emit" one last check: 456 // if this is any sort of extension warning, and if we're in an __extension__ 457 // block, silence it. 458 if (AllExtensionsSilenced && isBuiltinExtensionDiag(DiagID)) 459 return Diagnostic::Ignored; 460 461 return Result; 462} 463 464struct WarningOption { 465 const char *Name; 466 const short *Members; 467 const short *SubGroups; 468}; 469 470#define GET_DIAG_ARRAYS 471#include "clang/Basic/DiagnosticGroups.inc" 472#undef GET_DIAG_ARRAYS 473 474// Second the table of options, sorted by name for fast binary lookup. 475static const WarningOption OptionTable[] = { 476#define GET_DIAG_TABLE 477#include "clang/Basic/DiagnosticGroups.inc" 478#undef GET_DIAG_TABLE 479}; 480static const size_t OptionTableSize = 481sizeof(OptionTable) / sizeof(OptionTable[0]); 482 483static bool WarningOptionCompare(const WarningOption &LHS, 484 const WarningOption &RHS) { 485 return strcmp(LHS.Name, RHS.Name) < 0; 486} 487 488static void MapGroupMembers(const WarningOption *Group, diag::Mapping Mapping, 489 Diagnostic &Diags) { 490 // Option exists, poke all the members of its diagnostic set. 491 if (const short *Member = Group->Members) { 492 for (; *Member != -1; ++Member) 493 Diags.setDiagnosticMapping(*Member, Mapping); 494 } 495 496 // Enable/disable all subgroups along with this one. 497 if (const short *SubGroups = Group->SubGroups) { 498 for (; *SubGroups != (short)-1; ++SubGroups) 499 MapGroupMembers(&OptionTable[(short)*SubGroups], Mapping, Diags); 500 } 501} 502 503/// setDiagnosticGroupMapping - Change an entire diagnostic group (e.g. 504/// "unknown-pragmas" to have the specified mapping. This returns true and 505/// ignores the request if "Group" was unknown, false otherwise. 506bool Diagnostic::setDiagnosticGroupMapping(const char *Group, 507 diag::Mapping Map) { 508 509 WarningOption Key = { Group, 0, 0 }; 510 const WarningOption *Found = 511 std::lower_bound(OptionTable, OptionTable + OptionTableSize, Key, 512 WarningOptionCompare); 513 if (Found == OptionTable + OptionTableSize || 514 strcmp(Found->Name, Group) != 0) 515 return true; // Option not found. 516 517 MapGroupMembers(Found, Map, *this); 518 return false; 519} 520 521 522/// ProcessDiag - This is the method used to report a diagnostic that is 523/// finally fully formed. 524bool Diagnostic::ProcessDiag() { 525 DiagnosticInfo Info(this); 526 527 if (SuppressAllDiagnostics) 528 return false; 529 530 // Figure out the diagnostic level of this message. 531 Diagnostic::Level DiagLevel; 532 unsigned DiagID = Info.getID(); 533 534 // ShouldEmitInSystemHeader - True if this diagnostic should be produced even 535 // in a system header. 536 bool ShouldEmitInSystemHeader; 537 538 if (DiagID >= diag::DIAG_UPPER_LIMIT) { 539 // Handle custom diagnostics, which cannot be mapped. 540 DiagLevel = CustomDiagInfo->getLevel(DiagID); 541 542 // Custom diagnostics always are emitted in system headers. 543 ShouldEmitInSystemHeader = true; 544 } else { 545 // Get the class of the diagnostic. If this is a NOTE, map it onto whatever 546 // the diagnostic level was for the previous diagnostic so that it is 547 // filtered the same as the previous diagnostic. 548 unsigned DiagClass = getBuiltinDiagClass(DiagID); 549 if (DiagClass == CLASS_NOTE) { 550 DiagLevel = Diagnostic::Note; 551 ShouldEmitInSystemHeader = false; // extra consideration is needed 552 } else { 553 // If this is not an error and we are in a system header, we ignore it. 554 // Check the original Diag ID here, because we also want to ignore 555 // extensions and warnings in -Werror and -pedantic-errors modes, which 556 // *map* warnings/extensions to errors. 557 ShouldEmitInSystemHeader = DiagClass == CLASS_ERROR; 558 559 DiagLevel = getDiagnosticLevel(DiagID, DiagClass); 560 } 561 } 562 563 if (DiagLevel != Diagnostic::Note) { 564 // Record that a fatal error occurred only when we see a second 565 // non-note diagnostic. This allows notes to be attached to the 566 // fatal error, but suppresses any diagnostics that follow those 567 // notes. 568 if (LastDiagLevel == Diagnostic::Fatal) 569 FatalErrorOccurred = true; 570 571 LastDiagLevel = DiagLevel; 572 } 573 574 // If a fatal error has already been emitted, silence all subsequent 575 // diagnostics. 576 if (FatalErrorOccurred) { 577 if (DiagLevel >= Diagnostic::Error) { 578 ++NumErrors; 579 ++NumErrorsSuppressed; 580 } 581 582 return false; 583 } 584 585 // If the client doesn't care about this message, don't issue it. If this is 586 // a note and the last real diagnostic was ignored, ignore it too. 587 if (DiagLevel == Diagnostic::Ignored || 588 (DiagLevel == Diagnostic::Note && LastDiagLevel == Diagnostic::Ignored)) 589 return false; 590 591 // If this diagnostic is in a system header and is not a clang error, suppress 592 // it. 593 if (SuppressSystemWarnings && !ShouldEmitInSystemHeader && 594 Info.getLocation().isValid() && 595 Info.getLocation().getInstantiationLoc().isInSystemHeader() && 596 (DiagLevel != Diagnostic::Note || LastDiagLevel == Diagnostic::Ignored)) { 597 LastDiagLevel = Diagnostic::Ignored; 598 return false; 599 } 600 601 if (DiagLevel >= Diagnostic::Error) { 602 ErrorOccurred = true; 603 ++NumErrors; 604 605 // If we've emitted a lot of errors, emit a fatal error after it to stop a 606 // flood of bogus errors. 607 if (ErrorLimit && NumErrors >= ErrorLimit && 608 DiagLevel == Diagnostic::Error) 609 SetDelayedDiagnostic(diag::fatal_too_many_errors); 610 } 611 612 // Finally, report it. 613 Client->HandleDiagnostic(DiagLevel, Info); 614 if (Client->IncludeInDiagnosticCounts()) { 615 if (DiagLevel == Diagnostic::Warning) 616 ++NumWarnings; 617 } 618 619 CurDiagID = ~0U; 620 621 return true; 622} 623 624bool DiagnosticBuilder::Emit() { 625 // If DiagObj is null, then its soul was stolen by the copy ctor 626 // or the user called Emit(). 627 if (DiagObj == 0) return false; 628 629 // When emitting diagnostics, we set the final argument count into 630 // the Diagnostic object. 631 DiagObj->NumDiagArgs = NumArgs; 632 DiagObj->NumDiagRanges = NumRanges; 633 DiagObj->NumFixItHints = NumFixItHints; 634 635 // Process the diagnostic, sending the accumulated information to the 636 // DiagnosticClient. 637 bool Emitted = DiagObj->ProcessDiag(); 638 639 // Clear out the current diagnostic object. 640 unsigned DiagID = DiagObj->CurDiagID; 641 DiagObj->Clear(); 642 643 // If there was a delayed diagnostic, emit it now. 644 if (DiagObj->DelayedDiagID && DiagObj->DelayedDiagID != DiagID) 645 DiagObj->ReportDelayed(); 646 647 // This diagnostic is dead. 648 DiagObj = 0; 649 650 return Emitted; 651} 652 653 654DiagnosticClient::~DiagnosticClient() {} 655 656 657/// ModifierIs - Return true if the specified modifier matches specified string. 658template <std::size_t StrLen> 659static bool ModifierIs(const char *Modifier, unsigned ModifierLen, 660 const char (&Str)[StrLen]) { 661 return StrLen-1 == ModifierLen && !memcmp(Modifier, Str, StrLen-1); 662} 663 664/// ScanForward - Scans forward, looking for the given character, skipping 665/// nested clauses and escaped characters. 666static const char *ScanFormat(const char *I, const char *E, char Target) { 667 unsigned Depth = 0; 668 669 for ( ; I != E; ++I) { 670 if (Depth == 0 && *I == Target) return I; 671 if (Depth != 0 && *I == '}') Depth--; 672 673 if (*I == '%') { 674 I++; 675 if (I == E) break; 676 677 // Escaped characters get implicitly skipped here. 678 679 // Format specifier. 680 if (!isdigit(*I) && !ispunct(*I)) { 681 for (I++; I != E && !isdigit(*I) && *I != '{'; I++) ; 682 if (I == E) break; 683 if (*I == '{') 684 Depth++; 685 } 686 } 687 } 688 return E; 689} 690 691/// HandleSelectModifier - Handle the integer 'select' modifier. This is used 692/// like this: %select{foo|bar|baz}2. This means that the integer argument 693/// "%2" has a value from 0-2. If the value is 0, the diagnostic prints 'foo'. 694/// If the value is 1, it prints 'bar'. If it has the value 2, it prints 'baz'. 695/// This is very useful for certain classes of variant diagnostics. 696static void HandleSelectModifier(const DiagnosticInfo &DInfo, unsigned ValNo, 697 const char *Argument, unsigned ArgumentLen, 698 llvm::SmallVectorImpl<char> &OutStr) { 699 const char *ArgumentEnd = Argument+ArgumentLen; 700 701 // Skip over 'ValNo' |'s. 702 while (ValNo) { 703 const char *NextVal = ScanFormat(Argument, ArgumentEnd, '|'); 704 assert(NextVal != ArgumentEnd && "Value for integer select modifier was" 705 " larger than the number of options in the diagnostic string!"); 706 Argument = NextVal+1; // Skip this string. 707 --ValNo; 708 } 709 710 // Get the end of the value. This is either the } or the |. 711 const char *EndPtr = ScanFormat(Argument, ArgumentEnd, '|'); 712 713 // Recursively format the result of the select clause into the output string. 714 DInfo.FormatDiagnostic(Argument, EndPtr, OutStr); 715} 716 717/// HandleIntegerSModifier - Handle the integer 's' modifier. This adds the 718/// letter 's' to the string if the value is not 1. This is used in cases like 719/// this: "you idiot, you have %4 parameter%s4!". 720static void HandleIntegerSModifier(unsigned ValNo, 721 llvm::SmallVectorImpl<char> &OutStr) { 722 if (ValNo != 1) 723 OutStr.push_back('s'); 724} 725 726/// HandleOrdinalModifier - Handle the integer 'ord' modifier. This 727/// prints the ordinal form of the given integer, with 1 corresponding 728/// to the first ordinal. Currently this is hard-coded to use the 729/// English form. 730static void HandleOrdinalModifier(unsigned ValNo, 731 llvm::SmallVectorImpl<char> &OutStr) { 732 assert(ValNo != 0 && "ValNo must be strictly positive!"); 733 734 llvm::raw_svector_ostream Out(OutStr); 735 736 // We could use text forms for the first N ordinals, but the numeric 737 // forms are actually nicer in diagnostics because they stand out. 738 Out << ValNo; 739 740 // It is critically important that we do this perfectly for 741 // user-written sequences with over 100 elements. 742 switch (ValNo % 100) { 743 case 11: 744 case 12: 745 case 13: 746 Out << "th"; return; 747 default: 748 switch (ValNo % 10) { 749 case 1: Out << "st"; return; 750 case 2: Out << "nd"; return; 751 case 3: Out << "rd"; return; 752 default: Out << "th"; return; 753 } 754 } 755} 756 757 758/// PluralNumber - Parse an unsigned integer and advance Start. 759static unsigned PluralNumber(const char *&Start, const char *End) { 760 // Programming 101: Parse a decimal number :-) 761 unsigned Val = 0; 762 while (Start != End && *Start >= '0' && *Start <= '9') { 763 Val *= 10; 764 Val += *Start - '0'; 765 ++Start; 766 } 767 return Val; 768} 769 770/// TestPluralRange - Test if Val is in the parsed range. Modifies Start. 771static bool TestPluralRange(unsigned Val, const char *&Start, const char *End) { 772 if (*Start != '[') { 773 unsigned Ref = PluralNumber(Start, End); 774 return Ref == Val; 775 } 776 777 ++Start; 778 unsigned Low = PluralNumber(Start, End); 779 assert(*Start == ',' && "Bad plural expression syntax: expected ,"); 780 ++Start; 781 unsigned High = PluralNumber(Start, End); 782 assert(*Start == ']' && "Bad plural expression syntax: expected )"); 783 ++Start; 784 return Low <= Val && Val <= High; 785} 786 787/// EvalPluralExpr - Actual expression evaluator for HandlePluralModifier. 788static bool EvalPluralExpr(unsigned ValNo, const char *Start, const char *End) { 789 // Empty condition? 790 if (*Start == ':') 791 return true; 792 793 while (1) { 794 char C = *Start; 795 if (C == '%') { 796 // Modulo expression 797 ++Start; 798 unsigned Arg = PluralNumber(Start, End); 799 assert(*Start == '=' && "Bad plural expression syntax: expected ="); 800 ++Start; 801 unsigned ValMod = ValNo % Arg; 802 if (TestPluralRange(ValMod, Start, End)) 803 return true; 804 } else { 805 assert((C == '[' || (C >= '0' && C <= '9')) && 806 "Bad plural expression syntax: unexpected character"); 807 // Range expression 808 if (TestPluralRange(ValNo, Start, End)) 809 return true; 810 } 811 812 // Scan for next or-expr part. 813 Start = std::find(Start, End, ','); 814 if (Start == End) 815 break; 816 ++Start; 817 } 818 return false; 819} 820 821/// HandlePluralModifier - Handle the integer 'plural' modifier. This is used 822/// for complex plural forms, or in languages where all plurals are complex. 823/// The syntax is: %plural{cond1:form1|cond2:form2|:form3}, where condn are 824/// conditions that are tested in order, the form corresponding to the first 825/// that applies being emitted. The empty condition is always true, making the 826/// last form a default case. 827/// Conditions are simple boolean expressions, where n is the number argument. 828/// Here are the rules. 829/// condition := expression | empty 830/// empty := -> always true 831/// expression := numeric [',' expression] -> logical or 832/// numeric := range -> true if n in range 833/// | '%' number '=' range -> true if n % number in range 834/// range := number 835/// | '[' number ',' number ']' -> ranges are inclusive both ends 836/// 837/// Here are some examples from the GNU gettext manual written in this form: 838/// English: 839/// {1:form0|:form1} 840/// Latvian: 841/// {0:form2|%100=11,%10=0,%10=[2,9]:form1|:form0} 842/// Gaeilge: 843/// {1:form0|2:form1|:form2} 844/// Romanian: 845/// {1:form0|0,%100=[1,19]:form1|:form2} 846/// Lithuanian: 847/// {%10=0,%100=[10,19]:form2|%10=1:form0|:form1} 848/// Russian (requires repeated form): 849/// {%100=[11,14]:form2|%10=1:form0|%10=[2,4]:form1|:form2} 850/// Slovak 851/// {1:form0|[2,4]:form1|:form2} 852/// Polish (requires repeated form): 853/// {1:form0|%100=[10,20]:form2|%10=[2,4]:form1|:form2} 854static void HandlePluralModifier(unsigned ValNo, 855 const char *Argument, unsigned ArgumentLen, 856 llvm::SmallVectorImpl<char> &OutStr) { 857 const char *ArgumentEnd = Argument + ArgumentLen; 858 while (1) { 859 assert(Argument < ArgumentEnd && "Plural expression didn't match."); 860 const char *ExprEnd = Argument; 861 while (*ExprEnd != ':') { 862 assert(ExprEnd != ArgumentEnd && "Plural missing expression end"); 863 ++ExprEnd; 864 } 865 if (EvalPluralExpr(ValNo, Argument, ExprEnd)) { 866 Argument = ExprEnd + 1; 867 ExprEnd = ScanFormat(Argument, ArgumentEnd, '|'); 868 OutStr.append(Argument, ExprEnd); 869 return; 870 } 871 Argument = ScanFormat(Argument, ArgumentEnd - 1, '|') + 1; 872 } 873} 874 875 876/// FormatDiagnostic - Format this diagnostic into a string, substituting the 877/// formal arguments into the %0 slots. The result is appended onto the Str 878/// array. 879void DiagnosticInfo:: 880FormatDiagnostic(llvm::SmallVectorImpl<char> &OutStr) const { 881 const char *DiagStr = getDiags()->getDescription(getID()); 882 const char *DiagEnd = DiagStr+strlen(DiagStr); 883 884 FormatDiagnostic(DiagStr, DiagEnd, OutStr); 885} 886 887void DiagnosticInfo:: 888FormatDiagnostic(const char *DiagStr, const char *DiagEnd, 889 llvm::SmallVectorImpl<char> &OutStr) const { 890 891 /// FormattedArgs - Keep track of all of the arguments formatted by 892 /// ConvertArgToString and pass them into subsequent calls to 893 /// ConvertArgToString, allowing the implementation to avoid redundancies in 894 /// obvious cases. 895 llvm::SmallVector<Diagnostic::ArgumentValue, 8> FormattedArgs; 896 897 while (DiagStr != DiagEnd) { 898 if (DiagStr[0] != '%') { 899 // Append non-%0 substrings to Str if we have one. 900 const char *StrEnd = std::find(DiagStr, DiagEnd, '%'); 901 OutStr.append(DiagStr, StrEnd); 902 DiagStr = StrEnd; 903 continue; 904 } else if (ispunct(DiagStr[1])) { 905 OutStr.push_back(DiagStr[1]); // %% -> %. 906 DiagStr += 2; 907 continue; 908 } 909 910 // Skip the %. 911 ++DiagStr; 912 913 // This must be a placeholder for a diagnostic argument. The format for a 914 // placeholder is one of "%0", "%modifier0", or "%modifier{arguments}0". 915 // The digit is a number from 0-9 indicating which argument this comes from. 916 // The modifier is a string of digits from the set [-a-z]+, arguments is a 917 // brace enclosed string. 918 const char *Modifier = 0, *Argument = 0; 919 unsigned ModifierLen = 0, ArgumentLen = 0; 920 921 // Check to see if we have a modifier. If so eat it. 922 if (!isdigit(DiagStr[0])) { 923 Modifier = DiagStr; 924 while (DiagStr[0] == '-' || 925 (DiagStr[0] >= 'a' && DiagStr[0] <= 'z')) 926 ++DiagStr; 927 ModifierLen = DiagStr-Modifier; 928 929 // If we have an argument, get it next. 930 if (DiagStr[0] == '{') { 931 ++DiagStr; // Skip {. 932 Argument = DiagStr; 933 934 DiagStr = ScanFormat(DiagStr, DiagEnd, '}'); 935 assert(DiagStr != DiagEnd && "Mismatched {}'s in diagnostic string!"); 936 ArgumentLen = DiagStr-Argument; 937 ++DiagStr; // Skip }. 938 } 939 } 940 941 assert(isdigit(*DiagStr) && "Invalid format for argument in diagnostic"); 942 unsigned ArgNo = *DiagStr++ - '0'; 943 944 Diagnostic::ArgumentKind Kind = getArgKind(ArgNo); 945 946 switch (Kind) { 947 // ---- STRINGS ---- 948 case Diagnostic::ak_std_string: { 949 const std::string &S = getArgStdStr(ArgNo); 950 assert(ModifierLen == 0 && "No modifiers for strings yet"); 951 OutStr.append(S.begin(), S.end()); 952 break; 953 } 954 case Diagnostic::ak_c_string: { 955 const char *S = getArgCStr(ArgNo); 956 assert(ModifierLen == 0 && "No modifiers for strings yet"); 957 958 // Don't crash if get passed a null pointer by accident. 959 if (!S) 960 S = "(null)"; 961 962 OutStr.append(S, S + strlen(S)); 963 break; 964 } 965 // ---- INTEGERS ---- 966 case Diagnostic::ak_sint: { 967 int Val = getArgSInt(ArgNo); 968 969 if (ModifierIs(Modifier, ModifierLen, "select")) { 970 HandleSelectModifier(*this, (unsigned)Val, Argument, ArgumentLen, OutStr); 971 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 972 HandleIntegerSModifier(Val, OutStr); 973 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 974 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); 975 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 976 HandleOrdinalModifier((unsigned)Val, OutStr); 977 } else { 978 assert(ModifierLen == 0 && "Unknown integer modifier"); 979 llvm::raw_svector_ostream(OutStr) << Val; 980 } 981 break; 982 } 983 case Diagnostic::ak_uint: { 984 unsigned Val = getArgUInt(ArgNo); 985 986 if (ModifierIs(Modifier, ModifierLen, "select")) { 987 HandleSelectModifier(*this, Val, Argument, ArgumentLen, OutStr); 988 } else if (ModifierIs(Modifier, ModifierLen, "s")) { 989 HandleIntegerSModifier(Val, OutStr); 990 } else if (ModifierIs(Modifier, ModifierLen, "plural")) { 991 HandlePluralModifier((unsigned)Val, Argument, ArgumentLen, OutStr); 992 } else if (ModifierIs(Modifier, ModifierLen, "ordinal")) { 993 HandleOrdinalModifier(Val, OutStr); 994 } else { 995 assert(ModifierLen == 0 && "Unknown integer modifier"); 996 llvm::raw_svector_ostream(OutStr) << Val; 997 } 998 break; 999 } 1000 // ---- NAMES and TYPES ---- 1001 case Diagnostic::ak_identifierinfo: { 1002 const IdentifierInfo *II = getArgIdentifier(ArgNo); 1003 assert(ModifierLen == 0 && "No modifiers for strings yet"); 1004 1005 // Don't crash if get passed a null pointer by accident. 1006 if (!II) { 1007 const char *S = "(null)"; 1008 OutStr.append(S, S + strlen(S)); 1009 continue; 1010 } 1011 1012 llvm::raw_svector_ostream(OutStr) << '\'' << II->getName() << '\''; 1013 break; 1014 } 1015 case Diagnostic::ak_qualtype: 1016 case Diagnostic::ak_declarationname: 1017 case Diagnostic::ak_nameddecl: 1018 case Diagnostic::ak_nestednamespec: 1019 case Diagnostic::ak_declcontext: 1020 getDiags()->ConvertArgToString(Kind, getRawArg(ArgNo), 1021 Modifier, ModifierLen, 1022 Argument, ArgumentLen, 1023 FormattedArgs.data(), FormattedArgs.size(), 1024 OutStr); 1025 break; 1026 } 1027 1028 // Remember this argument info for subsequent formatting operations. Turn 1029 // std::strings into a null terminated string to make it be the same case as 1030 // all the other ones. 1031 if (Kind != Diagnostic::ak_std_string) 1032 FormattedArgs.push_back(std::make_pair(Kind, getRawArg(ArgNo))); 1033 else 1034 FormattedArgs.push_back(std::make_pair(Diagnostic::ak_c_string, 1035 (intptr_t)getArgStdStr(ArgNo).c_str())); 1036 1037 } 1038} 1039 1040StoredDiagnostic::StoredDiagnostic() { } 1041 1042StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, 1043 llvm::StringRef Message) 1044 : Level(Level), Loc(), Message(Message) { } 1045 1046StoredDiagnostic::StoredDiagnostic(Diagnostic::Level Level, 1047 const DiagnosticInfo &Info) 1048 : Level(Level), Loc(Info.getLocation()) { 1049 llvm::SmallString<64> Message; 1050 Info.FormatDiagnostic(Message); 1051 this->Message.assign(Message.begin(), Message.end()); 1052 1053 Ranges.reserve(Info.getNumRanges()); 1054 for (unsigned I = 0, N = Info.getNumRanges(); I != N; ++I) 1055 Ranges.push_back(Info.getRange(I)); 1056 1057 FixIts.reserve(Info.getNumFixItHints()); 1058 for (unsigned I = 0, N = Info.getNumFixItHints(); I != N; ++I) 1059 FixIts.push_back(Info.getFixItHint(I)); 1060} 1061 1062StoredDiagnostic::~StoredDiagnostic() { } 1063 1064static void WriteUnsigned(llvm::raw_ostream &OS, unsigned Value) { 1065 OS.write((const char *)&Value, sizeof(unsigned)); 1066} 1067 1068static void WriteString(llvm::raw_ostream &OS, llvm::StringRef String) { 1069 WriteUnsigned(OS, String.size()); 1070 OS.write(String.data(), String.size()); 1071} 1072 1073static void WriteSourceLocation(llvm::raw_ostream &OS, 1074 SourceManager *SM, 1075 SourceLocation Location) { 1076 if (!SM || Location.isInvalid()) { 1077 // If we don't have a source manager or this location is invalid, 1078 // just write an invalid location. 1079 WriteUnsigned(OS, 0); 1080 WriteUnsigned(OS, 0); 1081 WriteUnsigned(OS, 0); 1082 return; 1083 } 1084 1085 Location = SM->getInstantiationLoc(Location); 1086 std::pair<FileID, unsigned> Decomposed = SM->getDecomposedLoc(Location); 1087 1088 const FileEntry *FE = SM->getFileEntryForID(Decomposed.first); 1089 if (FE) 1090 WriteString(OS, FE->getName()); 1091 else { 1092 // Fallback to using the buffer name when there is no entry. 1093 WriteString(OS, SM->getBuffer(Decomposed.first)->getBufferIdentifier()); 1094 } 1095 1096 WriteUnsigned(OS, SM->getLineNumber(Decomposed.first, Decomposed.second)); 1097 WriteUnsigned(OS, SM->getColumnNumber(Decomposed.first, Decomposed.second)); 1098} 1099 1100void StoredDiagnostic::Serialize(llvm::raw_ostream &OS) const { 1101 SourceManager *SM = 0; 1102 if (getLocation().isValid()) 1103 SM = &const_cast<SourceManager &>(getLocation().getManager()); 1104 1105 // Write a short header to help identify diagnostics. 1106 OS << (char)0x06 << (char)0x07; 1107 1108 // Write the diagnostic level and location. 1109 WriteUnsigned(OS, (unsigned)Level); 1110 WriteSourceLocation(OS, SM, getLocation()); 1111 1112 // Write the diagnostic message. 1113 llvm::SmallString<64> Message; 1114 WriteString(OS, getMessage()); 1115 1116 // Count the number of ranges that don't point into macros, since 1117 // only simple file ranges serialize well. 1118 unsigned NumNonMacroRanges = 0; 1119 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) { 1120 if (R->getBegin().isMacroID() || R->getEnd().isMacroID()) 1121 continue; 1122 1123 ++NumNonMacroRanges; 1124 } 1125 1126 // Write the ranges. 1127 WriteUnsigned(OS, NumNonMacroRanges); 1128 if (NumNonMacroRanges) { 1129 for (range_iterator R = range_begin(), REnd = range_end(); R != REnd; ++R) { 1130 if (R->getBegin().isMacroID() || R->getEnd().isMacroID()) 1131 continue; 1132 1133 WriteSourceLocation(OS, SM, R->getBegin()); 1134 WriteSourceLocation(OS, SM, R->getEnd()); 1135 WriteUnsigned(OS, R->isTokenRange()); 1136 } 1137 } 1138 1139 // Determine if all of the fix-its involve rewrites with simple file 1140 // locations (not in macro instantiations). If so, we can write 1141 // fix-it information. 1142 unsigned NumFixIts = 0; 1143 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) { 1144 if (F->RemoveRange.isValid() && 1145 (F->RemoveRange.getBegin().isMacroID() || 1146 F->RemoveRange.getEnd().isMacroID())) { 1147 NumFixIts = 0; 1148 break; 1149 } 1150 1151 if (F->InsertionLoc.isValid() && F->InsertionLoc.isMacroID()) { 1152 NumFixIts = 0; 1153 break; 1154 } 1155 1156 ++NumFixIts; 1157 } 1158 1159 // Write the fix-its. 1160 WriteUnsigned(OS, NumFixIts); 1161 for (fixit_iterator F = fixit_begin(), FEnd = fixit_end(); F != FEnd; ++F) { 1162 WriteSourceLocation(OS, SM, F->RemoveRange.getBegin()); 1163 WriteSourceLocation(OS, SM, F->RemoveRange.getEnd()); 1164 WriteUnsigned(OS, F->RemoveRange.isTokenRange()); 1165 WriteSourceLocation(OS, SM, F->InsertionLoc); 1166 WriteString(OS, F->CodeToInsert); 1167 } 1168} 1169 1170static bool ReadUnsigned(const char *&Memory, const char *MemoryEnd, 1171 unsigned &Value) { 1172 if (Memory + sizeof(unsigned) > MemoryEnd) 1173 return true; 1174 1175 memmove(&Value, Memory, sizeof(unsigned)); 1176 Memory += sizeof(unsigned); 1177 return false; 1178} 1179 1180static bool ReadSourceLocation(FileManager &FM, SourceManager &SM, 1181 const char *&Memory, const char *MemoryEnd, 1182 SourceLocation &Location) { 1183 // Read the filename. 1184 unsigned FileNameLen = 0; 1185 if (ReadUnsigned(Memory, MemoryEnd, FileNameLen) || 1186 Memory + FileNameLen > MemoryEnd) 1187 return true; 1188 1189 llvm::StringRef FileName(Memory, FileNameLen); 1190 Memory += FileNameLen; 1191 1192 // Read the line, column. 1193 unsigned Line = 0, Column = 0; 1194 if (ReadUnsigned(Memory, MemoryEnd, Line) || 1195 ReadUnsigned(Memory, MemoryEnd, Column)) 1196 return true; 1197 1198 if (FileName.empty()) { 1199 Location = SourceLocation(); 1200 return false; 1201 } 1202 1203 const FileEntry *File = FM.getFile(FileName); 1204 if (!File) 1205 return true; 1206 1207 // Make sure that this file has an entry in the source manager. 1208 if (!SM.hasFileInfo(File)) 1209 SM.createFileID(File, SourceLocation(), SrcMgr::C_User); 1210 1211 Location = SM.getLocation(File, Line, Column); 1212 return false; 1213} 1214 1215StoredDiagnostic 1216StoredDiagnostic::Deserialize(FileManager &FM, SourceManager &SM, 1217 const char *&Memory, const char *MemoryEnd) { 1218 while (true) { 1219 if (Memory == MemoryEnd) 1220 return StoredDiagnostic(); 1221 1222 if (*Memory != 0x06) { 1223 ++Memory; 1224 continue; 1225 } 1226 1227 ++Memory; 1228 if (Memory == MemoryEnd) 1229 return StoredDiagnostic(); 1230 1231 if (*Memory != 0x07) { 1232 ++Memory; 1233 continue; 1234 } 1235 1236 // We found the header. We're done. 1237 ++Memory; 1238 break; 1239 } 1240 1241 // Read the severity level. 1242 unsigned Level = 0; 1243 if (ReadUnsigned(Memory, MemoryEnd, Level) || Level > Diagnostic::Fatal) 1244 return StoredDiagnostic(); 1245 1246 // Read the source location. 1247 SourceLocation Location; 1248 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Location)) 1249 return StoredDiagnostic(); 1250 1251 // Read the diagnostic text. 1252 if (Memory == MemoryEnd) 1253 return StoredDiagnostic(); 1254 1255 unsigned MessageLen = 0; 1256 if (ReadUnsigned(Memory, MemoryEnd, MessageLen) || 1257 Memory + MessageLen > MemoryEnd) 1258 return StoredDiagnostic(); 1259 1260 llvm::StringRef Message(Memory, MessageLen); 1261 Memory += MessageLen; 1262 1263 1264 // At this point, we have enough information to form a diagnostic. Do so. 1265 StoredDiagnostic Diag; 1266 Diag.Level = (Diagnostic::Level)Level; 1267 Diag.Loc = FullSourceLoc(Location, SM); 1268 Diag.Message = Message; 1269 if (Memory == MemoryEnd) 1270 return Diag; 1271 1272 // Read the source ranges. 1273 unsigned NumSourceRanges = 0; 1274 if (ReadUnsigned(Memory, MemoryEnd, NumSourceRanges)) 1275 return Diag; 1276 for (unsigned I = 0; I != NumSourceRanges; ++I) { 1277 SourceLocation Begin, End; 1278 unsigned IsTokenRange; 1279 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, Begin) || 1280 ReadSourceLocation(FM, SM, Memory, MemoryEnd, End) || 1281 ReadUnsigned(Memory, MemoryEnd, IsTokenRange)) 1282 return Diag; 1283 1284 Diag.Ranges.push_back(CharSourceRange(SourceRange(Begin, End), 1285 IsTokenRange)); 1286 } 1287 1288 // Read the fix-it hints. 1289 unsigned NumFixIts = 0; 1290 if (ReadUnsigned(Memory, MemoryEnd, NumFixIts)) 1291 return Diag; 1292 for (unsigned I = 0; I != NumFixIts; ++I) { 1293 SourceLocation RemoveBegin, RemoveEnd, InsertionLoc; 1294 unsigned InsertLen = 0, RemoveIsTokenRange; 1295 if (ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveBegin) || 1296 ReadSourceLocation(FM, SM, Memory, MemoryEnd, RemoveEnd) || 1297 ReadUnsigned(Memory, MemoryEnd, RemoveIsTokenRange) || 1298 ReadSourceLocation(FM, SM, Memory, MemoryEnd, InsertionLoc) || 1299 ReadUnsigned(Memory, MemoryEnd, InsertLen) || 1300 Memory + InsertLen > MemoryEnd) { 1301 Diag.FixIts.clear(); 1302 return Diag; 1303 } 1304 1305 FixItHint Hint; 1306 Hint.RemoveRange = CharSourceRange(SourceRange(RemoveBegin, RemoveEnd), 1307 RemoveIsTokenRange); 1308 Hint.InsertionLoc = InsertionLoc; 1309 Hint.CodeToInsert.assign(Memory, Memory + InsertLen); 1310 Memory += InsertLen; 1311 Diag.FixIts.push_back(Hint); 1312 } 1313 1314 return Diag; 1315} 1316 1317/// IncludeInDiagnosticCounts - This method (whose default implementation 1318/// returns true) indicates whether the diagnostics handled by this 1319/// DiagnosticClient should be included in the number of diagnostics 1320/// reported by Diagnostic. 1321bool DiagnosticClient::IncludeInDiagnosticCounts() const { return true; } 1322 1323PartialDiagnostic::StorageAllocator::StorageAllocator() { 1324 for (unsigned I = 0; I != NumCached; ++I) 1325 FreeList[I] = Cached + I; 1326 NumFreeListEntries = NumCached; 1327} 1328 1329PartialDiagnostic::StorageAllocator::~StorageAllocator() { 1330 assert(NumFreeListEntries == NumCached && "A partial is on the lamb"); 1331} 1332