From 01fc7511aecf6c34ddf9694353cb9f822292be23 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Wed, 23 Sep 2026 12:15:21 +0100 Subject: [PATCH] [core] Call a lambda whose only statement returns a braced value (#19503) --- esphome/cpp_generator.py | 8 +++++++- tests/unit_tests/test_cpp_generator.py | 9 +++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/esphome/cpp_generator.py b/esphome/cpp_generator.py index f394337604..a681583053 100644 --- a/esphome/cpp_generator.py +++ b/esphome/cpp_generator.py @@ -1212,7 +1212,13 @@ def call_lambda(lamb: LambdaExpression) -> Expression: assert lamb.return_type is not None, "Lambda must have a return type to be called" expr = lamb.content.strip() # A lone `return ;` reduces to the expression; anything longer is called as is. - if re.match(r"^return\b", expr) and expr.endswith(";") and expr.count(";") == 1: + # A braced return such as `return {};` needs the lambda's return type, so it is called. + if ( + re.match(r"^return\b", expr) + and expr.endswith(";") + and expr.count(";") == 1 + and not expr[6:].lstrip().startswith("{") + ): expr = RawExpression(expr[6:-1].strip()) # Don't cast if the return type is a class if isinstance(lamb.return_type, MockObjClass): diff --git a/tests/unit_tests/test_cpp_generator.py b/tests/unit_tests/test_cpp_generator.py index a618ad50e0..fa6255b8c9 100644 --- a/tests/unit_tests/test_cpp_generator.py +++ b/tests/unit_tests/test_cpp_generator.py @@ -260,6 +260,15 @@ class TestCallLambda: assert isinstance(result, cg.CallExpression) assert str(result).endswith("}()") + def test_call_lambda__braced_return_is_called(self) -> None: + """A braced return needs the lambda's return type, so it is not reduced.""" + lamb = cg.LambdaExpression(("return {};",), (), "", ct.int_) + + result = cg.call_lambda(lamb) + + assert isinstance(result, cg.CallExpression) + assert "static_cast" not in str(result) + def test_call_lambda__return_expression_with_class_return_type_no_cast(self): """A class return type is not cast, since static_cast doesn't apply to arbitrary class types."""