From 936694af2c801c96fbd126cb21f8f2d2331536db Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Fri, 17 Apr 2026 14:49:14 -0500 Subject: [PATCH] [core] Don't emit IIFE for comment-only chunks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Some components (sha256, async_tcp, network, empty text_sensor:, etc.) emit only a ComponentMarker plus config-dump comments and no actual C++ statements. Wrapping those in a `[]() { ... }();` IIFE is pure clutter in the generated main.cpp — the IIFE has no body. When _wrap_in_iifes sees a chunk whose lines are all // comments, emit them verbatim instead of wrapping. Peak stack and flash are unchanged on apollo and neargaragedoor since GCC was already eliding the empty IIFEs; this just makes the generated code read cleanly to humans. --- esphome/core/__init__.py | 12 +++++++++--- tests/unit_tests/test_core.py | 7 +++++++ 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/esphome/core/__init__.py b/esphome/core/__init__.py index e88add3828d..b66899e1338 100644 --- a/esphome/core/__init__.py +++ b/esphome/core/__init__.py @@ -552,9 +552,15 @@ def _wrap_in_iifes(lines: list[str], max_statements: int) -> list[str]: def flush() -> None: if not chunk: return - out.append("[]() {") - out.extend(chunk) - out.append("}();") + # If the chunk is comments-only (e.g. a component that emits a + # header marker and config dump but no C++ statements), emit them + # verbatim without wrapping — an empty IIFE is pure clutter. + if all(line.lstrip().startswith("//") for line in chunk): + out.extend(chunk) + else: + out.append("[]() {") + out.extend(chunk) + out.append("}();") chunk.clear() for line in lines: diff --git a/tests/unit_tests/test_core.py b/tests/unit_tests/test_core.py index 02a804e6a1d..cd65e670ed7 100644 --- a/tests/unit_tests/test_core.py +++ b/tests/unit_tests/test_core.py @@ -934,6 +934,13 @@ def test_wrap_in_iifes_unbalanced_braces_fall_through() -> None: assert [line for line in result if line in lines] == lines +def test_wrap_in_iifes_skips_comment_only_chunks() -> None: + # Components that emit only a ComponentMarker + config dump (no C++ + # statements) should not be wrapped in an empty IIFE. + lines = ["// === sha256 ===", "// sha256:", "// {}"] + assert core._wrap_in_iifes(lines, max_statements=50) == lines + + def test_cpp_main_section_no_components_emits_flat() -> None: target = core.EsphomeCore() target.main_statements = [RawStatement("a();"), RawStatement("b();")]