[clang-tools-extra] [clang-tidy] Add readability-use-span-first-last check (PR #118074)
via cfe-commits
cfe-commits at lists.llvm.org
Fri Feb 27 02:46:13 PST 2026
================
@@ -0,0 +1,121 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "../utils/Matchers.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::readability {
+
+void UseSpanFirstLastCheck::registerMatchers(MatchFinder *Finder) {
+ // Type matcher for concrete std::span types.
+ const auto HasSpanType =
+ hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+ classTemplateSpecializationDecl(hasName("::std::span"))))));
+
+ // Type matcher for dependent std::span types (in templates).
+ const auto HasDependentSpanType = hasType(
+ hasCanonicalType(hasDeclaration(namedDecl(hasName("::std::span")))));
+
+ // --- Non-dependent matchers (concrete types) ---
+
+ // Match span.subspan(0, n) -> first(n)
+ Finder->addMatcher(
+ cxxMemberCallExpr(
+ argumentCountIs(2),
+ callee(memberExpr(hasDeclaration(cxxMethodDecl(hasName("subspan"))))),
+ on(expr(HasSpanType).bind("span_object")),
+ hasArgument(0, integerLiteral(equals(0))),
+ hasArgument(1, expr().bind("count")))
+ .bind("subspan_call"),
+ this);
+
+ // Match span.subspan(span.size() - n) -> last(n)
----------------
zeyi2 wrote:
Can we also support this pattern?
```
s.subspan(s.size() - n, n) -> last(n)
```
https://github.com/llvm/llvm-project/pull/118074
More information about the cfe-commits
mailing list