[clang-tools-extra] [clang-tidy] Enhance modernize-use-starts-ends-with to handle substr patterns (PR #116033)
via cfe-commits
cfe-commits at lists.llvm.org
Thu Nov 14 12:54:29 PST 2024
================
@@ -173,7 +240,101 @@ void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) {
this);
}
+void UseStartsEndsWithCheck::handleSubstrMatch(const MatchFinder::MatchResult &Result) {
+ const auto *SubstrCall = Result.Nodes.getNodeAs<CXXMemberCallExpr>("substr_fun");
+ const auto *PositiveComparison = Result.Nodes.getNodeAs<Expr>("positiveComparison");
+ const auto *NegativeComparison = Result.Nodes.getNodeAs<Expr>("negativeComparison");
+
+ if (!SubstrCall || (!PositiveComparison && !NegativeComparison))
+ return;
+
+ const bool Negated = NegativeComparison != nullptr;
+ const auto *Comparison = Negated ? NegativeComparison : PositiveComparison;
+
+ if (SubstrCall->getBeginLoc().isMacroID())
+ return;
+
+ const auto *Str = Result.Nodes.getNodeAs<Expr>("str");
+ const auto *Literal = Result.Nodes.getNodeAs<StringLiteral>("literal");
+ const auto *Length = Result.Nodes.getNodeAs<Expr>("length");
+
+ if (!Str || !Literal || !Length)
+ return;
+
+ // Special handling for strlen and size/length member calls
+ const bool IsValidLength = [&]() {
+ if (const auto *LengthInt = dyn_cast<IntegerLiteral>(Length)) {
+ return LengthInt->getValue().getZExtValue() == Literal->getLength();
+ }
+
+ if (const auto *Call = dyn_cast<CallExpr>(Length)) {
+ if (const auto *FD = Call->getDirectCallee()) {
+ if (FD->getName() == "strlen" && Call->getNumArgs() == 1) {
+ if (const auto *StrArg = dyn_cast<StringLiteral>(
+ Call->getArg(0)->IgnoreParenImpCasts())) {
+ return StrArg->getLength() == Literal->getLength();
+ }
+ }
+ }
+ }
+
+ if (const auto *MemberCall = dyn_cast<CXXMemberCallExpr>(Length)) {
+ if (const auto *Method = MemberCall->getMethodDecl()) {
+ StringRef Name = Method->getName();
----------------
EugeneZelenko wrote:
```suggestion
const StringRef Name = Method->getName();
```
https://github.com/llvm/llvm-project/pull/116033
More information about the cfe-commits
mailing list