[clang-tools-extra] [clang-tidy] Add new performance-use-starts-ends-with check (PR #72385)

Piotr Zegar via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 17 04:31:05 PST 2023


================
@@ -0,0 +1,109 @@
+//===--- UseStartsEndsWithCheck.cpp - clang-tidy --------------------------===//
+//
+// 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 "UseStartsEndsWithCheck.h"
+
+#include "../utils/OptionsUtils.h"
+#include "clang/Lex/Lexer.h"
+
+#include <string>
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::performance {
+
+UseStartsEndsWithCheck::UseStartsEndsWithCheck(StringRef Name,
+                                               ClangTidyContext *Context)
+    : ClangTidyCheck(Name, Context) {}
+
+void UseStartsEndsWithCheck::registerMatchers(MatchFinder *Finder) {
+  const auto ZeroLiteral = integerLiteral(equals(0));
+  const auto HasStartsWithMethod = anyOf(
+      hasMethod(cxxMethodDecl(hasName("starts_with")).bind("starts_with_fun")),
+      hasMethod(cxxMethodDecl(hasName("startsWith")).bind("starts_with_fun")),
+      hasMethod(cxxMethodDecl(hasName("startswith")).bind("starts_with_fun")));
+  const auto ClassWithStartsWithFunction = cxxRecordDecl(anyOf(
+      HasStartsWithMethod, hasAnyBase(hasType(hasCanonicalType(hasDeclaration(
+                               cxxRecordDecl(HasStartsWithMethod)))))));
+
+  const auto FindExpr = cxxMemberCallExpr(
+      // .find() call...
+      callee(cxxMethodDecl(hasName("find")).bind("find_fun")),
+      // ... on a class with a starts_with function...
+      on(hasType(
+          hasCanonicalType(hasDeclaration(ClassWithStartsWithFunction)))),
+      // ... and either "0" as second argument or the default argument (also 0).
+      anyOf(hasArgument(1, ZeroLiteral), argumentCountIs(1)));
----------------
PiotrZSL wrote:

consider putting this anyOf first, to exclude lot of calls that have more than 1 argument

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


More information about the cfe-commits mailing list