[clang-tools-extra] [clang-tidy] Add readability-use-span-first-last check (PR #118074)

Julian Schmidt via cfe-commits cfe-commits at lists.llvm.org
Fri Dec 6 14:22:52 PST 2024


================
@@ -0,0 +1,96 @@
+//===--- UseSpanFirstLastCheck.cpp - clang-tidy -----------------*- C++ -*-===//
+//
+// 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 "UseSpanFirstLastCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/RecursiveASTVisitor.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+void UseSpanFirstLastCheck::registerMatchers(MatchFinder *Finder) {
+  const auto HasSpanType =
+      hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+          classTemplateSpecializationDecl(hasName("::std::span"))))));
+
+  // Match span.subspan(0, n) -> first(n)
+  Finder->addMatcher(
+      cxxMemberCallExpr(
+          callee(memberExpr(hasDeclaration(cxxMethodDecl(hasName("subspan"))))),
+          on(expr(HasSpanType).bind("span_object")),
+          hasArgument(0, integerLiteral(equals(0))),
+          hasArgument(1, expr().bind("count")), argumentCountIs(2))
+          .bind("first_subspan"),
+      this);
+
+  // Match span.subspan(size() - n) or span.subspan(std::ranges::size(span) - n)
+  // -> last(n)
+  const auto SizeCall = anyOf(
+      cxxMemberCallExpr(
+          callee(memberExpr(hasDeclaration(cxxMethodDecl(hasName("size")))))),
+      callExpr(callee(
+          functionDecl(hasAnyName("::std::size", "::std::ranges::size")))));
----------------
5chmidti wrote:

Both of these are not constrained to be the span object. You'll probably want to swap the `callee` and `on` matchers, and add an `equalsBoundNode("span_object")` check for the `on` and `hasArgument(0,...` in the matchers of `SizeCall`.

Right now, this would match `span.subspan(other.size() - n)` and turn it into `span.last(n)`.

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


More information about the cfe-commits mailing list