1 //===- VerifyDiagnosticConsumer.cpp - Verifying Diagnostic Client ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This is a concrete diagnostic client, which buffers the diagnostic messages. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/Frontend/VerifyDiagnosticConsumer.h" 14 #include "clang/Basic/CharInfo.h" 15 #include "clang/Basic/Diagnostic.h" 16 #include "clang/Basic/DiagnosticOptions.h" 17 #include "clang/Basic/FileManager.h" 18 #include "clang/Basic/LLVM.h" 19 #include "clang/Basic/SourceLocation.h" 20 #include "clang/Basic/SourceManager.h" 21 #include "clang/Basic/TokenKinds.h" 22 #include "clang/Frontend/FrontendDiagnostic.h" 23 #include "clang/Frontend/TextDiagnosticBuffer.h" 24 #include "clang/Lex/HeaderSearch.h" 25 #include "clang/Lex/Lexer.h" 26 #include "clang/Lex/PPCallbacks.h" 27 #include "clang/Lex/Preprocessor.h" 28 #include "clang/Lex/Token.h" 29 #include "llvm/ADT/STLExtras.h" 30 #include "llvm/ADT/SmallPtrSet.h" 31 #include "llvm/ADT/SmallString.h" 32 #include "llvm/ADT/StringRef.h" 33 #include "llvm/ADT/Twine.h" 34 #include "llvm/Support/ErrorHandling.h" 35 #include "llvm/Support/Regex.h" 36 #include "llvm/Support/raw_ostream.h" 37 #include <algorithm> 38 #include <cassert> 39 #include <cstddef> 40 #include <cstring> 41 #include <iterator> 42 #include <memory> 43 #include <string> 44 #include <utility> 45 #include <vector> 46 47 using namespace clang; 48 49 using Directive = VerifyDiagnosticConsumer::Directive; 50 using DirectiveList = VerifyDiagnosticConsumer::DirectiveList; 51 using ExpectedData = VerifyDiagnosticConsumer::ExpectedData; 52 53 #ifndef NDEBUG 54 55 namespace { 56 57 class VerifyFileTracker : public PPCallbacks { 58 VerifyDiagnosticConsumer &Verify; 59 SourceManager &SM; 60 61 public: 62 VerifyFileTracker(VerifyDiagnosticConsumer &Verify, SourceManager &SM) 63 : Verify(Verify), SM(SM) {} 64 65 /// Hook into the preprocessor and update the list of parsed 66 /// files when the preprocessor indicates a new file is entered. 67 void FileChanged(SourceLocation Loc, FileChangeReason Reason, 68 SrcMgr::CharacteristicKind FileType, 69 FileID PrevFID) override { 70 Verify.UpdateParsedFileStatus(SM, SM.getFileID(Loc), 71 VerifyDiagnosticConsumer::IsParsed); 72 } 73 }; 74 75 } // namespace 76 77 #endif 78 79 //===----------------------------------------------------------------------===// 80 // Checking diagnostics implementation. 81 //===----------------------------------------------------------------------===// 82 83 using DiagList = TextDiagnosticBuffer::DiagList; 84 using const_diag_iterator = TextDiagnosticBuffer::const_iterator; 85 86 namespace { 87 88 /// StandardDirective - Directive with string matching. 89 class StandardDirective : public Directive { 90 public: 91 StandardDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc, 92 bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text, 93 unsigned Min, unsigned Max) 94 : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine, 95 MatchAnyLine, Text, Min, Max) {} 96 97 bool isValid(std::string &Error) override { 98 // all strings are considered valid; even empty ones 99 return true; 100 } 101 102 bool match(StringRef S) override { return S.contains(Text); } 103 }; 104 105 /// RegexDirective - Directive with regular-expression matching. 106 class RegexDirective : public Directive { 107 public: 108 RegexDirective(SourceLocation DirectiveLoc, SourceLocation DiagnosticLoc, 109 bool MatchAnyFileAndLine, bool MatchAnyLine, StringRef Text, 110 unsigned Min, unsigned Max, StringRef RegexStr) 111 : Directive(DirectiveLoc, DiagnosticLoc, MatchAnyFileAndLine, 112 MatchAnyLine, Text, Min, Max), 113 Regex(RegexStr) {} 114 115 bool isValid(std::string &Error) override { 116 return Regex.isValid(Error); 117 } 118 119 bool match(StringRef S) override { 120 return Regex.match(S); 121 } 122 123 private: 124 llvm::Regex Regex; 125 }; 126 127 class ParseHelper 128 { 129 public: 130 ParseHelper(StringRef S) 131 : Begin(S.begin()), End(S.end()), C(Begin), P(Begin) {} 132 133 // Return true if string literal is next. 134 bool Next(StringRef S) { 135 P = C; 136 PEnd = C + S.size(); 137 if (PEnd > End) 138 return false; 139 return memcmp(P, S.data(), S.size()) == 0; 140 } 141 142 // Return true if number is next. 143 // Output N only if number is next. 144 bool Next(unsigned &N) { 145 unsigned TMP = 0; 146 P = C; 147 PEnd = P; 148 for (; PEnd < End && *PEnd >= '0' && *PEnd <= '9'; ++PEnd) { 149 TMP *= 10; 150 TMP += *PEnd - '0'; 151 } 152 if (PEnd == C) 153 return false; 154 N = TMP; 155 return true; 156 } 157 158 // Return true if a marker is next. 159 // A marker is the longest match for /#[A-Za-z0-9_-]+/. 160 bool NextMarker() { 161 P = C; 162 if (P == End || *P != '#') 163 return false; 164 PEnd = P; 165 ++PEnd; 166 while ((isAlphanumeric(*PEnd) || *PEnd == '-' || *PEnd == '_') && 167 PEnd < End) 168 ++PEnd; 169 return PEnd > P + 1; 170 } 171 172 // Return true if string literal S is matched in content. 173 // When true, P marks begin-position of the match, and calling Advance sets C 174 // to end-position of the match. 175 // If S is the empty string, then search for any letter instead (makes sense 176 // with FinishDirectiveToken=true). 177 // If EnsureStartOfWord, then skip matches that don't start a new word. 178 // If FinishDirectiveToken, then assume the match is the start of a comment 179 // directive for -verify, and extend the match to include the entire first 180 // token of that directive. 181 bool Search(StringRef S, bool EnsureStartOfWord = false, 182 bool FinishDirectiveToken = false) { 183 do { 184 if (!S.empty()) { 185 P = std::search(C, End, S.begin(), S.end()); 186 PEnd = P + S.size(); 187 } 188 else { 189 P = C; 190 while (P != End && !isLetter(*P)) 191 ++P; 192 PEnd = P + 1; 193 } 194 if (P == End) 195 break; 196 // If not start of word but required, skip and search again. 197 if (EnsureStartOfWord 198 // Check if string literal starts a new word. 199 && !(P == Begin || isWhitespace(P[-1]) 200 // Or it could be preceded by the start of a comment. 201 || (P > (Begin + 1) && (P[-1] == '/' || P[-1] == '*') 202 && P[-2] == '/'))) 203 continue; 204 if (FinishDirectiveToken) { 205 while (PEnd != End && (isAlphanumeric(*PEnd) 206 || *PEnd == '-' || *PEnd == '_')) 207 ++PEnd; 208 // Put back trailing digits and hyphens to be parsed later as a count 209 // or count range. Because -verify prefixes must start with letters, 210 // we know the actual directive we found starts with a letter, so 211 // we won't put back the entire directive word and thus record an empty 212 // string. 213 assert(isLetter(*P) && "-verify prefix must start with a letter"); 214 while (isDigit(PEnd[-1]) || PEnd[-1] == '-') 215 --PEnd; 216 } 217 return true; 218 } while (Advance()); 219 return false; 220 } 221 222 // Return true if a CloseBrace that closes the OpenBrace at the current nest 223 // level is found. When true, P marks begin-position of CloseBrace. 224 bool SearchClosingBrace(StringRef OpenBrace, StringRef CloseBrace) { 225 unsigned Depth = 1; 226 P = C; 227 while (P < End) { 228 StringRef S(P, End - P); 229 if (S.startswith(OpenBrace)) { 230 ++Depth; 231 P += OpenBrace.size(); 232 } else if (S.startswith(CloseBrace)) { 233 --Depth; 234 if (Depth == 0) { 235 PEnd = P + CloseBrace.size(); 236 return true; 237 } 238 P += CloseBrace.size(); 239 } else { 240 ++P; 241 } 242 } 243 return false; 244 } 245 246 // Advance 1-past previous next/search. 247 // Behavior is undefined if previous next/search failed. 248 bool Advance() { 249 C = PEnd; 250 return C < End; 251 } 252 253 // Return the text matched by the previous next/search. 254 // Behavior is undefined if previous next/search failed. 255 StringRef Match() { return StringRef(P, PEnd - P); } 256 257 // Skip zero or more whitespace. 258 void SkipWhitespace() { 259 for (; C < End && isWhitespace(*C); ++C) 260 ; 261 } 262 263 // Return true if EOF reached. 264 bool Done() { 265 return !(C < End); 266 } 267 268 // Beginning of expected content. 269 const char * const Begin; 270 271 // End of expected content (1-past). 272 const char * const End; 273 274 // Position of next char in content. 275 const char *C; 276 277 // Previous next/search subject start. 278 const char *P; 279 280 private: 281 // Previous next/search subject end (1-past). 282 const char *PEnd = nullptr; 283 }; 284 285 // The information necessary to create a directive. 286 struct UnattachedDirective { 287 DirectiveList *DL = nullptr; 288 bool RegexKind = false; 289 SourceLocation DirectivePos, ContentBegin; 290 std::string Text; 291 unsigned Min = 1, Max = 1; 292 }; 293 294 // Attach the specified directive to the line of code indicated by 295 // \p ExpectedLoc. 296 void attachDirective(DiagnosticsEngine &Diags, const UnattachedDirective &UD, 297 SourceLocation ExpectedLoc, 298 bool MatchAnyFileAndLine = false, 299 bool MatchAnyLine = false) { 300 // Construct new directive. 301 std::unique_ptr<Directive> D = Directive::create( 302 UD.RegexKind, UD.DirectivePos, ExpectedLoc, MatchAnyFileAndLine, 303 MatchAnyLine, UD.Text, UD.Min, UD.Max); 304 305 std::string Error; 306 if (!D->isValid(Error)) { 307 Diags.Report(UD.ContentBegin, diag::err_verify_invalid_content) 308 << (UD.RegexKind ? "regex" : "string") << Error; 309 } 310 311 UD.DL->push_back(std::move(D)); 312 } 313 314 } // anonymous 315 316 // Tracker for markers in the input files. A marker is a comment of the form 317 // 318 // n = 123; // #123 319 // 320 // ... that can be referred to by a later expected-* directive: 321 // 322 // // expected-error@#123 {{undeclared identifier 'n'}} 323 // 324 // Marker declarations must be at the start of a comment or preceded by 325 // whitespace to distinguish them from uses of markers in directives. 326 class VerifyDiagnosticConsumer::MarkerTracker { 327 DiagnosticsEngine &Diags; 328 329 struct Marker { 330 SourceLocation DefLoc; 331 SourceLocation RedefLoc; 332 SourceLocation UseLoc; 333 }; 334 llvm::StringMap<Marker> Markers; 335 336 // Directives that couldn't be created yet because they name an unknown 337 // marker. 338 llvm::StringMap<llvm::SmallVector<UnattachedDirective, 2>> DeferredDirectives; 339 340 public: 341 MarkerTracker(DiagnosticsEngine &Diags) : Diags(Diags) {} 342 343 // Register a marker. 344 void addMarker(StringRef MarkerName, SourceLocation Pos) { 345 auto InsertResult = Markers.insert( 346 {MarkerName, Marker{Pos, SourceLocation(), SourceLocation()}}); 347 348 Marker &M = InsertResult.first->second; 349 if (!InsertResult.second) { 350 // Marker was redefined. 351 M.RedefLoc = Pos; 352 } else { 353 // First definition: build any deferred directives. 354 auto Deferred = DeferredDirectives.find(MarkerName); 355 if (Deferred != DeferredDirectives.end()) { 356 for (auto &UD : Deferred->second) { 357 if (M.UseLoc.isInvalid()) 358 M.UseLoc = UD.DirectivePos; 359 attachDirective(Diags, UD, Pos); 360 } 361 DeferredDirectives.erase(Deferred); 362 } 363 } 364 } 365 366 // Register a directive at the specified marker. 367 void addDirective(StringRef MarkerName, const UnattachedDirective &UD) { 368 auto MarkerIt = Markers.find(MarkerName); 369 if (MarkerIt != Markers.end()) { 370 Marker &M = MarkerIt->second; 371 if (M.UseLoc.isInvalid()) 372 M.UseLoc = UD.DirectivePos; 373 return attachDirective(Diags, UD, M.DefLoc); 374 } 375 DeferredDirectives[MarkerName].push_back(UD); 376 } 377 378 // Ensure we have no remaining deferred directives, and no 379 // multiply-defined-and-used markers. 380 void finalize() { 381 for (auto &MarkerInfo : Markers) { 382 StringRef Name = MarkerInfo.first(); 383 Marker &M = MarkerInfo.second; 384 if (M.RedefLoc.isValid() && M.UseLoc.isValid()) { 385 Diags.Report(M.UseLoc, diag::err_verify_ambiguous_marker) << Name; 386 Diags.Report(M.DefLoc, diag::note_verify_ambiguous_marker) << Name; 387 Diags.Report(M.RedefLoc, diag::note_verify_ambiguous_marker) << Name; 388 } 389 } 390 391 for (auto &DeferredPair : DeferredDirectives) { 392 Diags.Report(DeferredPair.second.front().DirectivePos, 393 diag::err_verify_no_such_marker) 394 << DeferredPair.first(); 395 } 396 } 397 }; 398 399 /// ParseDirective - Go through the comment and see if it indicates expected 400 /// diagnostics. If so, then put them in the appropriate directive list. 401 /// 402 /// Returns true if any valid directives were found. 403 static bool ParseDirective(StringRef S, ExpectedData *ED, SourceManager &SM, 404 Preprocessor *PP, SourceLocation Pos, 405 VerifyDiagnosticConsumer::DirectiveStatus &Status, 406 VerifyDiagnosticConsumer::MarkerTracker &Markers) { 407 DiagnosticsEngine &Diags = PP ? PP->getDiagnostics() : SM.getDiagnostics(); 408 409 // First, scan the comment looking for markers. 410 for (ParseHelper PH(S); !PH.Done();) { 411 if (!PH.Search("#", true)) 412 break; 413 PH.C = PH.P; 414 if (!PH.NextMarker()) { 415 PH.Next("#"); 416 PH.Advance(); 417 continue; 418 } 419 PH.Advance(); 420 Markers.addMarker(PH.Match(), Pos); 421 } 422 423 // A single comment may contain multiple directives. 424 bool FoundDirective = false; 425 for (ParseHelper PH(S); !PH.Done();) { 426 // Search for the initial directive token. 427 // If one prefix, save time by searching only for its directives. 428 // Otherwise, search for any potential directive token and check it later. 429 const auto &Prefixes = Diags.getDiagnosticOptions().VerifyPrefixes; 430 if (!(Prefixes.size() == 1 ? PH.Search(*Prefixes.begin(), true, true) 431 : PH.Search("", true, true))) 432 break; 433 434 StringRef DToken = PH.Match(); 435 PH.Advance(); 436 437 // Default directive kind. 438 UnattachedDirective D; 439 const char *KindStr = "string"; 440 441 // Parse the initial directive token in reverse so we can easily determine 442 // its exact actual prefix. If we were to parse it from the front instead, 443 // it would be harder to determine where the prefix ends because there 444 // might be multiple matching -verify prefixes because some might prefix 445 // others. 446 447 // Regex in initial directive token: -re 448 if (DToken.endswith("-re")) { 449 D.RegexKind = true; 450 KindStr = "regex"; 451 DToken = DToken.substr(0, DToken.size()-3); 452 } 453 454 // Type in initial directive token: -{error|warning|note|no-diagnostics} 455 bool NoDiag = false; 456 StringRef DType; 457 if (DToken.endswith(DType="-error")) 458 D.DL = ED ? &ED->Errors : nullptr; 459 else if (DToken.endswith(DType="-warning")) 460 D.DL = ED ? &ED->Warnings : nullptr; 461 else if (DToken.endswith(DType="-remark")) 462 D.DL = ED ? &ED->Remarks : nullptr; 463 else if (DToken.endswith(DType="-note")) 464 D.DL = ED ? &ED->Notes : nullptr; 465 else if (DToken.endswith(DType="-no-diagnostics")) { 466 NoDiag = true; 467 if (D.RegexKind) 468 continue; 469 } 470 else 471 continue; 472 DToken = DToken.substr(0, DToken.size()-DType.size()); 473 474 // What's left in DToken is the actual prefix. That might not be a -verify 475 // prefix even if there is only one -verify prefix (for example, the full 476 // DToken is foo-bar-warning, but foo is the only -verify prefix). 477 if (!std::binary_search(Prefixes.begin(), Prefixes.end(), DToken)) 478 continue; 479 480 if (NoDiag) { 481 if (Status == VerifyDiagnosticConsumer::HasOtherExpectedDirectives) 482 Diags.Report(Pos, diag::err_verify_invalid_no_diags) 483 << /*IsExpectedNoDiagnostics=*/true; 484 else 485 Status = VerifyDiagnosticConsumer::HasExpectedNoDiagnostics; 486 continue; 487 } 488 if (Status == VerifyDiagnosticConsumer::HasExpectedNoDiagnostics) { 489 Diags.Report(Pos, diag::err_verify_invalid_no_diags) 490 << /*IsExpectedNoDiagnostics=*/false; 491 continue; 492 } 493 Status = VerifyDiagnosticConsumer::HasOtherExpectedDirectives; 494 495 // If a directive has been found but we're not interested 496 // in storing the directive information, return now. 497 if (!D.DL) 498 return true; 499 500 // Next optional token: @ 501 SourceLocation ExpectedLoc; 502 StringRef Marker; 503 bool MatchAnyFileAndLine = false; 504 bool MatchAnyLine = false; 505 if (!PH.Next("@")) { 506 ExpectedLoc = Pos; 507 } else { 508 PH.Advance(); 509 unsigned Line = 0; 510 bool FoundPlus = PH.Next("+"); 511 if (FoundPlus || PH.Next("-")) { 512 // Relative to current line. 513 PH.Advance(); 514 bool Invalid = false; 515 unsigned ExpectedLine = SM.getSpellingLineNumber(Pos, &Invalid); 516 if (!Invalid && PH.Next(Line) && (FoundPlus || Line < ExpectedLine)) { 517 if (FoundPlus) ExpectedLine += Line; 518 else ExpectedLine -= Line; 519 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), ExpectedLine, 1); 520 } 521 } else if (PH.Next(Line)) { 522 // Absolute line number. 523 if (Line > 0) 524 ExpectedLoc = SM.translateLineCol(SM.getFileID(Pos), Line, 1); 525 } else if (PH.NextMarker()) { 526 Marker = PH.Match(); 527 } else if (PP && PH.Search(":")) { 528 // Specific source file. 529 StringRef Filename(PH.C, PH.P-PH.C); 530 PH.Advance(); 531 532 if (Filename == "*") { 533 MatchAnyFileAndLine = true; 534 if (!PH.Next("*")) { 535 Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin), 536 diag::err_verify_missing_line) 537 << "'*'"; 538 continue; 539 } 540 MatchAnyLine = true; 541 ExpectedLoc = SourceLocation(); 542 } else { 543 // Lookup file via Preprocessor, like a #include. 544 const DirectoryLookup *CurDir; 545 Optional<FileEntryRef> File = 546 PP->LookupFile(Pos, Filename, false, nullptr, nullptr, CurDir, 547 nullptr, nullptr, nullptr, nullptr, nullptr); 548 if (!File) { 549 Diags.Report(Pos.getLocWithOffset(PH.C - PH.Begin), 550 diag::err_verify_missing_file) 551 << Filename << KindStr; 552 continue; 553 } 554 555 FileID FID = SM.translateFile(*File); 556 if (FID.isInvalid()) 557 FID = SM.createFileID(*File, Pos, SrcMgr::C_User); 558 559 if (PH.Next(Line) && Line > 0) 560 ExpectedLoc = SM.translateLineCol(FID, Line, 1); 561 else if (PH.Next("*")) { 562 MatchAnyLine = true; 563 ExpectedLoc = SM.translateLineCol(FID, 1, 1); 564 } 565 } 566 } else if (PH.Next("*")) { 567 MatchAnyLine = true; 568 ExpectedLoc = SourceLocation(); 569 } 570 571 if (ExpectedLoc.isInvalid() && !MatchAnyLine && Marker.empty()) { 572 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 573 diag::err_verify_missing_line) << KindStr; 574 continue; 575 } 576 PH.Advance(); 577 } 578 579 // Skip optional whitespace. 580 PH.SkipWhitespace(); 581 582 // Next optional token: positive integer or a '+'. 583 if (PH.Next(D.Min)) { 584 PH.Advance(); 585 // A positive integer can be followed by a '+' meaning min 586 // or more, or by a '-' meaning a range from min to max. 587 if (PH.Next("+")) { 588 D.Max = Directive::MaxCount; 589 PH.Advance(); 590 } else if (PH.Next("-")) { 591 PH.Advance(); 592 if (!PH.Next(D.Max) || D.Max < D.Min) { 593 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 594 diag::err_verify_invalid_range) << KindStr; 595 continue; 596 } 597 PH.Advance(); 598 } else { 599 D.Max = D.Min; 600 } 601 } else if (PH.Next("+")) { 602 // '+' on its own means "1 or more". 603 D.Max = Directive::MaxCount; 604 PH.Advance(); 605 } 606 607 // Skip optional whitespace. 608 PH.SkipWhitespace(); 609 610 // Next token: {{ 611 if (!PH.Next("{{")) { 612 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 613 diag::err_verify_missing_start) << KindStr; 614 continue; 615 } 616 PH.Advance(); 617 const char* const ContentBegin = PH.C; // mark content begin 618 // Search for token: }} 619 if (!PH.SearchClosingBrace("{{", "}}")) { 620 Diags.Report(Pos.getLocWithOffset(PH.C-PH.Begin), 621 diag::err_verify_missing_end) << KindStr; 622 continue; 623 } 624 const char* const ContentEnd = PH.P; // mark content end 625 PH.Advance(); 626 627 D.DirectivePos = Pos; 628 D.ContentBegin = Pos.getLocWithOffset(ContentBegin - PH.Begin); 629 630 // Build directive text; convert \n to newlines. 631 StringRef NewlineStr = "\\n"; 632 StringRef Content(ContentBegin, ContentEnd-ContentBegin); 633 size_t CPos = 0; 634 size_t FPos; 635 while ((FPos = Content.find(NewlineStr, CPos)) != StringRef::npos) { 636 D.Text += Content.substr(CPos, FPos-CPos); 637 D.Text += '\n'; 638 CPos = FPos + NewlineStr.size(); 639 } 640 if (D.Text.empty()) 641 D.Text.assign(ContentBegin, ContentEnd); 642 643 // Check that regex directives contain at least one regex. 644 if (D.RegexKind && D.Text.find("{{") == StringRef::npos) { 645 Diags.Report(D.ContentBegin, diag::err_verify_missing_regex) << D.Text; 646 return false; 647 } 648 649 if (Marker.empty()) 650 attachDirective(Diags, D, ExpectedLoc, MatchAnyFileAndLine, MatchAnyLine); 651 else 652 Markers.addDirective(Marker, D); 653 FoundDirective = true; 654 } 655 656 return FoundDirective; 657 } 658 659 VerifyDiagnosticConsumer::VerifyDiagnosticConsumer(DiagnosticsEngine &Diags_) 660 : Diags(Diags_), PrimaryClient(Diags.getClient()), 661 PrimaryClientOwner(Diags.takeClient()), 662 Buffer(new TextDiagnosticBuffer()), Markers(new MarkerTracker(Diags)), 663 Status(HasNoDirectives) { 664 if (Diags.hasSourceManager()) 665 setSourceManager(Diags.getSourceManager()); 666 } 667 668 VerifyDiagnosticConsumer::~VerifyDiagnosticConsumer() { 669 assert(!ActiveSourceFiles && "Incomplete parsing of source files!"); 670 assert(!CurrentPreprocessor && "CurrentPreprocessor should be invalid!"); 671 SrcManager = nullptr; 672 CheckDiagnostics(); 673 assert(!Diags.ownsClient() && 674 "The VerifyDiagnosticConsumer takes over ownership of the client!"); 675 } 676 677 // DiagnosticConsumer interface. 678 679 void VerifyDiagnosticConsumer::BeginSourceFile(const LangOptions &LangOpts, 680 const Preprocessor *PP) { 681 // Attach comment handler on first invocation. 682 if (++ActiveSourceFiles == 1) { 683 if (PP) { 684 CurrentPreprocessor = PP; 685 this->LangOpts = &LangOpts; 686 setSourceManager(PP->getSourceManager()); 687 const_cast<Preprocessor *>(PP)->addCommentHandler(this); 688 #ifndef NDEBUG 689 // Debug build tracks parsed files. 690 const_cast<Preprocessor *>(PP)->addPPCallbacks( 691 std::make_unique<VerifyFileTracker>(*this, *SrcManager)); 692 #endif 693 } 694 } 695 696 assert((!PP || CurrentPreprocessor == PP) && "Preprocessor changed!"); 697 PrimaryClient->BeginSourceFile(LangOpts, PP); 698 } 699 700 void VerifyDiagnosticConsumer::EndSourceFile() { 701 assert(ActiveSourceFiles && "No active source files!"); 702 PrimaryClient->EndSourceFile(); 703 704 // Detach comment handler once last active source file completed. 705 if (--ActiveSourceFiles == 0) { 706 if (CurrentPreprocessor) 707 const_cast<Preprocessor *>(CurrentPreprocessor)-> 708 removeCommentHandler(this); 709 710 // Diagnose any used-but-not-defined markers. 711 Markers->finalize(); 712 713 // Check diagnostics once last file completed. 714 CheckDiagnostics(); 715 CurrentPreprocessor = nullptr; 716 LangOpts = nullptr; 717 } 718 } 719 720 void VerifyDiagnosticConsumer::HandleDiagnostic( 721 DiagnosticsEngine::Level DiagLevel, const Diagnostic &Info) { 722 if (Info.hasSourceManager()) { 723 // If this diagnostic is for a different source manager, ignore it. 724 if (SrcManager && &Info.getSourceManager() != SrcManager) 725 return; 726 727 setSourceManager(Info.getSourceManager()); 728 } 729 730 #ifndef NDEBUG 731 // Debug build tracks unparsed files for possible 732 // unparsed expected-* directives. 733 if (SrcManager) { 734 SourceLocation Loc = Info.getLocation(); 735 if (Loc.isValid()) { 736 ParsedStatus PS = IsUnparsed; 737 738 Loc = SrcManager->getExpansionLoc(Loc); 739 FileID FID = SrcManager->getFileID(Loc); 740 741 const FileEntry *FE = SrcManager->getFileEntryForID(FID); 742 if (FE && CurrentPreprocessor && SrcManager->isLoadedFileID(FID)) { 743 // If the file is a modules header file it shall not be parsed 744 // for expected-* directives. 745 HeaderSearch &HS = CurrentPreprocessor->getHeaderSearchInfo(); 746 if (HS.findModuleForHeader(FE)) 747 PS = IsUnparsedNoDirectives; 748 } 749 750 UpdateParsedFileStatus(*SrcManager, FID, PS); 751 } 752 } 753 #endif 754 755 // Send the diagnostic to the buffer, we will check it once we reach the end 756 // of the source file (or are destructed). 757 Buffer->HandleDiagnostic(DiagLevel, Info); 758 } 759 760 /// HandleComment - Hook into the preprocessor and extract comments containing 761 /// expected errors and warnings. 762 bool VerifyDiagnosticConsumer::HandleComment(Preprocessor &PP, 763 SourceRange Comment) { 764 SourceManager &SM = PP.getSourceManager(); 765 766 // If this comment is for a different source manager, ignore it. 767 if (SrcManager && &SM != SrcManager) 768 return false; 769 770 SourceLocation CommentBegin = Comment.getBegin(); 771 772 const char *CommentRaw = SM.getCharacterData(CommentBegin); 773 StringRef C(CommentRaw, SM.getCharacterData(Comment.getEnd()) - CommentRaw); 774 775 if (C.empty()) 776 return false; 777 778 // Fold any "\<EOL>" sequences 779 size_t loc = C.find('\\'); 780 if (loc == StringRef::npos) { 781 ParseDirective(C, &ED, SM, &PP, CommentBegin, Status, *Markers); 782 return false; 783 } 784 785 std::string C2; 786 C2.reserve(C.size()); 787 788 for (size_t last = 0;; loc = C.find('\\', last)) { 789 if (loc == StringRef::npos || loc == C.size()) { 790 C2 += C.substr(last); 791 break; 792 } 793 C2 += C.substr(last, loc-last); 794 last = loc + 1; 795 796 if (C[last] == '\n' || C[last] == '\r') { 797 ++last; 798 799 // Escape \r\n or \n\r, but not \n\n. 800 if (last < C.size()) 801 if (C[last] == '\n' || C[last] == '\r') 802 if (C[last] != C[last-1]) 803 ++last; 804 } else { 805 // This was just a normal backslash. 806 C2 += '\\'; 807 } 808 } 809 810 if (!C2.empty()) 811 ParseDirective(C2, &ED, SM, &PP, CommentBegin, Status, *Markers); 812 return false; 813 } 814 815 #ifndef NDEBUG 816 /// Lex the specified source file to determine whether it contains 817 /// any expected-* directives. As a Lexer is used rather than a full-blown 818 /// Preprocessor, directives inside skipped #if blocks will still be found. 819 /// 820 /// \return true if any directives were found. 821 static bool findDirectives(SourceManager &SM, FileID FID, 822 const LangOptions &LangOpts) { 823 // Create a raw lexer to pull all the comments out of FID. 824 if (FID.isInvalid()) 825 return false; 826 827 // Create a lexer to lex all the tokens of the main file in raw mode. 828 llvm::MemoryBufferRef FromFile = SM.getBufferOrFake(FID); 829 Lexer RawLex(FID, FromFile, SM, LangOpts); 830 831 // Return comments as tokens, this is how we find expected diagnostics. 832 RawLex.SetCommentRetentionState(true); 833 834 Token Tok; 835 Tok.setKind(tok::comment); 836 VerifyDiagnosticConsumer::DirectiveStatus Status = 837 VerifyDiagnosticConsumer::HasNoDirectives; 838 while (Tok.isNot(tok::eof)) { 839 RawLex.LexFromRawLexer(Tok); 840 if (!Tok.is(tok::comment)) continue; 841 842 std::string Comment = RawLex.getSpelling(Tok, SM, LangOpts); 843 if (Comment.empty()) continue; 844 845 // We don't care about tracking markers for this phase. 846 VerifyDiagnosticConsumer::MarkerTracker Markers(SM.getDiagnostics()); 847 848 // Find first directive. 849 if (ParseDirective(Comment, nullptr, SM, nullptr, Tok.getLocation(), 850 Status, Markers)) 851 return true; 852 } 853 return false; 854 } 855 #endif // !NDEBUG 856 857 /// Takes a list of diagnostics that have been generated but not matched 858 /// by an expected-* directive and produces a diagnostic to the user from this. 859 static unsigned PrintUnexpected(DiagnosticsEngine &Diags, SourceManager *SourceMgr, 860 const_diag_iterator diag_begin, 861 const_diag_iterator diag_end, 862 const char *Kind) { 863 if (diag_begin == diag_end) return 0; 864 865 SmallString<256> Fmt; 866 llvm::raw_svector_ostream OS(Fmt); 867 for (const_diag_iterator I = diag_begin, E = diag_end; I != E; ++I) { 868 if (I->first.isInvalid() || !SourceMgr) 869 OS << "\n (frontend)"; 870 else { 871 OS << "\n "; 872 if (const FileEntry *File = SourceMgr->getFileEntryForID( 873 SourceMgr->getFileID(I->first))) 874 OS << " File " << File->getName(); 875 OS << " Line " << SourceMgr->getPresumedLineNumber(I->first); 876 } 877 OS << ": " << I->second; 878 } 879 880 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit() 881 << Kind << /*Unexpected=*/true << OS.str(); 882 return std::distance(diag_begin, diag_end); 883 } 884 885 /// Takes a list of diagnostics that were expected to have been generated 886 /// but were not and produces a diagnostic to the user from this. 887 static unsigned PrintExpected(DiagnosticsEngine &Diags, 888 SourceManager &SourceMgr, 889 std::vector<Directive *> &DL, const char *Kind) { 890 if (DL.empty()) 891 return 0; 892 893 SmallString<256> Fmt; 894 llvm::raw_svector_ostream OS(Fmt); 895 for (const auto *D : DL) { 896 if (D->DiagnosticLoc.isInvalid() || D->MatchAnyFileAndLine) 897 OS << "\n File *"; 898 else 899 OS << "\n File " << SourceMgr.getFilename(D->DiagnosticLoc); 900 if (D->MatchAnyLine) 901 OS << " Line *"; 902 else 903 OS << " Line " << SourceMgr.getPresumedLineNumber(D->DiagnosticLoc); 904 if (D->DirectiveLoc != D->DiagnosticLoc) 905 OS << " (directive at " 906 << SourceMgr.getFilename(D->DirectiveLoc) << ':' 907 << SourceMgr.getPresumedLineNumber(D->DirectiveLoc) << ')'; 908 OS << ": " << D->Text; 909 } 910 911 Diags.Report(diag::err_verify_inconsistent_diags).setForceEmit() 912 << Kind << /*Unexpected=*/false << OS.str(); 913 return DL.size(); 914 } 915 916 /// Determine whether two source locations come from the same file. 917 static bool IsFromSameFile(SourceManager &SM, SourceLocation DirectiveLoc, 918 SourceLocation DiagnosticLoc) { 919 while (DiagnosticLoc.isMacroID()) 920 DiagnosticLoc = SM.getImmediateMacroCallerLoc(DiagnosticLoc); 921 922 if (SM.isWrittenInSameFile(DirectiveLoc, DiagnosticLoc)) 923 return true; 924 925 const FileEntry *DiagFile = SM.getFileEntryForID(SM.getFileID(DiagnosticLoc)); 926 if (!DiagFile && SM.isWrittenInMainFile(DirectiveLoc)) 927 return true; 928 929 return (DiagFile == SM.getFileEntryForID(SM.getFileID(DirectiveLoc))); 930 } 931 932 /// CheckLists - Compare expected to seen diagnostic lists and return the 933 /// the difference between them. 934 static unsigned CheckLists(DiagnosticsEngine &Diags, SourceManager &SourceMgr, 935 const char *Label, 936 DirectiveList &Left, 937 const_diag_iterator d2_begin, 938 const_diag_iterator d2_end, 939 bool IgnoreUnexpected) { 940 std::vector<Directive *> LeftOnly; 941 DiagList Right(d2_begin, d2_end); 942 943 for (auto &Owner : Left) { 944 Directive &D = *Owner; 945 unsigned LineNo1 = SourceMgr.getPresumedLineNumber(D.DiagnosticLoc); 946 947 for (unsigned i = 0; i < D.Max; ++i) { 948 DiagList::iterator II, IE; 949 for (II = Right.begin(), IE = Right.end(); II != IE; ++II) { 950 if (!D.MatchAnyLine) { 951 unsigned LineNo2 = SourceMgr.getPresumedLineNumber(II->first); 952 if (LineNo1 != LineNo2) 953 continue; 954 } 955 956 if (!D.DiagnosticLoc.isInvalid() && !D.MatchAnyFileAndLine && 957 !IsFromSameFile(SourceMgr, D.DiagnosticLoc, II->first)) 958 continue; 959 960 const std::string &RightText = II->second; 961 if (D.match(RightText)) 962 break; 963 } 964 if (II == IE) { 965 // Not found. 966 if (i >= D.Min) break; 967 LeftOnly.push_back(&D); 968 } else { 969 // Found. The same cannot be found twice. 970 Right.erase(II); 971 } 972 } 973 } 974 // Now all that's left in Right are those that were not matched. 975 unsigned num = PrintExpected(Diags, SourceMgr, LeftOnly, Label); 976 if (!IgnoreUnexpected) 977 num += PrintUnexpected(Diags, &SourceMgr, Right.begin(), Right.end(), Label); 978 return num; 979 } 980 981 /// CheckResults - This compares the expected results to those that 982 /// were actually reported. It emits any discrepencies. Return "true" if there 983 /// were problems. Return "false" otherwise. 984 static unsigned CheckResults(DiagnosticsEngine &Diags, SourceManager &SourceMgr, 985 const TextDiagnosticBuffer &Buffer, 986 ExpectedData &ED) { 987 // We want to capture the delta between what was expected and what was 988 // seen. 989 // 990 // Expected \ Seen - set expected but not seen 991 // Seen \ Expected - set seen but not expected 992 unsigned NumProblems = 0; 993 994 const DiagnosticLevelMask DiagMask = 995 Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected(); 996 997 // See if there are error mismatches. 998 NumProblems += CheckLists(Diags, SourceMgr, "error", ED.Errors, 999 Buffer.err_begin(), Buffer.err_end(), 1000 bool(DiagnosticLevelMask::Error & DiagMask)); 1001 1002 // See if there are warning mismatches. 1003 NumProblems += CheckLists(Diags, SourceMgr, "warning", ED.Warnings, 1004 Buffer.warn_begin(), Buffer.warn_end(), 1005 bool(DiagnosticLevelMask::Warning & DiagMask)); 1006 1007 // See if there are remark mismatches. 1008 NumProblems += CheckLists(Diags, SourceMgr, "remark", ED.Remarks, 1009 Buffer.remark_begin(), Buffer.remark_end(), 1010 bool(DiagnosticLevelMask::Remark & DiagMask)); 1011 1012 // See if there are note mismatches. 1013 NumProblems += CheckLists(Diags, SourceMgr, "note", ED.Notes, 1014 Buffer.note_begin(), Buffer.note_end(), 1015 bool(DiagnosticLevelMask::Note & DiagMask)); 1016 1017 return NumProblems; 1018 } 1019 1020 void VerifyDiagnosticConsumer::UpdateParsedFileStatus(SourceManager &SM, 1021 FileID FID, 1022 ParsedStatus PS) { 1023 // Check SourceManager hasn't changed. 1024 setSourceManager(SM); 1025 1026 #ifndef NDEBUG 1027 if (FID.isInvalid()) 1028 return; 1029 1030 const FileEntry *FE = SM.getFileEntryForID(FID); 1031 1032 if (PS == IsParsed) { 1033 // Move the FileID from the unparsed set to the parsed set. 1034 UnparsedFiles.erase(FID); 1035 ParsedFiles.insert(std::make_pair(FID, FE)); 1036 } else if (!ParsedFiles.count(FID) && !UnparsedFiles.count(FID)) { 1037 // Add the FileID to the unparsed set if we haven't seen it before. 1038 1039 // Check for directives. 1040 bool FoundDirectives; 1041 if (PS == IsUnparsedNoDirectives) 1042 FoundDirectives = false; 1043 else 1044 FoundDirectives = !LangOpts || findDirectives(SM, FID, *LangOpts); 1045 1046 // Add the FileID to the unparsed set. 1047 UnparsedFiles.insert(std::make_pair(FID, 1048 UnparsedFileStatus(FE, FoundDirectives))); 1049 } 1050 #endif 1051 } 1052 1053 void VerifyDiagnosticConsumer::CheckDiagnostics() { 1054 // Ensure any diagnostics go to the primary client. 1055 DiagnosticConsumer *CurClient = Diags.getClient(); 1056 std::unique_ptr<DiagnosticConsumer> Owner = Diags.takeClient(); 1057 Diags.setClient(PrimaryClient, false); 1058 1059 #ifndef NDEBUG 1060 // In a debug build, scan through any files that may have been missed 1061 // during parsing and issue a fatal error if directives are contained 1062 // within these files. If a fatal error occurs, this suggests that 1063 // this file is being parsed separately from the main file, in which 1064 // case consider moving the directives to the correct place, if this 1065 // is applicable. 1066 if (!UnparsedFiles.empty()) { 1067 // Generate a cache of parsed FileEntry pointers for alias lookups. 1068 llvm::SmallPtrSet<const FileEntry *, 8> ParsedFileCache; 1069 for (const auto &I : ParsedFiles) 1070 if (const FileEntry *FE = I.second) 1071 ParsedFileCache.insert(FE); 1072 1073 // Iterate through list of unparsed files. 1074 for (const auto &I : UnparsedFiles) { 1075 const UnparsedFileStatus &Status = I.second; 1076 const FileEntry *FE = Status.getFile(); 1077 1078 // Skip files that have been parsed via an alias. 1079 if (FE && ParsedFileCache.count(FE)) 1080 continue; 1081 1082 // Report a fatal error if this file contained directives. 1083 if (Status.foundDirectives()) { 1084 llvm::report_fatal_error(Twine("-verify directives found after rather" 1085 " than during normal parsing of ", 1086 StringRef(FE ? FE->getName() : "(unknown)"))); 1087 } 1088 } 1089 1090 // UnparsedFiles has been processed now, so clear it. 1091 UnparsedFiles.clear(); 1092 } 1093 #endif // !NDEBUG 1094 1095 if (SrcManager) { 1096 // Produce an error if no expected-* directives could be found in the 1097 // source file(s) processed. 1098 if (Status == HasNoDirectives) { 1099 Diags.Report(diag::err_verify_no_directives).setForceEmit(); 1100 ++NumErrors; 1101 Status = HasNoDirectivesReported; 1102 } 1103 1104 // Check that the expected diagnostics occurred. 1105 NumErrors += CheckResults(Diags, *SrcManager, *Buffer, ED); 1106 } else { 1107 const DiagnosticLevelMask DiagMask = 1108 ~Diags.getDiagnosticOptions().getVerifyIgnoreUnexpected(); 1109 if (bool(DiagnosticLevelMask::Error & DiagMask)) 1110 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->err_begin(), 1111 Buffer->err_end(), "error"); 1112 if (bool(DiagnosticLevelMask::Warning & DiagMask)) 1113 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->warn_begin(), 1114 Buffer->warn_end(), "warn"); 1115 if (bool(DiagnosticLevelMask::Remark & DiagMask)) 1116 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->remark_begin(), 1117 Buffer->remark_end(), "remark"); 1118 if (bool(DiagnosticLevelMask::Note & DiagMask)) 1119 NumErrors += PrintUnexpected(Diags, nullptr, Buffer->note_begin(), 1120 Buffer->note_end(), "note"); 1121 } 1122 1123 Diags.setClient(CurClient, Owner.release() != nullptr); 1124 1125 // Reset the buffer, we have processed all the diagnostics in it. 1126 Buffer.reset(new TextDiagnosticBuffer()); 1127 ED.Reset(); 1128 } 1129 1130 std::unique_ptr<Directive> Directive::create(bool RegexKind, 1131 SourceLocation DirectiveLoc, 1132 SourceLocation DiagnosticLoc, 1133 bool MatchAnyFileAndLine, 1134 bool MatchAnyLine, StringRef Text, 1135 unsigned Min, unsigned Max) { 1136 if (!RegexKind) 1137 return std::make_unique<StandardDirective>(DirectiveLoc, DiagnosticLoc, 1138 MatchAnyFileAndLine, 1139 MatchAnyLine, Text, Min, Max); 1140 1141 // Parse the directive into a regular expression. 1142 std::string RegexStr; 1143 StringRef S = Text; 1144 while (!S.empty()) { 1145 if (S.startswith("{{")) { 1146 S = S.drop_front(2); 1147 size_t RegexMatchLength = S.find("}}"); 1148 assert(RegexMatchLength != StringRef::npos); 1149 // Append the regex, enclosed in parentheses. 1150 RegexStr += "("; 1151 RegexStr.append(S.data(), RegexMatchLength); 1152 RegexStr += ")"; 1153 S = S.drop_front(RegexMatchLength + 2); 1154 } else { 1155 size_t VerbatimMatchLength = S.find("{{"); 1156 if (VerbatimMatchLength == StringRef::npos) 1157 VerbatimMatchLength = S.size(); 1158 // Escape and append the fixed string. 1159 RegexStr += llvm::Regex::escape(S.substr(0, VerbatimMatchLength)); 1160 S = S.drop_front(VerbatimMatchLength); 1161 } 1162 } 1163 1164 return std::make_unique<RegexDirective>(DirectiveLoc, DiagnosticLoc, 1165 MatchAnyFileAndLine, MatchAnyLine, 1166 Text, Min, Max, RegexStr); 1167 } 1168