https://github.com/NaithamShravani created https://github.com/llvm/llvm-project/pull/242662
## Summary The NOLINT directive handler currently searches raw source buffers for `NOLINT` directives without checking whether they occur inside actual comment tokens. As a result, occurrences of strings such as `"NOLINT"`, `"NOLINTNEXTLINE"`, and `"NOLINTBEGIN"` inside ordinary and raw string literals can unintentionally suppress Clang-Tidy diagnostics. This change uses Clang's raw lexer to identify actual comment tokens and parses NOLINT directives only within those comments. ## Changes - Use Clang's raw lexer to identify comment tokens before parsing NOLINT directives. - Prevent suppression directives inside ordinary and raw string literals from being recognized. - Cache parsed directives per file. - Parse NOLINT block directives lazily when block suppression is enabled. - Correct forwarding of the `EnableNoLintBlocks` setting. - Add regression tests for string literals, raw strings, block comments, and CRLF input. ## Testing - 22/22 focused NOLINT lit tests passed. - 333/333 Clang-Tidy unit tests passed. - Formatting checks passed. - The broader infrastructure lit suite had one unrelated Windows failure: `cxx20-modules.cppm` could not execute `%clang` because the configured compiler path contained a space (`C:\Program Files\...`). ## Notes This change addresses suppression-directive parsing correctness. It does not claim a memory-safety vulnerability in Clang-Tidy. >From affd0e4669266f3cc1362256738e1a8215e1e15b Mon Sep 17 00:00:00 2001 From: NaithamShravani <[email protected]> Date: Sat, 14 Nov 2026 21:59:53 +0530 Subject: [PATCH] [clang-tidy] Ignore NOLINT directives in non-comment tokens --- .../ClangTidyDiagnosticConsumer.cpp | 5 +- .../clang-tidy/NoLintDirectiveHandler.cpp | 228 ++++++++++-------- .../clang-tidy/NoLintDirectiveHandler.h | 7 +- clang-tools-extra/test/.gitattributes | 1 + .../clang-tidy/infrastructure/nolint-crlf.cpp | 23 ++ .../test/clang-tidy/infrastructure/nolint.cpp | 53 +++- .../ClangTidyDiagnosticConsumerTest.cpp | 49 ++++ 7 files changed, 266 insertions(+), 100 deletions(-) create mode 100644 clang-tools-extra/test/clang-tidy/infrastructure/nolint-crlf.cpp diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp index cd163300ec896f..c2dbd9e8ee28a3 100644 --- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp +++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp @@ -218,7 +218,8 @@ bool ClangTidyContext::shouldSuppressDiagnostic( bool EnableNoLintBlocks) { const std::string CheckName = getCheckName(Info.getID()); return NoLintHandler.shouldSuppress(DiagLevel, Info, CheckName, NoLintErrors, - AllowIO, EnableNoLintBlocks); + AllowIO, EnableNoLintBlocks, + &getLangOpts()); } void ClangTidyContext::setSourceManager(SourceManager *SourceMgr) { @@ -401,7 +402,7 @@ void ClangTidyDiagnosticConsumer::HandleDiagnostic( SmallVector<tooling::Diagnostic, 1> SuppressionErrors; if (Context.shouldSuppressDiagnostic(DiagLevel, Info, SuppressionErrors, - EnableNolintBlocks)) { + /*AllowIO=*/true, EnableNolintBlocks)) { ++Context.Stats.ErrorsIgnoredNOLINT; // Ignored a warning, should ignore related notes as well LastErrorWasIgnored = true; diff --git a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp index f67d19be4525cc..b5d34c523ed092 100644 --- a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp +++ b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.cpp @@ -15,13 +15,17 @@ #include "NoLintDirectiveHandler.h" #include "GlobList.h" #include "clang/Basic/LLVM.h" +#include "clang/Basic/LangOptions.h" +#include "clang/Basic/LangStandard.h" #include "clang/Basic/SourceLocation.h" #include "clang/Basic/SourceManager.h" +#include "clang/Lex/Lexer.h" #include "clang/Tooling/Core/Diagnostic.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSwitch.h" +#include "llvm/TargetParser/Triple.h" #include <cassert> #include <cstddef> #include <memory> @@ -110,43 +114,74 @@ class NoLintToken { } // namespace -// Consume the entire buffer and return all `NoLintToken`s that were found. -static SmallVector<NoLintToken> getNoLints(StringRef Buffer) { +// Parse NOLINT directives from the contents of a single comment. `Offset` is +// the comment's offset in the original source buffer. +static void parseNoLintsFromComment(StringRef Comment, size_t Offset, + SmallVectorImpl<NoLintToken> &NoLints) { static constexpr StringRef NOLINT = "NOLINT"; - SmallVector<NoLintToken> NoLints; - size_t Pos = 0; - while (Pos < Buffer.size()) { - // Find NOLINT: - const size_t NoLintPos = Buffer.find(NOLINT, Pos); + while (Pos < Comment.size()) { + const size_t NoLintPos = Comment.find(NOLINT, Pos); if (NoLintPos == StringRef::npos) - break; // Buffer exhausted + break; - // Read [A-Z] characters immediately after "NOLINT", e.g. the "NEXTLINE" in - // "NOLINTNEXTLINE". Pos = NoLintPos + NOLINT.size(); - while (Pos < Buffer.size() && llvm::isAlpha(Buffer[Pos])) + while (Pos < Comment.size() && llvm::isAlpha(Comment[Pos])) ++Pos; - // Is this a recognized NOLINT type? - const std::optional<NoLintType> NoLintType = - strToNoLintType(Buffer.slice(NoLintPos, Pos)); - if (!NoLintType) + const std::optional<NoLintType> Type = + strToNoLintType(Comment.slice(NoLintPos, Pos)); + if (!Type) continue; - // Get checks, if specified. std::optional<StringRef> Checks; - if (Pos < Buffer.size() && Buffer[Pos] == '(') { - const size_t ClosingBracket = Buffer.find_first_of("\n)", ++Pos); - if (ClosingBracket != StringRef::npos && Buffer[ClosingBracket] == ')') { - Checks = Buffer.slice(Pos, ClosingBracket); + if (Pos < Comment.size() && Comment[Pos] == '(') { + const size_t ClosingBracket = Comment.find_first_of("\n)", ++Pos); + if (ClosingBracket != StringRef::npos && Comment[ClosingBracket] == ')') { + Checks = Comment.slice(Pos, ClosingBracket); Pos = ClosingBracket + 1; } } + NoLints.emplace_back(*Type, Offset + NoLintPos, Checks); + } +} - NoLints.emplace_back(*NoLintType, NoLintPos, Checks); +// Consume the buffer using Clang's raw lexer and return all `NoLintToken`s +// found within actual comments. String literals, character literals, and +// other non-comment tokens are ignored so they cannot become suppression +// directives. +static SmallVector<NoLintToken> getNoLints(StringRef Buffer, + const LangOptions *LangOpts) { + SmallVector<NoLintToken> NoLints; + + LangOptions EffectiveLangOpts; + if (LangOpts) { + EffectiveLangOpts = *LangOpts; + } else { + std::vector<std::string> Includes; + LangOptions::setLangDefaults(EffectiveLangOpts, Language::CXX, + llvm::Triple(), Includes, + LangStandard::lang_cxx11); } + // Ensure line comments are always recognized even in strict C89 modes. + EffectiveLangOpts.LineComment = true; + + Lexer Lex(SourceLocation(), EffectiveLangOpts, Buffer.begin(), Buffer.begin(), + Buffer.end()); + Lex.SetCommentRetentionState(true); + Token Tok; + while (true) { + const bool Done = Lex.LexFromRawLexer(Tok); + if (Tok.is(tok::comment)) { + const size_t CommentOffset = + Lex.getCurrentBufferOffset() - Tok.getLength(); + const StringRef Comment = Buffer.substr(CommentOffset, Tok.getLength()); + parseNoLintsFromComment(Comment, CommentOffset, NoLints); + } + if (Done || Tok.is(tok::eof)) + break; + } return NoLints; } @@ -201,26 +236,30 @@ static tooling::Diagnostic makeNoLintError(const SourceManager &SrcMgr, // `NoLintBlockToken`s. If any BEGINs or ENDs are left over, a diagnostic is // written to `NoLintErrors`. static SmallVector<NoLintBlockToken> -formNoLintBlocks(SmallVector<NoLintToken> NoLints, const SourceManager &SrcMgr, +formNoLintBlocks(ArrayRef<NoLintToken> NoLints, const SourceManager &SrcMgr, FileID File, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors) { SmallVector<NoLintBlockToken> CompletedBlocks; - SmallVector<NoLintToken> Stack; + SmallVector<const NoLintToken *> Stack; // Nested blocks must be fully contained within their parent block. What this // means is that when you have a series of nested BEGIN tokens, the END tokens // shall appear in the reverse order, starting with the closing of the // inner-most block first, then the next level up, and so on. This is // essentially a last-in-first-out/stack system. - for (NoLintToken &NoLint : NoLints) { + for (const NoLintToken &NoLint : NoLints) { if (NoLint.Type == NoLintType::NoLintBegin) { // A new block is being started. Add it to the stack. - Stack.emplace_back(std::move(NoLint)); + Stack.push_back(&NoLint); } else if (NoLint.Type == NoLintType::NoLintEnd) { - if (!Stack.empty() && Stack.back().checks() == NoLint.checks()) { + if (!Stack.empty() && Stack.back()->checks() == NoLint.checks()) { // The previous block is being closed. Pop one element off the stack. - CompletedBlocks.emplace_back(Stack.back().Pos, NoLint.Pos, - std::move(Stack.back().ChecksGlob)); + const auto Checks = Stack.back()->checks(); + CompletedBlocks.emplace_back( + Stack.back()->Pos, NoLint.Pos, + std::make_unique<CachedGlobList>(Checks ? StringRef(*Checks) + : StringRef("*"), + /*KeepNegativeGlobs=*/false)); Stack.pop_back(); } else { // Trying to close the wrong block. @@ -229,48 +268,79 @@ formNoLintBlocks(SmallVector<NoLintToken> NoLints, const SourceManager &SrcMgr, } } - for (const NoLintToken &NoLint : Stack) - NoLintErrors.emplace_back(makeNoLintError(SrcMgr, File, NoLint)); + for (const NoLintToken *NoLint : Stack) + NoLintErrors.emplace_back(makeNoLintError(SrcMgr, File, *NoLint)); return CompletedBlocks; } -//===----------------------------------------------------------------------===// -// NoLintDirectiveHandler::Impl -//===----------------------------------------------------------------------===// +// Whether the line has a NOLINT of type = `Type` that can suppress the +// diagnostic `DiagName`. Directives are stored in increasing Pos order, so we +// can binary search for the line's start position. +static bool lineHasNoLint(ArrayRef<NoLintToken> NoLints, + std::pair<size_t, size_t> LineStartAndEnd, + NoLintType Type, StringRef DiagName) { + auto It = llvm::lower_bound( + NoLints, LineStartAndEnd.first, + [](const NoLintToken &Token, size_t Pos) { return Token.Pos < Pos; }); + for (; It != NoLints.end() && It->Pos < LineStartAndEnd.second; ++It) + if (It->Type == Type && It->suppresses(DiagName)) + return true; + return false; +} + +// Whether the provided diagnostic is located within and is suppressible by a +// block of NOLINT(BEGIN/END) comments. +static bool withinNoLintBlock(ArrayRef<NoLintBlockToken> NoLintBlocks, + size_t DiagPos, StringRef DiagName) { + return llvm::any_of(NoLintBlocks, [&](const NoLintBlockToken &NoLintBlock) { + return NoLintBlock.suppresses(DiagPos, DiagName); + }); +} + +// Get the file contents as a string. +static std::optional<StringRef> getBuffer(const SourceManager &SrcMgr, + FileID File, bool AllowIO) { + return AllowIO ? SrcMgr.getBufferDataOrNone(File) + : SrcMgr.getBufferDataIfLoaded(File); +} class NoLintDirectiveHandler::Impl { public: bool shouldSuppress(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Diag, StringRef DiagName, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, - bool AllowIO, bool EnableNoLintBlocks); + bool AllowIO, bool EnableNoLintBlocks, + const LangOptions *LangOpts); + + struct CachedFileDirectives { + SmallVector<NoLintToken> NoLints; + std::optional<SmallVector<NoLintBlockToken>> Blocks; + }; private: bool diagHasNoLintInMacro(const Diagnostic &Diag, StringRef DiagName, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, - bool AllowIO, bool EnableNoLintBlocks); + bool AllowIO, bool EnableNoLintBlocks, + const LangOptions *LangOpts); bool diagHasNoLint(StringRef DiagName, SourceLocation DiagLoc, const SourceManager &SrcMgr, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, - bool AllowIO, bool EnableNoLintBlocks); + bool AllowIO, bool EnableNoLintBlocks, + const LangOptions *LangOpts); - void generateCache(const SourceManager &SrcMgr, StringRef FileName, - FileID File, StringRef Buffer, - SmallVectorImpl<tooling::Diagnostic> &NoLintErrors); - - llvm::StringMap<SmallVector<NoLintBlockToken>> Cache; + llvm::StringMap<CachedFileDirectives> Cache; }; bool NoLintDirectiveHandler::Impl::shouldSuppress( DiagnosticsEngine::Level DiagLevel, const Diagnostic &Diag, StringRef DiagName, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, - bool AllowIO, bool EnableNoLintBlocks) { + bool AllowIO, bool EnableNoLintBlocks, const LangOptions *LangOpts) { if (DiagLevel >= DiagnosticsEngine::Error) return false; return diagHasNoLintInMacro(Diag, DiagName, NoLintErrors, AllowIO, - EnableNoLintBlocks); + EnableNoLintBlocks, LangOpts); } // Look at the macro's spelling location for a NOLINT. If none is found, keep @@ -278,14 +348,14 @@ bool NoLintDirectiveHandler::Impl::shouldSuppress( bool NoLintDirectiveHandler::Impl::diagHasNoLintInMacro( const Diagnostic &Diag, StringRef DiagName, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, bool AllowIO, - bool EnableNoLintBlocks) { + bool EnableNoLintBlocks, const LangOptions *LangOpts) { SourceLocation DiagLoc = Diag.getLocation(); if (DiagLoc.isInvalid()) return false; const SourceManager &SrcMgr = Diag.getSourceManager(); while (true) { if (diagHasNoLint(DiagName, DiagLoc, SrcMgr, NoLintErrors, AllowIO, - EnableNoLintBlocks)) + EnableNoLintBlocks, LangOpts)) return true; if (!DiagLoc.isMacroID()) return false; @@ -303,37 +373,6 @@ static std::pair<size_t, size_t> getLineStartAndEnd(StringRef Buffer, return {StartPos, EndPos}; } -// Whether the line has a NOLINT of type = `Type` that can suppress the -// diagnostic `DiagName`. -static bool lineHasNoLint(StringRef Buffer, - std::pair<size_t, size_t> LineStartAndEnd, - NoLintType Type, StringRef DiagName) { - // Get all NOLINTs on the line. - Buffer = Buffer.slice(LineStartAndEnd.first, LineStartAndEnd.second); - SmallVector<NoLintToken> NoLints = getNoLints(Buffer); - - // Do any of these NOLINTs match the desired type and diag name? - return llvm::any_of(NoLints, [&](const NoLintToken &NoLint) { - return NoLint.Type == Type && NoLint.suppresses(DiagName); - }); -} - -// Whether the provided diagnostic is located within and is suppressible by a -// block of NOLINT(BEGIN/END) comments. -static bool withinNoLintBlock(ArrayRef<NoLintBlockToken> NoLintBlocks, - size_t DiagPos, StringRef DiagName) { - return llvm::any_of(NoLintBlocks, [&](const NoLintBlockToken &NoLintBlock) { - return NoLintBlock.suppresses(DiagPos, DiagName); - }); -} - -// Get the file contents as a string. -static std::optional<StringRef> getBuffer(const SourceManager &SrcMgr, - FileID File, bool AllowIO) { - return AllowIO ? SrcMgr.getBufferDataOrNone(File) - : SrcMgr.getBufferDataIfLoaded(File); -} - // We will check for NOLINTs and NOLINTNEXTLINEs first. Checking for these is // not so expensive (just need to parse the current and previous lines). Only if // that fails do we look for NOLINT(BEGIN/END) blocks (which requires reading @@ -341,7 +380,7 @@ static std::optional<StringRef> getBuffer(const SourceManager &SrcMgr, bool NoLintDirectiveHandler::Impl::diagHasNoLint( StringRef DiagName, SourceLocation DiagLoc, const SourceManager &SrcMgr, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, bool AllowIO, - bool EnableNoLintBlocks) { + bool EnableNoLintBlocks, const LangOptions *LangOpts) { // Translate the diagnostic's SourceLocation to a raw file + offset pair. const auto [File, Pos] = SrcMgr.getDecomposedSpellingLoc(DiagLoc); @@ -356,15 +395,23 @@ bool NoLintDirectiveHandler::Impl::diagHasNoLint( if (!Buffer) return false; + if (!Cache.contains(*FileName)) + Cache.try_emplace( + *FileName, + CachedFileDirectives{getNoLints(*Buffer, LangOpts), std::nullopt}); + + CachedFileDirectives &Directives = Cache[*FileName]; + // Check if there's a NOLINT on this line. const auto ThisLine = getLineStartAndEnd(*Buffer, Pos); - if (lineHasNoLint(*Buffer, ThisLine, NoLintType::NoLint, DiagName)) + if (lineHasNoLint(Directives.NoLints, ThisLine, NoLintType::NoLint, DiagName)) return true; // Check if there's a NOLINTNEXTLINE on the previous line. if (ThisLine.first > 0) { const auto PrevLine = getLineStartAndEnd(*Buffer, ThisLine.first - 1); - if (lineHasNoLint(*Buffer, PrevLine, NoLintType::NoLintNextLine, DiagName)) + if (lineHasNoLint(Directives.NoLints, PrevLine, NoLintType::NoLintNextLine, + DiagName)) return true; } @@ -372,22 +419,11 @@ bool NoLintDirectiveHandler::Impl::diagHasNoLint( if (!EnableNoLintBlocks) return false; - // Do we have cached NOLINT block locations for this file? - if (!Cache.contains(*FileName)) - // Warning: heavy operation - need to read entire file. - generateCache(SrcMgr, *FileName, File, *Buffer, NoLintErrors); - - return withinNoLintBlock(Cache[*FileName], Pos, DiagName); -} + if (!Directives.Blocks) + Directives.Blocks = + formNoLintBlocks(Directives.NoLints, SrcMgr, File, NoLintErrors); -// Find all NOLINT(BEGIN/END) blocks in a file and store in the cache. -void NoLintDirectiveHandler::Impl::generateCache( - const SourceManager &SrcMgr, StringRef FileName, FileID File, - StringRef Buffer, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors) { - // Read entire file to get all NOLINTs and match each BEGIN with its - // corresponding END, raising errors for any BEGIN or END that is unmatched. - Cache.try_emplace(FileName, formNoLintBlocks(getNoLints(Buffer), SrcMgr, File, - NoLintErrors)); + return withinNoLintBlock(*Directives.Blocks, Pos, DiagName); } //===----------------------------------------------------------------------===// @@ -402,9 +438,9 @@ NoLintDirectiveHandler::~NoLintDirectiveHandler() = default; bool NoLintDirectiveHandler::shouldSuppress( DiagnosticsEngine::Level DiagLevel, const Diagnostic &Diag, StringRef DiagName, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, - bool AllowIO, bool EnableNoLintBlocks) { + bool AllowIO, bool EnableNoLintBlocks, const LangOptions *LangOpts) { return PImpl->shouldSuppress(DiagLevel, Diag, DiagName, NoLintErrors, AllowIO, - EnableNoLintBlocks); + EnableNoLintBlocks, LangOpts); } } // namespace clang::tidy diff --git a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.h b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.h index 4aafd34b33956e..ae64ff36b04176 100644 --- a/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.h +++ b/clang-tools-extra/clang-tidy/NoLintDirectiveHandler.h @@ -21,6 +21,10 @@ namespace llvm { template <typename T> class SmallVectorImpl; } // namespace llvm +namespace clang { +class LangOptions; +} // namespace clang + namespace clang::tidy { /// This class is used to locate NOLINT comments in the file being analyzed, to @@ -35,7 +39,8 @@ class NoLintDirectiveHandler { bool shouldSuppress(DiagnosticsEngine::Level DiagLevel, const Diagnostic &Diag, StringRef DiagName, SmallVectorImpl<tooling::Diagnostic> &NoLintErrors, - bool AllowIO, bool EnableNoLintBlocks); + bool AllowIO, bool EnableNoLintBlocks, + const LangOptions *LangOpts = nullptr); private: class Impl; diff --git a/clang-tools-extra/test/.gitattributes b/clang-tools-extra/test/.gitattributes index 3c39030a95eabc..7d3223d26ab26a 100644 --- a/clang-tools-extra/test/.gitattributes +++ b/clang-tools-extra/test/.gitattributes @@ -15,3 +15,4 @@ clang-apply-replacements/Inputs/crlf/crlf.cpp -text clang-apply-replacements/Inputs/crlf/crlf.cpp.expected -text clang-tidy/checkers/modernize/Inputs/macro-to-enum/crlf.cpp -text clang-tidy/checkers/modernize/Inputs/macro-to-enum/crlf.cpp.expected -text +clang-tidy/infrastructure/nolint-crlf.cpp -text diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/nolint-crlf.cpp b/clang-tools-extra/test/clang-tidy/infrastructure/nolint-crlf.cpp new file mode 100644 index 00000000000000..c82de6671ab20b --- /dev/null +++ b/clang-tools-extra/test/clang-tidy/infrastructure/nolint-crlf.cpp @@ -0,0 +1,23 @@ +// RUN: %check_clang_tidy %s google-explicit-constructor %t + +class A { A(int i); }; +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit + +class B { B(int i); }; // NOLINT + +// NOLINTNEXTLINE +class C { C(int i); }; + +// NOLINTBEGIN +class D { D(int i); }; +// NOLINTEND + +const char *S = "NOLINT"; +class E { E(int i); }; +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit + +const char *SNL = "NOLINTNEXTLINE"; +class F { F(int i); }; +// CHECK-MESSAGES: :[[@LINE-1]]:11: warning: single-argument constructors must be marked explicit + +// CHECK-MESSAGES: Suppressed 3 warnings (3 NOLINT) diff --git a/clang-tools-extra/test/clang-tidy/infrastructure/nolint.cpp b/clang-tools-extra/test/clang-tidy/infrastructure/nolint.cpp index fd3fee6b9c56e1..4efad5d5f1139e 100644 --- a/clang-tools-extra/test/clang-tidy/infrastructure/nolint.cpp +++ b/clang-tools-extra/test/clang-tidy/infrastructure/nolint.cpp @@ -133,4 +133,55 @@ int array2[10]; // NOLINT(cppcoreguidelines-avoid-c-arrays) int array3[10]; // NOLINT(cppcoreguidelines-avoid-c-arrays,modernize-avoid-c-arrays) int array4[10]; // NOLINT(*-avoid-c-arrays) -// CHECK-MESSAGES: Suppressed 36 warnings (36 NOLINT) +// String literals must not act as NOLINT directives: +class StrLit1 { StrLit1(int x); }; const char *SL1 = "NOLINT"; +// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: single-argument constructors must be marked explicit + +class StrLit2 { StrLit2(int x); }; const char *SL2 = "NOLINT(google-explicit-constructor)"; +// CHECK-MESSAGES: :[[@LINE-1]]:17: warning: single-argument constructors must be marked explicit + +// Raw string literals must not act as NOLINT directives: +class RawStrLit1 { RawStrLit1(int x); }; const char *RSL1 = R"(NOLINT)"; +// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: single-argument constructors must be marked explicit + +class RawStrLit2 { RawStrLit2(int x); }; const char *RSL2 = R"(NOLINT(google-explicit-constructor))"; +// CHECK-MESSAGES: :[[@LINE-1]]:20: warning: single-argument constructors must be marked explicit + +// NOLINTNEXTLINE in string literals must not suppress subsequent lines: +const char *SLNL = "NOLINTNEXTLINE"; +class StrLitNextLine { StrLitNextLine(int x); }; +// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: single-argument constructors must be marked explicit + +const char *RSLNL = R"(NOLINTNEXTLINE(google-explicit-constructor))"; +class RawStrLitNextLine { RawStrLitNextLine(int x); }; +// CHECK-MESSAGES: :[[@LINE-1]]:27: warning: single-argument constructors must be marked explicit + +// NOLINTBEGIN/NOLINTEND inside string literals must not suppress: +const char *SLB = "NOLINTBEGIN"; +class StrLitBlock { StrLitBlock(int x); }; +// CHECK-MESSAGES: :[[@LINE-1]]:21: warning: single-argument constructors must be marked explicit +const char *SLE = "NOLINTEND"; + +const char *RSLB = R"(NOLINTBEGIN(google-explicit-constructor))"; +class RawStrLitBlock { RawStrLitBlock(int x); }; +// CHECK-MESSAGES: :[[@LINE-1]]:24: warning: single-argument constructors must be marked explicit +const char *RSLE = R"(NOLINTEND(google-explicit-constructor))"; + +// Genuine block comments must continue to suppress: +class BlockNolint { BlockNolint(int x); }; /* NOLINT */ +/* NOLINT(google-explicit-constructor) */ class BlockNolint2 { BlockNolint2(int x); }; + +// Multiline block comments with directives: +/* + NOLINTNEXTLINE(google-explicit-constructor) */ +class MultilineBlockNextLine { MultilineBlockNextLine(int x); }; + +/* + NOLINTBEGIN(google-explicit-constructor) +*/ +class BlockBeginEnd { BlockBeginEnd(int x); }; +/* + NOLINTEND(google-explicit-constructor) +*/ + +// CHECK-MESSAGES: Suppressed 40 warnings (40 NOLINT) diff --git a/clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp b/clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp index 39b86c7d62ef7d..2729a5b1aeccbd 100644 --- a/clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp +++ b/clang-tools-extra/unittests/clang-tidy/ClangTidyDiagnosticConsumerTest.cpp @@ -181,6 +181,55 @@ TEST(ClangTidyDiagnosticConsumer, LineFilterNormalizesWindowsPaths) { } #endif +TEST(ClangTidyDiagnosticConsumer, EnableNoLintBlocks) { + const auto RunWithBlocks = [](bool EnableBlocks) { + ClangTidyOptions Options; + Options.Checks = "*"; + ClangTidyContext Context(std::make_unique<DefaultOptionsProvider>( + ClangTidyGlobalOptions(), Options), + false, false, false); + ClangTidyDiagnosticConsumer DiagConsumer(Context, nullptr, true, false, + EnableBlocks); + auto DiagOpts = std::make_unique<DiagnosticOptions>(); + DiagnosticsEngine DE(DiagnosticIDs::create(), *DiagOpts, &DiagConsumer, + false); + Context.setDiagnosticsEngine(std::move(DiagOpts), &DE); + + std::vector<std::string> Args = {"clang-tidy", "-fsyntax-only", + "-std=c++20", "input.cc"}; + ast_matchers::MatchFinder Finder; + llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> FS( + new llvm::vfs::InMemoryFileSystem); + llvm::IntrusiveRefCntPtr<FileManager> Files( + new FileManager(FileSystemOptions(), FS)); + + SmallVector<std::unique_ptr<ClangTidyCheck>, 1> Checks; + tooling::ToolInvocation Invocation( + Args, + std::make_unique<TestClangTidyAction<TestCheck>>(Checks, Finder, + Context), + Files.get()); + FS->addFile("input.cc", 0, + llvm::MemoryBuffer::getMemBuffer("// NOLINTBEGIN\nint x;\n")); + Invocation.setDiagnosticConsumer(&DiagConsumer); + Invocation.run(); + return DiagConsumer.take(); + }; + + // When EnableNolintBlocks is true, unclosed NOLINTBEGIN produces a + // diagnostic. + EXPECT_TRUE(llvm::any_of(RunWithBlocks(true), [](const ClangTidyError &Err) { + return Err.DiagnosticName == "clang-tidy-nolint"; + })); + + // When EnableNolintBlocks is false, block directives are disabled and no + // unmatched NOLINTBEGIN error is generated. + EXPECT_FALSE( + llvm::any_of(RunWithBlocks(false), [](const ClangTidyError &Err) { + return Err.DiagnosticName == "clang-tidy-nolint"; + })); +} + } // namespace test } // namespace tidy } // namespace clang _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
