[clang-tools-extra] [clang-tidy][modernize-use-starts-ends-with] Add support for compare() (PR #89530)

Piotr Zegar via cfe-commits cfe-commits at lists.llvm.org
Sun Apr 21 07:39:56 PDT 2024


================
@@ -16,6 +16,49 @@
 using namespace clang::ast_matchers;
 
 namespace clang::tidy::modernize {
+namespace {
+// Given two argument indices X and Y, matches when a call expression has a
+// string at index X with an expression representing that string's length at
+// index Y. The string can be a string literal or a variable. The length can be
+// matched via an integer literal or a call to strlen() in the case of a string
+// literal, and by a call to size() or length() in the string variable case.
+AST_POLYMORPHIC_MATCHER_P2(HasStringAndLengthArguments,
+                           AST_POLYMORPHIC_SUPPORTED_TYPES(
+                               CallExpr, CXXConstructExpr,
+                               CXXUnresolvedConstructExpr, ObjCMessageExpr),
+                           unsigned, StringArgIndex, unsigned, LengthArgIndex) {
+  if (StringArgIndex >= Node.getNumArgs() ||
+      LengthArgIndex >= Node.getNumArgs()) {
+    return false;
+  }
+
+  const Expr *StringArgExpr =
+      Node.getArg(StringArgIndex)->IgnoreParenImpCasts();
+  const Expr *LengthArgExpr =
+      Node.getArg(LengthArgIndex)->IgnoreParenImpCasts();
+
+  if (const auto *StringArg = dyn_cast<StringLiteral>(StringArgExpr)) {
+    // Match an integer literal equal to the string length or a call to strlen.
+    const auto Matcher = expr(anyOf(
+        integerLiteral(equals(StringArg->getLength())),
+        callExpr(
+            callee(functionDecl(hasName("strlen"))), argumentCountIs(1),
+            hasArgument(0, stringLiteral(hasSize(StringArg->getLength()))))));
+    return Matcher.matches(*LengthArgExpr, Finder, Builder);
----------------
PiotrZSL wrote:

same in line 52

https://github.com/llvm/llvm-project/pull/89530


More information about the cfe-commits mailing list