================ @@ -0,0 +1,71 @@ +//===----------------------------------------------------------------------===// +// +// 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::tidy::readability; + +static std::string generateCaptureText(const clang::LambdaCapture &Capture) { + if (Capture.capturesThis()) { + return Capture.getCaptureKind() == clang::LCK_StarThis ? "*this" : "this"; + } + + std::string Result; + if (Capture.getCaptureKind() == clang::LCK_ByRef) { + Result += "&"; + } + Result += Capture.getCapturedVar()->getName().str(); + return Result; +} + +void AvoidDefaultLambdaCaptureCheck::registerMatchers( + clang::ast_matchers::MatchFinder *Finder) { + Finder->addMatcher( + clang::ast_matchers::lambdaExpr(clang::ast_matchers::hasDefaultCapture()) + .bind("lambda"), + this); +} + +void AvoidDefaultLambdaCaptureCheck::check( + const clang::ast_matchers::MatchFinder::MatchResult &Result) { + const auto *Lambda = Result.Nodes.getNodeAs<clang::LambdaExpr>("lambda"); + assert(Lambda); + + const clang::SourceLocation DefaultCaptureLoc = + Lambda->getCaptureDefaultLoc(); + if (DefaultCaptureLoc.isInvalid()) + return; + + std::vector<std::string> ImplicitCaptures; + for (const auto &Capture : Lambda->implicit_captures()) { + // It is impossible to explicitly capture a VLA in C++, since VLAs don't + // exist in ISO C++ and so the syntax was never created to capture them. + if (Capture.getCaptureKind() == LCK_VLAType) + return; + ImplicitCaptures.push_back(generateCaptureText(Capture)); + } + + auto Diag = diag(DefaultCaptureLoc, + "lambda default captures are discouraged; " + "prefer to capture specific variables explicitly"); ---------------- vbvictor wrote:
In other "avoid-xxx" checks we have different wordings which IMO is more concise and language-neutral. So to keep uniform, I'd suggest: "avoid default lambda captures; capture specific variables explicitly instead" OR "avoid default lambda captures; prefer to capture specific variables explicitly instead" OR "avoid default lambda captures; prefer to capture specific variables explicitly" But I think the shorter, the better, so I like the first variant https://github.com/llvm/llvm-project/pull/160150 _______________________________________________ cfe-commits mailing list [email protected] https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
