[clang-tools-extra] [clang-tidy] Add performance-substr-self-assignment check (PR #209657)
Yanzuo Liu via cfe-commits
cfe-commits at lists.llvm.org
Tue Jul 21 02:17:32 PDT 2026
================
@@ -0,0 +1,129 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "SubstrSelfAssignmentCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprCXX.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include <optional>
+#include <string>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::performance {
+
+SubstrSelfAssignmentCheck::SubstrSelfAssignmentCheck(StringRef Name,
+ ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context),
+ StringLikeClasses(utils::options::parseStringList(
+ Options.get("StringLikeClasses", "::std::basic_string"))) {}
+
+void SubstrSelfAssignmentCheck::storeOptions(
+ ClangTidyOptions::OptionMap &Opts) {
+ Options.store(Opts, "StringLikeClasses",
+ utils::options::serializeStringList(StringLikeClasses));
+}
+
+void SubstrSelfAssignmentCheck::registerMatchers(MatchFinder *Finder) {
+ const auto VarRef =
+ ignoringParens(declRefExpr(to(varDecl().bind("var"))).bind("lhs"));
+
+ const auto StringClass =
+ cxxRecordDecl(hasAnyName(StringLikeClasses)).bind("string-class");
+
+ // The static member 'npos' of the matched string class. A bare name
+ // comparison is not enough: a local variable or parameter that happens to
+ // be called 'npos' carries a real count, which has no single-'erase'
+ // rewrite.
+ const auto NposDecl =
+ varDecl(hasName("npos"),
+ hasDeclContext(cxxRecordDecl(equalsBoundNode("string-class"))));
+
+ const auto Npos =
+ expr(ignoringParenImpCasts(anyOf(declRefExpr(hasDeclaration(NposDecl)),
+ memberExpr(hasDeclaration(NposDecl)))));
----------------
zwuis wrote:
```diff
-anyOf(...)
+mapAnyOf(declRefExpr, memberExpr).with(hasDeclaration(...))
```
https://github.com/llvm/llvm-project/pull/209657
More information about the cfe-commits
mailing list