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

Nicolas van Kempen via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 17 03:43:40 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")));
----------------
nicovank wrote:

Using `hasAnyName` will match the first declared function. With this setup there is a precedence, I thought this was better. IIRC `llvm::StringRef` has `startswith` and `starts_with` and the latter is preferred.

This could maybe be an option, e.g. `OrderedStartsWithFunctions`. The code gets a bit trickier because this is the opposite of `mapAnyOf`, and AFAIK `anyOf` doesn't take a vector or other kind of collection, only varargs. Suggestions welcome.

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


More information about the cfe-commits mailing list