[clang-tools-extra] [clang-tidy] Support find for string-like classes in readability-container-contains (PR #157243)
Baranov Victor via cfe-commits
cfe-commits at lists.llvm.org
Tue Sep 9 08:54:46 PDT 2025
================
@@ -9,47 +9,43 @@
#include "ContainerContainsCheck.h"
#include "clang/AST/ASTContext.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
using namespace clang::ast_matchers;
namespace clang::tidy::readability {
void ContainerContainsCheck::registerMatchers(MatchFinder *Finder) {
- const auto HasContainsMatchingParamType = hasMethod(
- cxxMethodDecl(isConst(), parameterCountIs(1), returns(booleanType()),
- hasName("contains"), unless(isDeleted()), isPublic(),
- hasParameter(0, hasType(hasUnqualifiedDesugaredType(
- equalsBoundNode("parameterType"))))));
+ const auto Literal0 = integerLiteral(equals(0));
+ const auto Literal1 = integerLiteral(equals(1));
+
+ const auto ClassWithContains = cxxRecordDecl(
+ hasMethod(cxxMethodDecl(isConst(), parameterCountIs(1), isPublic(),
+ unless(isDeleted()), returns(booleanType()),
+ hasAnyName("contains", "Contains"))
+ .bind("contains_fun")));
const auto CountCall =
- cxxMemberCallExpr(
- argumentCountIs(1),
- callee(cxxMethodDecl(
- hasName("count"),
- hasParameter(0, hasType(hasUnqualifiedDesugaredType(
- type().bind("parameterType")))),
- ofClass(cxxRecordDecl(HasContainsMatchingParamType)))))
+ cxxMemberCallExpr(argumentCountIs(1),
+ callee(cxxMethodDecl(hasAnyName("count", "Count"),
+ ofClass(ClassWithContains))))
.bind("call");
const auto FindCall =
- cxxMemberCallExpr(
- argumentCountIs(1),
- callee(cxxMethodDecl(
- hasName("find"),
- hasParameter(0, hasType(hasUnqualifiedDesugaredType(
- type().bind("parameterType")))),
- ofClass(cxxRecordDecl(HasContainsMatchingParamType)))))
+ // Either one argument, or assume the second argument is the position to
+ // start searching from.
+ cxxMemberCallExpr(anyOf(argumentCountIs(1),
+ cxxMemberCallExpr(argumentCountIs(2),
+ hasArgument(1, Literal0))),
----------------
vbvictor wrote:
It's strange that we write `cxxMemberCallExpr` two times. Is it possible to write:
```cpp
cxxMemberCallExpr(
anyOf(
argumentCountIs(1),
allOf(
argumentCountIs(2),
hasArgument(1, Literal0)
)
)
)
```
https://github.com/llvm/llvm-project/pull/157243
More information about the cfe-commits
mailing list