1 //===---- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ------===// 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 is a concrete diagnostic client, which buffers the diagnostic messages. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 15 #include "clang/Basic/CharInfo.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Frontend/FrontendDiagnostic.h" 18 #include "clang/Frontend/TextDiagnosticBuffer.h" 19 #include "clang/Lex/HeaderSearch.h" 20 #include "clang/Lex/Preprocessor.h" 21 #include "llvm/ADT/SmallString.h" 22 #include "llvm/Support/Regex.h" 23 #include "llvm/Support/raw_ostream.h" 24 25 using namespace clang; 26 typedef VerifyDiagnosticConsumer::Directive Directive; 27 typedef VerifyDiagnosticConsumer::DirectiveList DirectiveList; 28 typedef VerifyDiagnosticConsumer::ExpectedData ExpectedData; 29 30 VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &_Diags) 31 : Diags(_Diags), 32 PrimaryClient(Diags.getClient()), OwnsPrimaryClient(Diags.ownsClient()), 33 Buffer(new TextDiagnosticBuffer()), CurrentPreprocessor(0), 34 LangOpts(0), SrcManager(0), ActiveSourceFiles(0), Status(HasNoDirectives) 35 { 36 Diags.takeClient(); 37 if (Diags.hasSourceManager()) 38 setSourceManager(Diags.getSourceManager()); 39 } 40 41 VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() { 42 assert(!ActiveSourceFiles && "Incomplete parsing of source files!"); 43 assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!"); 44 SrcManager = 0; 45 CheckDiagnostics(); 46 Diags.takeClient(); 47 if (OwnsPrimaryClient) 48 delete PrimaryClient; 49 } 50 51 #ifndef NDEBUG 52 namespace { 53 class VerifyFileTracker : public PPCallbacks { 54 VerifyDiagnosticConsumer &Verify; 55 SourceManager &SM; 56 57 public: 58 VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM) 59 : Verify(Verify), SM(SM) { } 60 61 /// \brief Hook into the preprocessor and update the list of parsed 62 /// files when the preprocessor indicates a new file is entered. 63 virtual void FileChanged(SourceLocation Loc, FileChangeReason Reason, 64 SrcMgr::CharacteristicKind FileType, 65 FileID PrevFID) { 66 Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc), 67 VerifyDiagnosticConsumer::IsParsed); 68 } 69 }; 70 } // End anonymous namespace. 71 #endif 72 73 // DiagnosticConsumer interface. 74 75 void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts, 76 const Preprocessor *PP) { 77 // Attach comment handler on first invocation. 78 if (++ActiveSourceFiles == 1) { 79 if (PP) { 80 CurrentPreprocessor = PP; 81 this->LangOpts = &LangOpts; 82 setSourceManager(PP->getSourceManager()); 83 const_cast<Preprocessor*>(PP)->addCommentHandler(this); 84 #ifndef NDEBUG 85 // Debug build tracks parsed files. 86 VerifyFileTracker *V = new VerifyFileTracker(*this, *SrcManager); 87 const_cast<Preprocessor*>(PP)->addPPCallbacks(V); 88 #endif 89 } 90 } 91 92 assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!"); 93 PrimaryClient->BeginSourceFile(LangOpts, PP); 94 } 95 96 void VerifyDiagnosticConsumer::EndSourceFile() { 97 assert(ActiveSourceFiles && "No active source files!"); 98 PrimaryClient->EndSourceFile(); 99 100 // Detach comment handler once last active source file completed. 101 if (--ActiveSourceFiles == 0) { 102 if (CurrentPreprocessor) 103 const_cast<Preprocessor*>(CurrentPreprocessor)->removeCommentHandler(this); 104 105 // Check diagnostics once last file completed. 106 CheckDiagnostics(); 107 CurrentPreprocessor = 0; 108 LangOpts = 0; 109 } 110 } 111 112 void VerifyDiagnosticConsumer::HandleDiagnostic( 113 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { 114 if (Info.hasSourceManager()) 115 setSourceManager(Info.getSourceManager()); 116 117 #ifndef NDEBUG 118 // Debug build tracks unparsed files for possible 119 // unparsed expected-* directives. 120 if (SrcManager) { 121 SourceLocation Loc = Info.getLocation(); 122 if (Loc.isValid()) { 123 ParsedStatus PS = IsUnparsed; 124 125 Loc = SrcManager->getExpansionLoc(Loc); 126 FileID FID = SrcManager->getFileID(Loc); 127 128 const FileEntry *FE = SrcManager->getFileEntryForID(FID); 129 if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) { 130 // If the file is a modules header file it shall not be parsed 131 // for expected-* directives. 132 HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo(); 133 if (HS.findModuleForHeader(FE)) 134 PS = IsUnparsedNoDirectives; 135 } 136 137 UpdateParsedFileStatus(*SrcManager, FID, PS); 138 } 139 } 140 #endif 141 142 // Send the diagnostic to the buffer, we will check it once we reach the end 143 // of the source file (or are destructed). 144 Buffer->HandleDiagnostic(DiagLevel, Info); 145 } 146 147 //===----------------------------------------------------------------------===// 148 // Checking diagnostics implementation. 149 //===----------------------------------------------------------------------===// 150 151 typedef TextDiagnosticBuffer::DiagList DiagList; 152 typedef TextDiagnosticBuffer::const_iterator const_diag_iterator; 153 154 namespace { 155 156 /// StandardDirective - Directive with string matching. 157 /// 158 class StandardDirective : public Directive { 159 public: 160 StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc, 161 StringRef Text, unsigned Min, unsigned Max) 162 : Directive(DirectiveLoc, DiagnosticLoc, Text, Min, Max) { } 163 164 virtual bool isValid(std::string &Error) { 165 // all strings are considered valid; even empty ones 166 return true; 167 } 168 169 virtual bool match(StringRef S) { 170 return S.find(Text) != StringRef::npos; 171 } 172 }; 173 174 /// RegexDirective - Directive with regular-expression matching. 175 /// 176 class RegexDirective : public Directive { 177 public: 178 RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc, 179 StringRef Text, unsigned Min, unsigned Max) 180 : Directive(DirectiveLoc, DiagnosticLoc, Text, Min, Max), Regex(Text) { } 181 182 virtual bool isValid(std::string &Error) { 183 if (Regex.isValid(Error)) 184 return true; 185 return false; 186 } 187 188 virtual bool match(StringRef S) { 189 return Regex.match(S); 190 } 191 192 private: 193 llvm::Regex Regex; 194 }; 195 196 class ParseHelper 197 { 198 public: 199 ParseHelper(StringRef S) 200 : Begin(S.begin()), End(S.end()), C(Begin), P(Begin), PEnd(NULL) { } 201 202 // Return true if string literal is next. 203 bool Next(StringRef S) { 204 P = C; 205 PEnd = C + S.size(); 206 if (PEnd > End) 207 return false; 208 return !memcmp(P, S.data(), S.size()); 209 } 210 211 // Return true if number is next. 212 // Output N only if number is next. 213 bool Next(unsigned &N) { 214 unsigned TMP = 0; 215 P = C; 216 for (; P < End && P[0] >= '0' && P[0] <= '9'; ++P) { 217 TMP *= 10; 218 TMP += P[0] - '0'; 219 } 220 if (P == C) 221 return false; 222 PEnd = P; 223 N = TMP; 224 return true; 225 } 226 227 // Return true if string literal is found. 228 // When true, P marks begin-position of S in content. 229 bool Search(StringRef S, bool EnsureStartOfWord = false) { 230 do { 231 P = std::search(C, End, S.begin(), S.end()); 232 PEnd = P + S.size(); 233 if (P == End) 234 break; 235 if (!EnsureStartOfWord 236 // Check if string literal starts a new word. 237 || P == Begin || isWhitespace(P[-1]) 238 // Or it could be preceeded by the start of a comment. 239 || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*') 240 && P[-2] == '/')) 241 return true; 242 // Otherwise, skip and search again. 243 } while (Advance()); 244 return false; 245 } 246 247 // Advance 1-past previous next/search. 248 // Behavior is undefined if previous next/search failed. 249 bool Advance() { 250 C = PEnd; 251 return C < End; 252 } 253 254 // Skip zero or more whitespace. 255 void SkipWhitespace() { 256 for (; C < End && isWhitespace(*C); ++C) 257 ; 258 } 259 260 // Return true if EOF reached. 261 bool Done() { 262 return !(C < End); 263 } 264 265 const char * const Begin; // beginning of expected content 266 const char * const End; // end of expected content (1-past) 267 const char *C; // position of next char in content 268 const char *P; 269 270 private: 271 const char *PEnd; // previous next/search subject end (1-past) 272 }; 273 274 } // namespace anonymous 275 276 /// ParseDirective - Go through the comment and see if it indicates expected 277 /// diagnostics. If so, then put them in the appropriate directive list. 278 /// 279 /// Returns true if any valid directives were found. 280 static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM, 281 Preprocessor *PP, SourceLocation Pos, 282 VerifyDiagnosticConsumer::DirectiveStatus &Status) { 283 DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics(); 284 285 // A single comment may contain multiple directives. 286 bool FoundDirective = false; 287 for (ParseHelper PH(S); !PH.Done();) { 288 // Search for token: expected 289 if (!PH.Search("expected", true)) 290 break; 291 PH.Advance(); 292 293 // Next token: - 294 if (!PH.Next("-")) 295 continue; 296 PH.Advance(); 297 298 // Next token: { error | warning | note } 299 DirectiveList* DL = NULL; 300 if (PH.Next("error")) 301 DL = ED ? &ED->Errors : NULL; 302 else if (PH.Next("warning")) 303 DL = ED ? &ED->Warnings : NULL; 304 else if (PH.Next("note")) 305 DL = ED ? &ED->Notes : NULL; 306 else if (PH.Next("no-diagnostics")) { 307 if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives) 308 Diags.Report(Pos, diag::err_verify_invalid_no_diags) 309 << /*IsExpectedNoDiagnostics=*/true; 310 else 311 Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics; 312 continue; 313 } else 314 continue; 315 PH.Advance(); 316 317 if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) { 318 Diags.Report(Pos, diag::err_verify_invalid_no_diags) 319 << /*IsExpectedNoDiagnostics=*/false; 320 continue; 321 } 322 Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives; 323 324 // If a directive has been found but we're not interested 325 // in storing the directive information, return now. 326 if (!DL) 327 return true; 328 329 // Default directive kind. 330 bool RegexKind = false; 331 const char* KindStr = "string"; 332 333 // Next optional token: - 334 if (PH.Next("-re")) { 335 PH.Advance(); 336 RegexKind = true; 337 KindStr = "regex"; 338 } 339 340 // Next optional token: @ 341 SourceLocation ExpectedLoc; 342 if (!PH.Next("@")) { 343 ExpectedLoc = Pos; 344 } else { 345 PH.Advance(); 346 unsigned Line = 0; 347 bool FoundPlus = PH.Next("+"); 348 if (FoundPlus || PH.Next("-")) { 349 // Relative to current line. 350 PH.Advance(); 351 bool Invalid = false; 352 unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid); 353 if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) { 354 if (FoundPlus) ExpectedLine += Line; 355 else ExpectedLine -= Line; 356 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1); 357 } 358 } else if (PH.Next(Line)) { 359 // Absolute line number. 360 if (Line > 0) 361 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1); 362 } else if (PP && PH.Search(":")) { 363 // Specific source file. 364 StringRef Filename(PH.C, PH.P-PH.C); 365 PH.Advance(); 366 367 // Lookup file via Preprocessor, like a #include. 368 const DirectoryLookup *CurDir; 369 const FileEntry *FE = PP->LookupFile(Filename, false, NULL, CurDir, 370 NULL, NULL, 0); 371 if (!FE) { 372 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 373 diag::err_verify_missing_file) << Filename << KindStr; 374 continue; 375 } 376 377 if (SM.translateFile(FE).isInvalid()) 378 SM.createFileID(FE, Pos, SrcMgr::C_User); 379 380 if (PH.Next(Line) && Line > 0) 381 ExpectedLoc = SM.translateFileLineCol(FE, Line, 1); 382 } 383 384 if (ExpectedLoc.isInvalid()) { 385 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 386 diag::err_verify_missing_line) << KindStr; 387 continue; 388 } 389 PH.Advance(); 390 } 391 392 // Skip optional whitespace. 393 PH.SkipWhitespace(); 394 395 // Next optional token: positive integer or a '+'. 396 unsigned Min = 1; 397 unsigned Max = 1; 398 if (PH.Next(Min)) { 399 PH.Advance(); 400 // A positive integer can be followed by a '+' meaning min 401 // or more, or by a '-' meaning a range from min to max. 402 if (PH.Next("+")) { 403 Max = Directive::MaxCount; 404 PH.Advance(); 405 } else if (PH.Next("-")) { 406 PH.Advance(); 407 if (!PH.Next(Max) || Max < Min) { 408 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 409 diag::err_verify_invalid_range) << KindStr; 410 continue; 411 } 412 PH.Advance(); 413 } else { 414 Max = Min; 415 } 416 } else if (PH.Next("+")) { 417 // '+' on its own means "1 or more". 418 Max = Directive::MaxCount; 419 PH.Advance(); 420 } 421 422 // Skip optional whitespace. 423 PH.SkipWhitespace(); 424 425 // Next token: {{ 426 if (!PH.Next("{{")) { 427 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 428 diag::err_verify_missing_start) << KindStr; 429 continue; 430 } 431 PH.Advance(); 432 const char* const ContentBegin = PH.C; // mark content begin 433 434 // Search for token: }} 435 if (!PH.Search("}}")) { 436 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 437 diag::err_verify_missing_end) << KindStr; 438 continue; 439 } 440 const char* const ContentEnd = PH.P; // mark content end 441 PH.Advance(); 442 443 // Build directive text; convert \n to newlines. 444 std::string Text; 445 StringRef NewlineStr = "\\n"; 446 StringRef Content(ContentBegin, ContentEnd-ContentBegin); 447 size_t CPos = 0; 448 size_t FPos; 449 while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) { 450 Text += Content.substr(CPos, FPos-CPos); 451 Text += '\n'; 452 CPos = FPos + NewlineStr.size(); 453 } 454 if (Text.empty()) 455 Text.assign(ContentBegin, ContentEnd); 456 457 // Construct new directive. 458 Directive *D = Directive::create(RegexKind, Pos, ExpectedLoc, Text, 459 Min, Max); 460 std::string Error; 461 if (D->isValid(Error)) { 462 DL->push_back(D); 463 FoundDirective = true; 464 } else { 465 Diags.Report(Pos.getLocWithOffset(ContentBegin-PH.Begin), 466 diag::err_verify_invalid_content) 467 << KindStr << Error; 468 } 469 } 470 471 return FoundDirective; 472 } 473 474 /// HandleComment - Hook into the preprocessor and extract comments containing 475 /// expected errors and warnings. 476 bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP, 477 SourceRange Comment) { 478 SourceManager &SM = PP.getSourceManager(); 479 SourceLocation CommentBegin = Comment.getBegin(); 480 481 const char *CommentRaw = SM.getCharacterData(CommentBegin); 482 StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw); 483 484 if (C.empty()) 485 return false; 486 487 // Fold any "\<EOL>" sequences 488 size_t loc = C.find('\\'); 489 if (loc == StringRef::npos) { 490 ParseDirective(C, &ED, SM, &PP, CommentBegin, Status); 491 return false; 492 } 493 494 std::string C2; 495 C2.reserve(C.size()); 496 497 for (size_t last = 0;; loc = C.find('\\', last)) { 498 if (loc == StringRef::npos || loc == C.size()) { 499 C2 += C.substr(last); 500 break; 501 } 502 C2 += C.substr(last, loc-last); 503 last = loc + 1; 504 505 if (C[last] == '\n' || C[last] == '\r') { 506 ++last; 507 508 // Escape \r\n or \n\r, but not \n\n. 509 if (last < C.size()) 510 if (C[last] == '\n' || C[last] == '\r') 511 if (C[last] != C[last-1]) 512 ++last; 513 } else { 514 // This was just a normal backslash. 515 C2 += '\\'; 516 } 517 } 518 519 if (!C2.empty()) 520 ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status); 521 return false; 522 } 523 524 #ifndef NDEBUG 525 /// \brief Lex the specified source file to determine whether it contains 526 /// any expected-* directives. As a Lexer is used rather than a full-blown 527 /// Preprocessor, directives inside skipped #if blocks will still be found. 528 /// 529 /// \return true if any directives were found. 530 static bool findDirectives(SourceManager &SM, FileID FID, 531 const LangOptions &LangOpts) { 532 // Create a raw lexer to pull all the comments out of FID. 533 if (FID.isInvalid()) 534 return false; 535 536 // Create a lexer to lex all the tokens of the main file in raw mode. 537 const llvm::MemoryBuffer *FromFile = SM.getBuffer(FID); 538 Lexer RawLex(FID, FromFile, SM, LangOpts); 539 540 // Return comments as tokens, this is how we find expected diagnostics. 541 RawLex.SetCommentRetentionState(true); 542 543 Token Tok; 544 Tok.setKind(tok::comment); 545 VerifyDiagnosticConsumer::DirectiveStatus Status = 546 VerifyDiagnosticConsumer::HasNoDirectives; 547 while (Tok.isNot(tok::eof)) { 548 RawLex.Lex(Tok); 549 if (!Tok.is(tok::comment)) continue; 550 551 std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts); 552 if (Comment.empty()) continue; 553 554 // Find first directive. 555 if (ParseDirective(Comment, 0, SM, 0, Tok.getLocation(), Status)) 556 return true; 557 } 558 return false; 559 } 560 #endif // !NDEBUG 561 562 /// \brief Takes a list of diagnostics that have been generated but not matched 563 /// by an expected-* directive and produces a diagnostic to the user from this. 564 static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr, 565 const_diag_iterator diag_begin, 566 const_diag_iterator diag_end, 567 const char *Kind) { 568 if (diag_begin == diag_end) return 0; 569 570 SmallString<256> Fmt; 571 llvm::raw_svector_ostream OS(Fmt); 572 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) { 573 if (I->first.isInvalid() || !SourceMgr) 574 OS << "\n (frontend)"; 575 else { 576 OS << "\n "; 577 if (const FileEntry *File = SourceMgr->getFileEntryForID( 578 SourceMgr->getFileID(I->first))) 579 OS << " File " << File->getName(); 580 OS << " Line " << SourceMgr->getPresumedLineNumber(I->first); 581 } 582 OS << ": " << I->second; 583 } 584 585 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit() 586 << Kind << /*Unexpected=*/true << OS.str(); 587 return std::distance(diag_begin, diag_end); 588 } 589 590 /// \brief Takes a list of diagnostics that were expected to have been generated 591 /// but were not and produces a diagnostic to the user from this. 592 static unsigned PrintExpected(DiagnosticsEngine &Diags, SourceManager &SourceMgr, 593 DirectiveList &DL, const char *Kind) { 594 if (DL.empty()) 595 return 0; 596 597 SmallString<256> Fmt; 598 llvm::raw_svector_ostream OS(Fmt); 599 for (DirectiveList::iterator I = DL.begin(), E = DL.end(); I != E; ++I) { 600 Directive &D = **I; 601 OS << "\n File " << SourceMgr.getFilename(D.DiagnosticLoc) 602 << " Line " << SourceMgr.getPresumedLineNumber(D.DiagnosticLoc); 603 if (D.DirectiveLoc != D.DiagnosticLoc) 604 OS << " (directive at " 605 << SourceMgr.getFilename(D.DirectiveLoc) << ':' 606 << SourceMgr.getPresumedLineNumber(D.DirectiveLoc) << ')'; 607 OS << ": " << D.Text; 608 } 609 610 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit() 611 << Kind << /*Unexpected=*/false << OS.str(); 612 return DL.size(); 613 } 614 615 /// \brief Determine whether two source locations come from the same file. 616 static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc, 617 SourceLocation DiagnosticLoc) { 618 while (DiagnosticLoc.isMacroID()) 619 DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc); 620 621 if (SM.isFromSameFile(DirectiveLoc, DiagnosticLoc)) 622 return true; 623 624 const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc)); 625 if (!DiagFile && SM.isFromMainFile(DirectiveLoc)) 626 return true; 627 628 return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc))); 629 } 630 631 /// CheckLists - Compare expected to seen diagnostic lists and return the 632 /// the difference between them. 633 /// 634 static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr, 635 const char *Label, 636 DirectiveList &Left, 637 const_diag_iterator d2_begin, 638 const_diag_iterator d2_end) { 639 DirectiveList LeftOnly; 640 DiagList Right(d2_begin, d2_end); 641 642 for (DirectiveList::iterator I = Left.begin(), E = Left.end(); I != E; ++I) { 643 Directive& D = **I; 644 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc); 645 646 for (unsigned i = 0; i < D.Max; ++i) { 647 DiagList::iterator II, IE; 648 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) { 649 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first); 650 if (LineNo1 != LineNo2) 651 continue; 652 653 if (!IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first)) 654 continue; 655 656 const std::string &RightText = II->second; 657 if (D.match(RightText)) 658 break; 659 } 660 if (II == IE) { 661 // Not found. 662 if (i >= D.Min) break; 663 LeftOnly.push_back(*I); 664 } else { 665 // Found. The same cannot be found twice. 666 Right.erase(II); 667 } 668 } 669 } 670 // Now all that's left in Right are those that were not matched. 671 unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label); 672 num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label); 673 return num; 674 } 675 676 /// CheckResults - This compares the expected results to those that 677 /// were actually reported. It emits any discrepencies. Return "true" if there 678 /// were problems. Return "false" otherwise. 679 /// 680 static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr, 681 const TextDiagnosticBuffer &Buffer, 682 ExpectedData &ED) { 683 // We want to capture the delta between what was expected and what was 684 // seen. 685 // 686 // Expected \ Seen - set expected but not seen 687 // Seen \ Expected - set seen but not expected 688 unsigned NumProblems = 0; 689 690 // See if there are error mismatches. 691 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors, 692 Buffer.err_begin(), Buffer.err_end()); 693 694 // See if there are warning mismatches. 695 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings, 696 Buffer.warn_begin(), Buffer.warn_end()); 697 698 // See if there are note mismatches. 699 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes, 700 Buffer.note_begin(), Buffer.note_end()); 701 702 return NumProblems; 703 } 704 705 void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM, 706 FileID FID, 707 ParsedStatus PS) { 708 // Check SourceManager hasn't changed. 709 setSourceManager(SM); 710 711 #ifndef NDEBUG 712 if (FID.isInvalid()) 713 return; 714 715 const FileEntry *FE = SM.getFileEntryForID(FID); 716 717 if (PS == IsParsed) { 718 // Move the FileID from the unparsed set to the parsed set. 719 UnparsedFiles.erase(FID); 720 ParsedFiles.insert(std::make_pair(FID, FE)); 721 } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) { 722 // Add the FileID to the unparsed set if we haven't seen it before. 723 724 // Check for directives. 725 bool FoundDirectives; 726 if (PS == IsUnparsedNoDirectives) 727 FoundDirectives = false; 728 else 729 FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts); 730 731 // Add the FileID to the unparsed set. 732 UnparsedFiles.insert(std::make_pair(FID, 733 UnparsedFileStatus(FE, FoundDirectives))); 734 } 735 #endif 736 } 737 738 void VerifyDiagnosticConsumer::CheckDiagnostics() { 739 // Ensure any diagnostics go to the primary client. 740 bool OwnsCurClient = Diags.ownsClient(); 741 DiagnosticConsumer *CurClient = Diags.takeClient(); 742 Diags.setClient(PrimaryClient, false); 743 744 #ifndef NDEBUG 745 // In a debug build, scan through any files that may have been missed 746 // during parsing and issue a fatal error if directives are contained 747 // within these files. If a fatal error occurs, this suggests that 748 // this file is being parsed separately from the main file, in which 749 // case consider moving the directives to the correct place, if this 750 // is applicable. 751 if (UnparsedFiles.size() > 0) { 752 // Generate a cache of parsed FileEntry pointers for alias lookups. 753 llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache; 754 for (ParsedFilesMap::iterator I = ParsedFiles.begin(), 755 End = ParsedFiles.end(); I != End; ++I) { 756 if (const FileEntry *FE = I->second) 757 ParsedFileCache.insert(FE); 758 } 759 760 // Iterate through list of unparsed files. 761 for (UnparsedFilesMap::iterator I = UnparsedFiles.begin(), 762 End = UnparsedFiles.end(); I != End; ++I) { 763 const UnparsedFileStatus &Status = I->second; 764 const FileEntry *FE = Status.getFile(); 765 766 // Skip files that have been parsed via an alias. 767 if (FE && ParsedFileCache.count(FE)) 768 continue; 769 770 // Report a fatal error if this file contained directives. 771 if (Status.foundDirectives()) { 772 llvm::report_fatal_error(Twine("-verify directives found after rather" 773 " than during normal parsing of ", 774 StringRef(FE ? FE->getName() : "(unknown)"))); 775 } 776 } 777 778 // UnparsedFiles has been processed now, so clear it. 779 UnparsedFiles.clear(); 780 } 781 #endif // !NDEBUG 782 783 if (SrcManager) { 784 // Produce an error if no expected-* directives could be found in the 785 // source file(s) processed. 786 if (Status == HasNoDirectives) { 787 Diags.Report(diag::err_verify_no_directives).setForceEmit(); 788 ++NumErrors; 789 Status = HasNoDirectivesReported; 790 } 791 792 // Check that the expected diagnostics occurred. 793 NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED); 794 } else { 795 NumErrors += (PrintUnexpected(Diags, 0, Buffer->err_begin(), 796 Buffer->err_end(), "error") + 797 PrintUnexpected(Diags, 0, Buffer->warn_begin(), 798 Buffer->warn_end(), "warn") + 799 PrintUnexpected(Diags, 0, Buffer->note_begin(), 800 Buffer->note_end(), "note")); 801 } 802 803 Diags.takeClient(); 804 Diags.setClient(CurClient, OwnsCurClient); 805 806 // Reset the buffer, we have processed all the diagnostics in it. 807 Buffer.reset(new TextDiagnosticBuffer()); 808 ED.Errors.clear(); 809 ED.Warnings.clear(); 810 ED.Notes.clear(); 811 } 812 813 DiagnosticConsumer * 814 VerifyDiagnosticConsumer::clone(DiagnosticsEngine &Diags) const { 815 if (!Diags.getClient()) 816 Diags.setClient(PrimaryClient->clone(Diags)); 817 818 return new VerifyDiagnosticConsumer(Diags); 819 } 820 821 Directive *Directive::create(bool RegexKind, SourceLocation DirectiveLoc, 822 SourceLocation DiagnosticLoc, StringRef Text, 823 unsigned Min, unsigned Max) { 824 if (RegexKind) 825 return new RegexDirective(DirectiveLoc, DiagnosticLoc, Text, Min, Max); 826 return new StandardDirective(DirectiveLoc, DiagnosticLoc, Text, Min, Max); 827 } 828