Skip to content
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
35df1c6
Bugprone-default-lambda-capture
jjmarr-amd Jul 11, 2025
dbb903f
Merge branch 'main' of github.com:llvm/llvm-project into DefaultLambd…
jjmarr-amd Sep 22, 2025
689f95b
Fix headers
jjmarr-amd Sep 22, 2025
9991b9c
remove superfluous comments.
jjmarr-amd Sep 22, 2025
db17a4c
add new matcher
jjmarr-amd Sep 22, 2025
7dcf216
Replace if with assert
jjmarr-amd Sep 22, 2025
176d195
Remove specific warning type
jjmarr-amd Sep 22, 2025
5f23dff
Sync documentation to release notes
jjmarr-amd Sep 22, 2025
4c41332
Update clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.h
jjmarr-amd Sep 22, 2025
330dbd8
Remove superfluous include
jjmarr-amd Sep 22, 2025
31366e6
Fix doc and release notes
jjmarr-amd Sep 22, 2025
70df9df
Fix const
jjmarr-amd Sep 22, 2025
0418517
Merge branch 'main' into DefaultLambdaCapture
jjmarr-amd Sep 22, 2025
0bcdbc4
Fix header guard
jjmarr-amd Sep 23, 2025
ac709f4
Fix header spelling
jjmarr-amd Sep 23, 2025
5d4c2ca
Rename check to readability-default-lambda-capture
jjmarr-amd Sep 24, 2025
c0b90d1
Update clang-tools-extra/docs/clang-tidy/checks/readability/default-l…
jjmarr-amd Sep 24, 2025
1172f73
update doc
jjmarr-amd Sep 25, 2025
66e6aaa
rename check to readability-avoid-default-lambda-capture
jjmarr-amd Sep 25, 2025
4bf58b6
use C++ style comments
jjmarr-amd Sep 25, 2025
a807dd0
Update clang-tools-extra/docs/clang-tidy/checks/readability/avoid-def…
jjmarr-amd Sep 25, 2025
8fdc097
fix doc again
jjmarr-amd Sep 25, 2025
ab8f4b9
remove reference to coding guideline
jjmarr-amd Sep 25, 2025
a4348de
Merge branch 'main' of github.com:llvm/llvm-project into DefaultLambd…
jjmarr-amd Sep 29, 2025
13b5049
rephrase
jjmarr-amd Sep 29, 2025
043df7c
commit vibe coded work
jjmarr-amd Sep 29, 2025
33af58b
attempt to fix to use something that isn't weird string manipulation
jjmarr-amd Sep 29, 2025
51aa182
more vibe coding with human intervention
jjmarr-amd Sep 29, 2025
dd65b90
go back to the hacky string manipulation
jjmarr-amd Sep 29, 2025
a9509f3
remove AI comments
jjmarr-amd Sep 29, 2025
e9e0f9a
fix namespacing issues
jjmarr-amd Sep 29, 2025
b2c3cc2
remove anonymous namespace
jjmarr-amd Sep 29, 2025
969558e
simplify per code review
jjmarr-amd Oct 1, 2025
359fd6c
Use IIFE so ReplacementText can be const.
jjmarr-amd Oct 1, 2025
4e10e78
simplify code even more
jjmarr-amd Oct 3, 2025
9765c90
Turns out this check doesn't like templated lambdas
jjmarr-amd Oct 3, 2025
33a79a0
ignore VLAs
jjmarr-amd Oct 8, 2025
8f21201
move around doc paragraphs
jjmarr-amd Oct 8, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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>(
Expand Down
1 change: 1 addition & 0 deletions clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ add_clang_library(clangTidyBugproneModule STATIC
CopyConstructorInitCheck.cpp
CrtpConstructorAccessibilityCheck.cpp
DanglingHandleCheck.cpp
DefaultLambdaCaptureCheck.cpp
DerivedMethodShadowingBaseMethodCheck.cpp
DynamicStaticInitializersCheck.cpp
EasilySwappableParametersCheck.cpp
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//===----------------------------------------------------------------------===//
//
// 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/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);

const 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
34 changes: 34 additions & 0 deletions clang-tools-extra/clang-tidy/bugprone/DefaultLambdaCaptureCheck.h
Original file line number Diff line number Diff line change
@@ -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_DEFAULTLAMBDACAPTURECHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_DEFAULTLAMBDACAPTURECHECK_H

#include "../ClangTidyCheck.h"

namespace clang::tidy::bugprone {

/** Flags lambdas that use default capture modes
*
* For the user-facing documentation see:
* https://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_DEFAULTLAMBDACAPTURECHECK_H
5 changes: 5 additions & 0 deletions clang-tools-extra/docs/ReleaseNotes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ New checks
Detects default initialization (to 0) of variables with ``enum`` type where
the enum has no enumerator with value of 0.

- New :doc:`bugprone-default-lambda-capture
<clang-tidy/checks/bugprone/default-lambda-capture>` check.

Warns on default lambda captures (e.g. ``[&](){ ... }``, ``[=](){ ... }``)

- New :doc:`bugprone-derived-method-shadowing-base-method
<clang-tidy/checks/bugprone/derived-method-shadowing-base-method>` check.

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
.. title:: clang-tidy - bugprone-default-lambda-capture

bugprone-default-lambda-capture
===============================

Warns on default lambda captures (e.g. ``[&](){ ... }``, ``[=](){ ... }``)

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: ``[]``
1 change: 1 addition & 0 deletions clang-tools-extra/docs/clang-tidy/checks/list.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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>`,
Expand Down
Original file line number Diff line number Diff line change
@@ -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>();
}
Loading