[core] Don't emit IIFE for comment-only chunks

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.
This commit is contained in:
J. Nick Koston
2026-04-17 15:06:42 -05:00
parent 6a7c9af870
commit 936694af2c
2 changed files with 16 additions and 3 deletions
+9 -3
View File
@@ -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:
+7
View File
@@ -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();")]