Skip to content

refactor(filesystem): isolate SD impl in its own TU so the linker tree-shakes it (removes FASTLED_USE_SDCARD macro from #2778) - #2782

Merged
zackees merged 1 commit into
masterfrom
feat/2773-sd-treeshake
Jun 5, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/2773-sd-treeshake

Conversation

@zackees

@zackees zackees commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Follow-up to #2778. Replaces the FASTLED_USE_SDCARD macro-gate that
landed there with a structural split — the linker now tree-shakes
SD code automatically, no user opt-in required.

Implements the redesign requested on the closed branch of #2778
("redesign this so that the symbols can be tree shaken out").

Why the macro wasn't the right answer

The first version of #2778 required every SD-using sketch to add
`#define FASTLED_USE_SDCARD` before `<FastLED.h>`. The reviewer pushed
back: the linker should handle this automatically. Root cause was
structural — `FileSystem::beginSd` and `make_sdcard_filesystem` lived
in `fl.system+.cpp.o` alongside the rest of `FileSystem`, so the linker
had to keep the whole TU alive and dragged the SD/VFS/printf chain
along regardless of whether any user code actually called `beginSd`.

The structural fix

Move `FileSystem::beginSd(int)` and the `make_sdcard_filesystem(int)`
weak-fallback / strong-overrides into a new sub-aggregate:

```
src/fl/build/fl.system.sd+.cpp # unity entry point (its own .o)
src/fl/system/sd/_build.cpp.hpp # subdirectory aggregator
src/fl/system/sd/file_system_sd.h # header pair
src/fl/system/sd/file_system_sd.cpp.hpp # actual impl
```

The unity-build glob auto-discovers the new `fl.system.sd+.cpp` and
compiles it to its own `.o` archive member of `libFastLED.a`. The
parent `fl/system/_build.cpp.hpp` does NOT need to include
`sd/_build.cpp.hpp` — per the unity-build linter's
recursive-build rule (`ci/lint_cpp/test_unity_build.py:189`), the
recursive entry point covers the subdirectory independently.

How the linker tree-shakes it now

  • Sketch calls `fs.beginSd(4)` → linker has unresolved
    `FileSystem::beginSd` → scans `libFastLED.a` → finds it in
    `fl.system.sd+.cpp.o` → pulls that `.o` → SD library + `vtable` for
    `VFSImpl` + the `_svfprintf_r` printf chain come along. Works.
  • Sketch doesn't call `beginSd` → no unresolved symbol → no archive
    pull → `fl.system.sd+.cpp.o` stays out of the link → the entire SD
    chain (`libSD.a`, `libFS.a`, `VFSImpl`, ~16 KB on ESP32-S3) is dropped.
    No macros, no opt-in, no user-visible change.

Same mechanism the other split unity aggregates use (e.g. `fl/channels/`'s
`detail/`, `rx/`, `spi/` subdirs are split via the same recursive-build
pattern, just within `fl.channels+`).

Removes the macro from #2778

This PR removes the `FASTLED_USE_SDCARD` conditional that landed in
#2778. Migration: none.

Measured (ESP32-S3, Blink.ino, PIO + IDF 5.4 + xtensa-esp-elf-gcc 14.2.0)

Build `firmware.bin` Δ
pre-#2778 master 673,402 B —
#2778 macro-gate (current master) 657,680 B −15,722 B
this PR (structural split) 657,392 B −16,010 B vs pre-#2778

A small additional 288 B over the macro-gate version, but the headline
win is removing the user-facing macro requirement while keeping the
~16 KB savings.

Verification

  • `bash test fl_system_file_system` — 1/1 pass (this test calls
    `fs.beginSd(5)`, exercising the linked SD TU path).
  • `bash compile esp32s3 --examples Blink --platformio` — clean build.
  • `firmware.bin`: 657,392 B.
  • `nm firmware.elf | grep VFSImpl` → empty.
  • `grep "libFastLED.a(fl.system.sd+.cpp.o)" firmware.map` → empty
    (the SD `.o` was not pulled).
  • `bash lint --cpp` — clean (includes `EXPECTED_BUILD_FILES`
    update in `ci/lint_cpp/test_unity_build.py`).
  • CI green.

Files

File Status Purpose
`src/fl/build/fl.system.sd+.cpp` new Unity-build entry point for the SD `.o`
`src/fl/system/sd/_build.cpp.hpp` new Subdirectory aggregator
`src/fl/system/sd/file_system_sd.h` new Header pair (satisfies `CppHppHeaderPairChecker`)
`src/fl/system/sd/file_system_sd.cpp.hpp` new The SD impl moved here
`src/fl/system/file_system.cpp.hpp` modified Removed `FASTLED_USE_SDCARD` gate, removed SD bits
`ci/lint_cpp/test_unity_build.py` modified Added `fl/build/fl.system.sd+.cpp` to `EXPECTED_BUILD_FILES`

Issue: #2773
Supersedes the macro-gate in #2778.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Restructured SD-card support into a dedicated compilation unit to enable linker-based tree-shaking, reducing binary size and memory footprint when SD functionality is not utilized. The public FileSystem API remains unchanged and fully functional.

…e-shakes it (#2773 item 1.2 follow-up to #2778)

Replaces the `FASTLED_USE_SDCARD` macro-gate landed in #2778 with a
**structural split** that lets the linker tree-shake SD code
AUTOMATICALLY — no user-side opt-in required, the macro is gone.

Implements the redesign requested on #2778 ("redesign this so that the
symbols can be tree shaken out"). Item 1.2 of #2773 the proper way.

## Why the macro gate wasn't the right answer

The first version of #2778 gated `<SD.h>` auto-detect behind
`FASTLED_USE_SDCARD`, requiring every SD-using sketch to add a
`#define` before `<FastLED.h>`. The reviewer pushed back that the
linker should handle this automatically. They were right — the root
cause was structural: `FileSystem::beginSd` and `make_sdcard_filesystem`
were compiled into the same translation unit (`fl.system+.cpp.o`) as
the rest of `FileSystem`, so the linker had to keep the whole TU alive
and dragged the SD/VFS/printf chain along.

## The structural fix

Move `FileSystem::beginSd(int)` and the `make_sdcard_filesystem(int)`
weak-fallback / strong-overrides into a NEW sub-aggregate:

```
src/fl/build/fl.system.sd+.cpp        # unity entry point (its own .o)
src/fl/system/sd/_build.cpp.hpp       # subdirectory aggregator
src/fl/system/sd/file_system_sd.h     # header pair
src/fl/system/sd/file_system_sd.cpp.hpp   # actual impl
```

The unity-build glob in `ci/meson/rglob.py` auto-discovers
`fl.system.sd+.cpp` and compiles it to its own `.o` archive member of
`libFastLED.a`. Per the unity-build linter's recursive-build rule
(`ci/lint_cpp/test_unity_build.py:189`), the parent
`fl/system/_build.cpp.hpp` does NOT need to include the new
`sd/_build.cpp.hpp` because the recursive entry point covers the
subdirectory independently.

## How the linker tree-shakes it now

- Sketch calls `fs.beginSd(4)` → linker has unresolved
  `FileSystem::beginSd` → scans `libFastLED.a` → finds it in
  `fl.system.sd+.cpp.o` → pulls that `.o` → SD library + vtable for
  `VFSImpl` + the `_svfprintf_r` printf chain come along. Works.
- Sketch doesn't call `beginSd` → no unresolved symbol → no archive
  pull → `fl.system.sd+.cpp.o` stays out of the link → the entire SD
  chain (libSD.a, libFS.a, `VFSImpl`, ~16 KB on ESP32-S3) is dropped.
  No macros, no opt-in, no user-visible change.

## Removes the macro from #2778

This PR removes the `FASTLED_USE_SDCARD` conditional that landed in
#2778. Migration: nothing — existing sketches that defined
`FASTLED_USE_SDCARD` keep working (the macro is now no-op but harmless),
and sketches that didn't define it but used `beginSd` (which was a
silent no-op in #2778) now work correctly again. Net effect for users
is "everything works as it did before #2778, but ~16 KB lighter for the
99% of sketches that never touch SD."

## Measured (ESP32-S3, Blink.ino, PIO + IDF 5.4 + xtensa-esp-elf-gcc 14.2.0)

| Build | firmware.bin | Δ |
|---|---:|---:|
| pre-#2778 master | 673,402 B | — |
| #2778 (macro gate, current master) | 657,680 B | −15,722 B |
| this PR (structural split) | **657,392 B** | **−16,010 B vs pre-#2778** |

Verification (from binary):

    xtensa-esp32s3-elf-nm firmware.elf | grep VFSImpl
    # empty after this PR

    xtensa-esp32s3-elf-nm firmware.elf | grep -E "FileSystem::beginSd|make_sdcard_filesystem"
    # empty — both are in the SD TU which was dropped

    grep "libFastLED.a(fl.system.sd\+.cpp.o)" firmware.map
    # no archive-pull line — the .o was never linked

When a sketch DOES call `fs.beginSd(5)`, the linker correctly pulls the
SD TU. Verified by `tests/fl/system/file_system.cpp` which calls
`fs.beginSd(5)` and expects success: passes with 1/1
(`bash test fl_system_file_system`).

## Verification

- [x] `bash test fl_system_file_system` — 1/1 pass (test calls
      `fs.beginSd(5)`, exercising the linked SD TU path).
- [x] `bash compile esp32s3 --examples Blink --platformio` — clean build.
- [x] `firmware.bin`: 657,392 B (vs 657,680 in #2778 macro-gate,
      −288 B further; vs 673,402 pre-#2778, −16,010 B total).
- [x] `nm firmware.elf | grep VFSImpl` — empty.
- [x] `bash lint --cpp` — clean (includes `EXPECTED_BUILD_FILES`
      update for the new aggregate).

Issue: #2773
Supersedes the macro-gate in #2778.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 5, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

SD-card support is extracted from conditional compilation in the main FileSystem translation unit into a separate, independently-linkable translation unit. This permits the linker to drop the entire SD library chain when FileSystem::beginSd() is never called.

Changes

SD Support Refactoring to Separate Translation Unit for Linker Dead-Stripping

Layer / File(s) Summary
Main FileSystem refactoring (removal of SD)
src/fl/system/file_system.cpp.hpp
Removed SD-specific compile-time gating directives, the FileSystem::beginSd(int) implementation, and weak fallback make_sdcard_filesystem(int) that returned NullFileSystem. Replaced with documentation that SD support moved to a separate translation unit for linker dead-stripping.
SD-specific implementation and headers
src/fl/system/sd/file_system_sd.cpp.hpp, src/fl/system/sd/file_system_sd.h, src/fl/system/sd/_build.cpp.hpp
New SD implementation files provide FileSystem::beginSd(int) and make_sdcard_filesystem(int) with platform-conditional backend selection (unit-test stub, WASM, Arduino SD/FS). Fallback returns null when SD is unavailable. Header scaffolding and build aggregation document the separate TU linkage intent.
Build system integration
src/fl/build/fl.system.sd+.cpp, ci/lint_cpp/test_unity_build.py
New SD translation unit entrypoint wires the SD implementation into the unity build and includes platform header. Lint test expectations updated to recognize the new entrypoint file in validation checks.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • FastLED/FastLED#2778: Both modify src/fl/system/file_system.cpp.hpp to change SD support provision—this PR moves SD implementation to a separate TU for dead-stripping while the other uses opt-in gating.
  • FastLED/FastLED#2442: Both update the unity-build lint (ci/lint_cpp/test_unity_build.py) by adding new expected build entrypoints to the EXPECTED_BUILD_FILES set.

Poem

🐇 A rabbit hops through linker chains,
With SD tucked in separate veins—
Now trees can shake and drop the load,
When SD never takes the road! 📦✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The pull request title accurately summarizes the main change: refactoring the filesystem module to isolate SD implementation into its own translation unit for linker tree-shaking, while removing the FASTLED_USE_SDCARD macro.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/2773-sd-treeshake

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Infer (1.2.0)
src/fl/build/fl.system.sd+.cpp

src/fl/build/fl.system.sd+.cpp:12:10: fatal error: 'platforms/new.h' file not found
12 | #include "platforms/new.h"
| ^~~~~~~~~~~~~~~~~
1 error generated.
Error: the following clang command did not run successfully:
/opt/infer-linux-x86_64-v1.2.0/lib/infer/facebook-clang-plugins/clang/install/bin/clang-18
@/tmp/coderabbit-infer/918aa4a7c131f925dca644d22f7c7e815b20d507-0d0d87b5f4ac865c/tmp/clang_command_.tmp.44091f.txt
++Contents of '/tmp/coderabbit-infer/918aa4a7c131f925dca644d22f7c7e815b20d507-0d0d87b5f4ac865c/tmp/clang_command_.tmp.44091f.txt':
"-cc1" "-load"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../../facebook-clang-plugins/libtooling/build/FacebookClangPlugin.dylib"
"-add-plugin" "BiniouASTExporter" "-plugin-arg-BiniouASTExporter" "-"
"-plugin-arg-BiniouASTExporter" "PREPEND_CURRENT_DIR=1"
"-plugin-arg-BiniouASTExporter" "MAX_STRING_SIZE=65535" "-cc1" "-triple"
"x86_64-unknown-linux-gnu" "-emit-obj" "-mrelax-all" "-d

... [truncated 1085 characters] ...

tall/lib/clang/18/include"
"-internal-isystem" "/usr/local/include" "-internal-isystem"
"/usr/lib/gcc/x86_64-linux-gnu/12/../../../../x86_64-linux-gnu/include"
"-internal-externc-isystem" "/usr/include/x86_64-linux-gnu"
"-internal-externc-isystem" "/include" "-internal-externc-isystem"
"/usr/include" "-Wno-ignored-optimization-argument" "-Wno-everything"
"-fdeprecated-macro" "-ferror-limit" "19" "-fgnuc-version=4.2.1"
"-fskip-odr-check-in-gmf" "-fcxx-exceptions" "-fexceptions"
"-D__GCC_HAVE_DWARF2_CFI_ASM=1" "-o"
"/tmp/coderabbit-infer/0d0d87b5f4ac865c/file.o" "-x" "c++"
"src/fl/build/fl.system.sd+.cpp" "-O0" "-fno-builtin" "-include"
"/opt/infer-linux-x86_64-v1.2.0/lib/infer/infer/bin/../lib/clang_wrappers/global_defines.h"
"-Wno-everything"


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/fl/system/sd/_build.cpp.hpp`:
- Around line 2-7: The comment block describing the SD-card unity build contains
Unicode punctuation (an em dash); update the comment lines that mention the
unity-build and linker tree-shake to use only ASCII punctuation (replace “—”
with a plain hyphen '-' or two hyphens '--') so the text around symbols like
FileSystem::beginSd(), libSD.a, libFS.a, VFSImpl and FastLED `#2773` remains
identical but ASCII-only; ensure no other non-7-bit characters remain in that
comment block.

In `@src/fl/system/sd/file_system_sd.cpp.hpp`:
- Around line 68-75: FileSystem::beginSd currently ignores the return value of
mFs->begin(), allowing beginSd to report success even if the SD backend failed
to initialize; update beginSd (which calls make_sdcard_filesystem and uses mFs)
to capture the boolean result of mFs->begin() and return false when that call
fails (only return true when mFs is non-null and mFs->begin() returns true), so
callers receive proper failure propagation.

In `@src/fl/system/sd/file_system_sd.h`:
- Around line 3-11: The header comment in file_system_sd.h contains Unicode
punctuation (em dash “—”); update the comment text to use only ASCII characters
(e.g., replace em dashes with double hyphens "--" or simple hyphens "-", and
replace any other Unicode punctuation) so the header is ASCII-only; preserve the
same wording and references to file_system_sd.cpp.hpp, FileSystem::beginSd(int),
make_sdcard_filesystem(int), and CppHppHeaderPairChecker while ensuring all
characters are 7-bit ASCII.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 9169d5a7-9135-4f9c-9818-3932c8562bcf

📥 Commits

Reviewing files that changed from the base of the PR and between a4bdea8 and 918aa4a.

📒 Files selected for processing (6)
  • ci/lint_cpp/test_unity_build.py
  • src/fl/build/fl.system.sd+.cpp
  • src/fl/system/file_system.cpp.hpp
  • src/fl/system/sd/_build.cpp.hpp
  • src/fl/system/sd/file_system_sd.cpp.hpp
  • src/fl/system/sd/file_system_sd.h

Comment on lines +2 to +7
/// @brief Unity-build aggregate for SD-card support. Pulled in only by
/// `src/fl/build/fl.system.sd+.cpp` — never by the parent
/// `src/fl/system/_build.cpp.hpp`. That separation is what lets the
/// linker tree-shake the entire SD chain (libSD.a, libFS.a, Arduino's
/// VFSImpl, ~16 KB on ESP32-S3) when the user never calls
/// `FileSystem::beginSd()`. See FastLED #2773 item 1.2.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Normalize comments to ASCII-only characters.

Lines 2-4 include Unicode punctuation (—). Replace with ASCII punctuation for compliance and tooling consistency.

As per coding guidelines, "ASCII-only source: ensure any comments/code in the added/modified .h/.hpp/.cpp files contain only 7-bit ASCII (no emoji/Unicode punctuation in source files)."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/system/sd/_build.cpp.hpp` around lines 2 - 7, The comment block
describing the SD-card unity build contains Unicode punctuation (an em dash);
update the comment lines that mention the unity-build and linker tree-shake to
use only ASCII punctuation (replace “—” with a plain hyphen '-' or two hyphens
'--') so the text around symbols like FileSystem::beginSd(), libSD.a, libFS.a,
VFSImpl and FastLED `#2773` remains identical but ASCII-only; ensure no other
non-7-bit characters remain in that comment block.

Comment on lines +68 to +75
bool FileSystem::beginSd(int cs_pin) {
mFs = make_sdcard_filesystem(cs_pin);
if (!mFs) {
return false;
}
mFs->begin();
return true;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Propagate backend initialization failure from beginSd.

Line 73 ignores the mFs->begin() result, so beginSd() can return true even when SD mount/init fails. That breaks callers that rely on false to detect unavailable media.

Suggested fix
 bool FileSystem::beginSd(int cs_pin) {
     mFs = make_sdcard_filesystem(cs_pin);
     if (!mFs) {
         return false;
     }
-    mFs->begin();
-    return true;
+    if (!mFs->begin()) {
+        mFs.reset();
+        return false;
+    }
+    return true;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
bool FileSystem::beginSd(int cs_pin) {
mFs = make_sdcard_filesystem(cs_pin);
if (!mFs) {
return false;
}
mFs->begin();
return true;
}
bool FileSystem::beginSd(int cs_pin) {
mFs = make_sdcard_filesystem(cs_pin);
if (!mFs) {
return false;
}
if (!mFs->begin()) {
mFs.reset();
return false;
}
return true;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/system/sd/file_system_sd.cpp.hpp` around lines 68 - 75,
FileSystem::beginSd currently ignores the return value of mFs->begin(), allowing
beginSd to report success even if the SD backend failed to initialize; update
beginSd (which calls make_sdcard_filesystem and uses mFs) to capture the boolean
result of mFs->begin() and return false when that call fails (only return true
when mFs is non-null and mFs->begin() returns true), so callers receive proper
failure propagation.

Comment on lines +3 to +11
/// @file fl/system/sd/file_system_sd.h
/// @brief Header pair for `file_system_sd.cpp.hpp`. The actual SD-card
/// API surface lives in `fl/system/file_system.h` —
/// `FileSystem::beginSd(int)` and `make_sdcard_filesystem(int)` are
/// declared there. This header exists only to satisfy the
/// `CppHppHeaderPairChecker` lint rule (every `.cpp.hpp` needs a
/// matching `.h` next to it). The SD implementation is split into its
/// own translation unit so the linker can dead-strip it when nobody
/// calls `beginSd`. See `file_system_sd.cpp.hpp` for the mechanism.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Replace Unicode punctuation with ASCII in header comments.

Lines 4-10 use Unicode punctuation (em dash —). Please switch to ASCII characters to satisfy source encoding constraints.

As per coding guidelines, "ASCII-only source: ensure any comments/code in the added/modified .h/.hpp/.cpp files contain only 7-bit ASCII (no emoji/Unicode punctuation in source files)."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/fl/system/sd/file_system_sd.h` around lines 3 - 11, The header comment in
file_system_sd.h contains Unicode punctuation (em dash “—”); update the comment
text to use only ASCII characters (e.g., replace em dashes with double hyphens
"--" or simple hyphens "-", and replace any other Unicode punctuation) so the
header is ASCII-only; preserve the same wording and references to
file_system_sd.cpp.hpp, FileSystem::beginSd(int), make_sdcard_filesystem(int),
and CppHppHeaderPairChecker while ensuring all characters are 7-bit ASCII.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant