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