[clang] [clang-tools-extra] [clang-tidy] Add readability-avoid-default-lambda-capture (PR #160150)
JJ Marr via cfe-commits
cfe-commits at lists.llvm.org
Wed Oct 8 08:12:32 PDT 2025
================
@@ -0,0 +1,94 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "AvoidDefaultLambdaCaptureCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Basic/Lambda.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+namespace {
+AST_MATCHER(LambdaExpr, hasDefaultCapture) {
+ return Node.getCaptureDefault() != LCD_None;
+}
+
+std::optional<std::string>
+generateImplicitCaptureText(const LambdaCapture &Capture) {
+ if (Capture.capturesThis()) {
+ return Capture.getCaptureKind() == LCK_StarThis ? "*this" : "this";
+ }
+
+ if (Capture.capturesVariable()) {
+ std::string Result;
+ if (Capture.getCaptureKind() == LCK_ByRef) {
+ Result += "&";
+ }
+ Result += Capture.getCapturedVar()->getName().str();
+ return Result;
+ }
+
+ if (Capture.capturesVLAType()) {
+ // VLA captures are rare and complex - for now we skip them
+ // A full implementation would need to handle the VLA type properly
+ return std::nullopt;
+ }
----------------
jjmarr-amd wrote:
clang/lib/AST/StmtPrinter.cpp:2368-2370 has this interesting line:
```
case LCK_VLAType:
llvm_unreachable("VLA type in explicit captures.");
}
```
I have come to the conclusion that it's impossible to explicitly capture a VLA, since VLAs aren't ISO standard C++. So, if a VLA shows up, the check will early-return without a warning.
IMO, if you've gone to the effort of enabling `clang-tidy` and you're still using variable-length arrays for some reason, this check likely won't convince you otherwise.
https://github.com/llvm/llvm-project/pull/160150
More information about the cfe-commits
mailing list