-
Notifications
You must be signed in to change notification settings - Fork 15.2k
[clang-tidy] Add readability-avoid-default-lambda-capture #160150
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
|
Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the LLVM GitHub User Guide. You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums. |
|
@llvm/pr-subscribers-clang-tools-extra @llvm/pr-subscribers-clang-tidy Author: JJ Marr (jjmarr-amd) ChangesThis is a new linter check that implements Scott Meyers' recommendation to avoid default lambda captures, e.g. The check does not contain an autofix. This will be added in a future PR to reduce the code review burden on this PR. This PR was generated with AI tools. My workflow involved 20 minutes of discussion about the check with AI, after which the AI generated commit I disagreed with the LLM on a few somewhat important points. First, the original warning called out the type of default capture (by-value or by-reference) in the warning message. I felt that was overengineered and unnecessary. Second, the LLM created an Full diff: https://github.com/llvm/llvm-project/pull/160150.diff 8 Files Affected:
diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 8baa8f6b35d4c..67222cbafb5f9 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -23,6 +23,7 @@
#include "CopyConstructorInitCheck.h"
#include "CrtpConstructorAccessibilityCheck.h"
#include "DanglingHandleCheck.h"
+#include "DefaultLambdaCaptureCheck.h"
#include "DerivedMethodShadowingBaseMethodCheck.h"
#include "DynamicStaticInitializersCheck.h"
#include "EasilySwappableParametersCheck.h"
@@ -136,6 +137,8 @@ class BugproneModule : public ClangTidyModule {
"bugprone-copy-constructor-init");
CheckFactories.registerCheck<DanglingHandleCheck>(
"bugprone-dangling-handle");
+ CheckFactories.registerCheck<DefaultLambdaCaptureCheck>(
+ "bugprone-default-lambda-capture");
CheckFactories.registerCheck<DerivedMethodShadowingBaseMethodCheck>(
"bugprone-derived-method-shadowing-base-method");
CheckFactories.registerCheck<DynamicStaticInitializersCheck>(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index b0dbe84a16cd4..c8c31f9f96bb0 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -19,6 +19,7 @@ add_clang_library(clangTidyBugproneModule STATIC
CopyConstructorInitCheck.cpp
CrtpConstructorAccessibilityCheck.cpp
DanglingHandleCheck.cpp
+ DefaultLambdaCaptureCheck.cpp
DerivedMethodShadowingBaseMethodCheck.cpp
DynamicStaticInitializersCheck.cpp
EasilySwappableParametersCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.cpp b/clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.cpp
new file mode 100644
index 0000000000000..288feb7853e0b
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.cpp
@@ -0,0 +1,40 @@
+//===----------------------------------------------------------------------===//
+//
+// 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 "DefaultLambdaCaptureCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+AST_MATCHER(LambdaExpr, hasDefaultCapture) {
+ return Node.getCaptureDefault() != LCD_None;
+}
+
+} // namespace
+
+void DefaultLambdaCaptureCheck::registerMatchers(MatchFinder *Finder) {
+ Finder->addMatcher(lambdaExpr(hasDefaultCapture()).bind("lambda"), this);
+}
+
+void DefaultLambdaCaptureCheck::check(const MatchFinder::MatchResult &Result) {
+ const auto *Lambda = Result.Nodes.getNodeAs<LambdaExpr>("lambda");
+ assert(Lambda);
+
+ SourceLocation DefaultCaptureLoc = Lambda->getCaptureDefaultLoc();
+ if (DefaultCaptureLoc.isInvalid())
+ return;
+
+ diag(DefaultCaptureLoc, "lambda default captures are discouraged; "
+ "prefer to capture specific variables explicitly");
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.h b/clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.h
new file mode 100644
index 0000000000000..9af861aaf2e93
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.h
@@ -0,0 +1,34 @@
+//===----------------------------------------------------------------------===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DEFAULT_LAMBDA_CAPTURE_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DEFAULT_LAMBDA_CAPTURE_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::bugprone {
+
+/** Flags lambdas that use default capture modes
+ *
+ * For the user-facing documentation see:
+ * http://clang.llvm.org/extra/clang-tidy/checks/bugprone/default-lambda-capture.html
+ */
+class DefaultLambdaCaptureCheck : public ClangTidyCheck {
+public:
+ DefaultLambdaCaptureCheck(StringRef Name, ClangTidyContext *Context)
+ : ClangTidyCheck(Name, Context) {}
+ void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+ void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
+ std::optional<TraversalKind> getCheckTraversalKind() const override {
+ return TK_IgnoreUnlessSpelledInSource;
+ }
+};
+
+} // namespace clang::tidy::bugprone
+
+#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DEFAULT_LAMBDA_CAPTURE_H
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst
index bc916396a14ca..780cf41373128 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -203,6 +203,15 @@ New checks
Finds virtual function overrides with different visibility than the function
in the base class.
+- New :doc:`bugprone-default-lambda-capture
+ <clang-tidy/checks/bugprone/default-lambda-capture>` check.
+
+ Finds lambda expressions that use default capture modes (``[=]`` or ``[&]``)
+ and suggests using explicit captures instead. Default captures can lead to
+ subtle bugs including dangling references with ``[&]``, unnecessary copies
+ with ``[=]``, and make code less maintainable by hiding which variables are
+ actually being captured.
+
New check aliases
^^^^^^^^^^^^^^^^^
diff --git a/clang-tools-extra/docs/clang-tidy/checks/bugprone/default-lambda-capture.rst b/clang-tools-extra/docs/clang-tidy/checks/bugprone/default-lambda-capture.rst
new file mode 100644
index 0000000000000..f1fcf3ec52948
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/default-lambda-capture.rst
@@ -0,0 +1,43 @@
+.. title:: clang-tidy - bugprone-default-lambda-capture
+
+bugprone-default-lambda-capture
+===============================
+
+ Finds lambda expressions that use default capture modes (``[=]`` or ``[&]``)
+ and suggests using explicit captures instead. Default captures can lead to
+ subtle bugs including dangling references with ``[&]``, unnecessary copies
+ with ``[=]``, and make code less maintainable by hiding which variables are
+ actually being captured.
+
+Implements Item 31 of Effective Modern C++ by Scott Meyers.
+
+Example
+-------
+
+.. code-block:: c++
+
+ void example() {
+ int x = 1;
+ int y = 2;
+
+ // Bad - default capture by copy
+ auto lambda1 = [=]() { return x + y; };
+
+ // Bad - default capture by reference
+ auto lambda2 = [&]() { return x + y; };
+
+ // Good - explicit captures
+ auto lambda3 = [x, y]() { return x + y; };
+ auto lambda4 = [&x, &y]() { return x + y; };
+ }
+
+The check will warn on:
+
+- Default capture by copy: ``[=]``
+- Default capture by reference: ``[&]``
+- Mixed captures with defaults: ``[=, &x]`` or ``[&, x]``
+
+The check will not warn on:
+
+- Explicit captures: ``[x]``, ``[&x]``, ``[x, y]``, ``[this]``
+- Empty capture lists: ``[]``
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index 472d509101cdb..5232f650f6579 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -91,6 +91,7 @@ Clang-Tidy Checks
:doc:`bugprone-copy-constructor-init <bugprone/copy-constructor-init>`, "Yes"
:doc:`bugprone-crtp-constructor-accessibility <bugprone/crtp-constructor-accessibility>`, "Yes"
:doc:`bugprone-dangling-handle <bugprone/dangling-handle>`,
+ :doc:`bugprone-default-lambda-capture <bugprone/default-lambda-capture>`,
:doc:`bugprone-derived-method-shadowing-base-method <bugprone/derived-method-shadowing-base-method>`,
:doc:`bugprone-dynamic-static-initializers <bugprone/dynamic-static-initializers>`,
:doc:`bugprone-easily-swappable-parameters <bugprone/easily-swappable-parameters>`,
diff --git a/clang-tools-extra/test/clang-tidy/checkers/bugprone/default-lambda-capture.cpp b/clang-tools-extra/test/clang-tidy/checkers/bugprone/default-lambda-capture.cpp
new file mode 100644
index 0000000000000..010edf11f0a2b
--- /dev/null
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/default-lambda-capture.cpp
@@ -0,0 +1,98 @@
+// RUN: %check_clang_tidy %s bugprone-default-lambda-capture %t
+
+void test_default_captures() {
+ int value = 42;
+ int another = 10;
+
+ auto lambda1 = [=](int x) { return value + x; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto lambda2 = [&](int x) { return value + x; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto lambda3 = [=, &another](int x) { return value + another + x; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto lambda4 = [&, value](int x) { return value + another + x; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+}
+
+void test_acceptable_captures() {
+ int value = 42;
+ int another = 10;
+
+ auto lambda1 = [value](int x) { return value + x; };
+ auto lambda2 = [&value](int x) { return value + x; };
+ auto lambda3 = [value, another](int x) { return value + another + x; };
+ auto lambda4 = [&value, &another](int x) { return value + another + x; };
+
+ auto lambda5 = [](int x, int y) { return x + y; };
+
+ struct S {
+ int member = 5;
+ void foo() {
+ auto lambda = [this]() { return member; };
+ }
+ };
+}
+
+void test_nested_lambdas() {
+ int outer_var = 1;
+ int middle_var = 2;
+ int inner_var = 3;
+
+ auto outer = [=]() {
+ // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto inner = [&](int x) { return outer_var + middle_var + inner_var + x; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:19: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ return inner(10);
+ };
+}
+
+void test_lambda_returns() {
+ int a = 1, b = 2, c = 3;
+
+ auto create_adder = [=](int x) {
+ // CHECK-MESSAGES: :[[@LINE-1]]:24: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+ return [x](int y) { return x + y; }; // Inner lambda is fine - explicit capture
+ };
+
+ auto func1 = [&]() { return a; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto func2 = [=]() { return b; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:17: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+}
+
+class TestClass {
+ int member = 42;
+
+public:
+ void test_member_function_lambdas() {
+ int local = 10;
+
+ auto lambda1 = [=]() { return member + local; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto lambda2 = [&]() { return member + local; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:21: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+
+ auto lambda3 = [this, local]() { return member + local; };
+ auto lambda4 = [this, &local]() { return member + local; };
+ }
+};
+
+template<typename T>
+void test_template_lambdas() {
+ T value{};
+
+ auto lambda = [=](T x) { return value + x; };
+ // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: lambda default captures are discouraged; prefer to capture specific variables explicitly [bugprone-default-lambda-capture]
+}
+
+void instantiate_templates() {
+ test_template_lambdas<int>();
+ test_template_lambdas<double>();
+}
|
clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.h
Outdated
Show resolved
Hide resolved
Co-authored-by: EugeneZelenko <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
|
✅ With the latest revision this PR passed the C/C++ code linter. |
|
Please address Clang-Tidy complains. |
Trying to figure out why this wasn't flagged by |
on-behalf-of: @amd <[email protected]>
HerrCai0907
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM with some nits.
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
|
|
||
| namespace clang::tidy::readability { | ||
|
|
||
| /// Flags lambdas that use default capture modes |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Here should be the same as the first section in doc
clang-tools-extra/docs/clang-tidy/checks/readability/avoid-default-lambda-capture.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/readability/avoid-default-lambda-capture.rst
Show resolved
Hide resolved
| // yet, so the list of implicit captures is empty. | ||
| if (ImplicitCaptures.empty() && Lambda->isGenericLambda()) | ||
| return; | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
avoid to fix-it hint in macro.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
could you elaborate on this comment? I don't really understand it.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My best guess is:
// no fixes here
#define MY_LAMBDA() [=]() { std::cout << "implicit_captured" << some_var; };
voif foo() { int some_var; MY_LAMBDA };
voif bar() { int some_var; MY_LAMBDA };or should worth testing too:
#define CAPTURE_ALL &
[CAPTURE_ALL]() { std::cout << "implicit_captured" << some_var; };There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this would obviously break the linter and I need to figure out how to handle this case.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think this would obviously break the linter and I need to figure out how to handle this case.
You could use IsInMacro on lambda location before generating fix-its.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This case we could leave as is:
#define CAPTURE_ALL &
[CAPTURE_ALL]() { std::cout << "implicit_captured" << some_var; };
clang-tools-extra/docs/clang-tidy/checks/readability/avoid-default-lambda-capture.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/readability/avoid-default-lambda-capture.cpp
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/readability/avoid-default-lambda-capture.cpp
Show resolved
Hide resolved
clang-tools-extra/test/clang-tidy/checkers/readability/avoid-default-lambda-capture.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
| auto Diag = diag(DefaultCaptureLoc, | ||
| "lambda default captures are discouraged; " | ||
| "prefer to capture specific variables explicitly"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In other "avoid-xxx" checks we have different wordings which IMHO 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
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Other checks state the problem condition, then give the suggestion. e.g. clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.cpp
ambiguous call to 'reset()' on a pointee of a smart pointer, prefer more explicit approach
So I'm going to say
lambda uses default capture mode; explicitly capture variables instead
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good would be list variables that are default captured, at least first one
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good would be list variables that are default captured, at least first one
Could be an additional "note" message
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good would be list variables that are default captured, at least first one
Could be an additional "note" message
Is this necessary now that there's a suggested fix that contains all the default captures?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I guess notes could be useful if some 3rd party software can capture warning/note messages from clang-tidy output but cant capture fixits. So in UI you would have more information.
But this feature IMHO not a blocker.
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.cpp
Outdated
Show resolved
Hide resolved
Co-authored-by: Congcong Cai <[email protected]> Co-authored-by: Baranov Victor <[email protected]>
…tureCheck.cpp Co-authored-by: Baranov Victor <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
clang-tools-extra/test/clang-tidy/checkers/readability/avoid-default-lambda-capture.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/readability/avoid-default-lambda-capture.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/docs/clang-tidy/checks/readability/avoid-default-lambda-capture.rst
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
Outdated
Show resolved
Hide resolved
clang-tools-extra/clang-tidy/readability/AvoidDefaultLambdaCaptureCheck.h
Show resolved
Hide resolved
|
When finished with initial work, please try to run the check over LLVM/other large codebase to see if there are any hidden bugs left. |
I already did so on the internal codebase this check is intended for, and it worked. |
Co-authored-by: Victor Chernyakin <[email protected]>
on-behalf-of: @amd <[email protected]>
| } | ||
|
|
||
| void AvoidDefaultLambdaCaptureCheck::registerMatchers(MatchFinder *Finder) { | ||
| Finder->addMatcher(lambdaExpr(hasDefaultCapture()).bind("lambda"), this); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
consider excluding system headers.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
doesn't clang-tidy have a global option to exclude system headers?
| auto Diag = diag(DefaultCaptureLoc, | ||
| "lambda default captures are discouraged; " | ||
| "prefer to capture specific variables explicitly"); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
good would be list variables that are default captured, at least first one
| ======================================== | ||
|
|
||
| Warns on default lambda captures (e.g. ``[&](){ ... }``, ``[=](){ ... }``). | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
mention somewere that check provide autofixes
|
I think think this check should have an option to not warning with STL algorithms: I do respect Scott Meyers' recommendations, but in practise that lambda in |
I agree. Not sure what other exemptions should be made, though. Sorry I haven't been working on this lately, got caught up with other stuff at work. |
on-behalf-of: @amd <[email protected]>
on-behalf-of: @amd <[email protected]>
|
|
||
| Coding guidelines that recommend against defaulted lambda captures include: | ||
|
|
||
| * Item 31 of Effective Modern C++ by Scott Meyers |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing punctuation?
🐧 Linux x64 Test Results
|
localspook
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Apart from these comments, LGTM (I would be fine with merging even without the option to not warn on algorithms, although if you want to implement that now, that's okay too!)
| for (int i = 0; i < n; ++i) { | ||
| vla[i] = i * 10; | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This loop seems unnecessary; I don't think it exercises any part of the check:
| for (int i = 0; i < n; ++i) { | |
| vla[i] = i * 10; | |
| } |
| (void)y3; | ||
| } | ||
|
|
||
| void test_vla_no_crash() { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I imagine the test is named no_crash because the check used to crash on VLAs, but since that crash was fixed in development (never went out to users), I would prefer to not mention here:
| void test_vla_no_crash() { | |
| void test_vla() { |
|
|
||
| // For template-dependent lambdas, the list of captures hasn't been created | ||
| // yet, so the list of implicit captures is empty. | ||
| if (ImplicitCaptures.empty() && Lambda->isGenericLambda()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure this condition is quite right. A "generic lambda" is one with a templated call operator, but the capture lists of those are known (see lines 33-34 of this AST: https://godbolt.org/z/M6nYc8c9s). For example, we can provide a fix-it just fine in the following case (and I think the check already does, although it would be good to add a test):
void f() {
int a;
int b;
auto l = [&]<template T>(T foo) { return a + b; };
// becomes: [&a, &b]<template T>(T foo) { return a + b; };
}As far as I can tell, it's only when the lambda's type is dependent that the capture list isn't known and we can't provide a fix-it, so I think the condition should be something like:
| if (ImplicitCaptures.empty() && Lambda->isGenericLambda()) | |
| if (ImplicitCaptures.empty() && Lambda->getLambdaClass()->isDependentType()) |
| auto lambda4 = [this, &local]() { return member + local; }; | ||
| } | ||
| }; | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
These cases are contrived, but could we test that we suggest deleting default captures that don't capture anything?
auto lambda1 = [&]() {};
// CHECK-FIXES: auto lambda1 = []() {};
auto lambda2 = [=]() {};
// CHECK-FIXES: auto lambda2 = []() {};
// If I'm right about the isGenericLambda condition being incorrect, I think
// the check currently doesn't provide a fix-it in this case, even though it could:
auto lambda3 = [&](auto) {};
// CHECK-FIXES auto lambda3 = [](auto) {};
This is a new linter check that implements Scott Meyers' recommendation to avoid default lambda captures, e.g.
[&]() { ... }.The check does not contain an autofix. This will be added in a future PR to reduce the code review burden on this PR.(Added after discussion.)This PR was generated with AI tools. My workflow involved 20 minutes of discussion about the check with AI, after which the AI generated commit
35df1c6. I then reviewed the PR at jjmarr-amd#1 and made various changes to the LLM output in follow-up commits. This took me a few months in between other work.I disagreed with the LLM on a few somewhat important points. First, the original warning called out the type of default capture (by-value or by-reference) in the warning message. I felt that was overengineered and unnecessary. Second, the LLM created an
AST_MATCHERthat matched every lambda, then checked for the presence of a default capture incheck(). From previous code reviews I believe it's better to put that logic into the matcher itself.on-behalf-of: @amd [email protected]