Skip to content

feat(lint): SingletonElisionChecker — land + drive to zero violations - #3495

Merged
zackees merged 3 commits into
masterfrom
feat/singleton-elision-lint
Jul 1, 2026
Merged

zackees merged 3 commits into
masterfrom
feat/singleton-elision-lint

Conversation

@zackees

@zackees zackees commented Jul 1, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds SingletonElisionChecker to the bash lint Rust checker suite, then drives the checker output to zero violations on the current tree. Establishes the ratchet against re-accumulation of namespace-scope statics that defeat --gc-sections elision.

Closes #3481 (meta) — the individual sub-issues #3482–#3493 track the follow-up work items.

What lands in this PR

Tooling

  • Rust checker SingletonElisionChecker (registered in the CLI, emits like every other lint rule).
  • Python scanner ci/scan_singleton_elision.py for ad-hoc analysis with JSON dump. Local artifacts gitignored.
  • Two escape-hatch markers:
    • FL_LINT_ALLOW_GLOBAL(<reason>) — per-line, honored inline on the decl OR on the preceding comment line
    • FL_LINT_ALLOW_GLOBAL_FILE(<reason>) — file-level, checked in the first 15 lines, suppresses whole file

One concrete migration

  • src/fl/stl/allocator.cpp.hpp: slab_registry (64 entries × ~24 bytes = ~1.5 KB .bss) moved into SlabRegistryState accessed via fl::Singleton<>::instance(). Elides fully when no SlabAllocator<T> is instantiated.

Allowlists (with justifications)

Public API surface (source-compat — x would need to become x()):

  • fl::cout, fl::cin, fl::fl_serial
  • fl::hex, fl::dec, fl::oct, fl::endl (empty-struct manipulator tags; inline constexpr would fix but requires C++17, project targets C++11)

Inherently untouchable:

  • fl/stl/singleton.cpp.hpp registry backing (self-reference)
  • platforms/stub/Arduino.cpp.hpp Serial/Serial1/Serial2/Serial3 (host-test stub emulating Arduino globals)
  • platforms/wasm/entry_point.cpp.hpp + js_fetch.cpp.hpp (WASM-only, no gc-sections benefit)
  • FastLED.cpp.hpp gControllersData (existing ATtiny85 code-size opt documented in-file — Singleton reverses the win)

Tier 2 driver files (file-level allowlist with backref to migration sub-issue):

Savings

Concrete (this PR)

  • ~1.5 KB .bss on any platform where SlabAllocator<T> is unused — from the slab_registry migration.

Unblocked by this PR (Tier 2 sub-issues)

Once each Tier 2 driver moves to Singleton<T> with cached-IRAM-pointer for ISR safety (sub-issues #3489, #3490, #3491):

  • I2S driver state (i2s_esp32dev): ~2 KB .bss on classic ESP32 sketches that don't use I2S
  • FlexIO driver state (Teensy 4): ~1.5 KB .bss
  • ObjectFLED diagnostics: ~500 B (event buffer + counters)
  • LPUART/RMT5 peripheral/LCD_CAM/MCPWM: ~200–500 B each
  • Estimated cumulative win: 8–12 KB flash / 3–5 KB DRAM on typical ESP32 build; larger multiplier on AVR/ATtiny.

Ratchet value (permanent)

  • Zero-violation baseline established. Every future PR gets bash lint warnings if it introduces new namespace-scope statics without justification.

Verification

$ ./ci/lint_cpp_rs/target/x86_64-pc-windows-msvc/debug/fastled-lint.exe \
    --checker singleton_elision --format json --project-root .
TOTAL: 0 violations in 0 files

$ ./test --cpp
✅ All tests passed (344/344 in 53.43s)

Test plan

  • bash lint --cpp — SingletonElisionChecker reports 0 violations
  • bash test --cpp — 344/344 host tests pass
  • CI green
  • User review of allowlist justifications (are the "public API" claims for cout/cin/fl_serial accurate — worth confirming these are actually called by name from user code before locking in as permanent allowlist)

Follow-up (out of scope for this PR)

Tracked in meta #3481 sub-issues #3482–#3493:

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a new code-quality scan that flags globally scoped definitions and suggests safer alternatives.
    • Expanded reporting so scan results are summarized in a machine-readable artifact.
  • Bug Fixes

    • Improved handling of legitimate global values and platform-specific exceptions to reduce false positives.
    • Updated several existing global declarations to be explicitly recognized as intentional.

zackees and others added 3 commits June 30, 2026 23:04
- New Rust checker `SingletonElisionChecker` (unregistered) implements
  regex + brace-depth tracking to identify namespace-scope variable
  definitions that should be wrapped in `fl::Singleton<T>` for
  `--gc-sections` elision.
- Sibling Python scanner (`ci/scan_singleton_elision.py`) produces a
  full violation report + JSON dump for ad-hoc analysis.
- `singleton_elision_violations.json` gitignored — local artifact.

Motivation and full plan documented in #3481. This commit only
lays down the tooling; registration into the CLI registry and the
actual code migration happen in subsequent commits so the diff stays
reviewable.

Part of #3481

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…AL escape hatch

- Registers `singleton_elision` in the CLI checker list so `bash lint`
  executes it. Reports 33 real violations across 15 files on the
  current tree.
- Adds `FL_LINT_ALLOW_GLOBAL(<reason>)` comment marker as a linter-only
  opt-out for cases where the storage genuinely cannot move to
  `Singleton<T>` (public API surface, ISR cache pointer, singleton
  registry backing itself, host-only stub / WASM entry points).
- Adds `::` filter to skip class-static-member out-of-class definitions
  like `constexpr bool numeric_limits<T>::is_signed;` — those are
  C++11-required, don't emit storage unless ODR-used, and were showing
  up as false positives before this fix (72 spurious hits eliminated).

Part of #3481

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…wlist + migration

Result: `bash lint` reports **0** `SingletonElisionChecker` violations,
down from 105 initial (before ::-filter) → 33 after correctness fixes →
0 now.

## Checker improvements
- File-level opt-out marker `FL_LINT_ALLOW_GLOBAL_FILE(<reason>)` in the
  first 15 lines suppresses the whole file. Used for Tier 2 driver files
  whose migration is tracked in dedicated sub-issues.
- Per-line marker `FL_LINT_ALLOW_GLOBAL(<reason>)` honored either inline
  on the declaration OR on the immediately preceding comment line.
- Class-static-member out-of-class defs (`X<T>::static_member`) skipped
  via `::` filter — 72 spurious hits eliminated.
- `should_process_file` anchored to project-root `src/` (via
  `is_under_project_subpath`) so scratch paths like
  `tests/fbuild_qemu_smoke/src/main.cpp` are not caught.

## Concrete migration
- `src/fl/stl/allocator.cpp.hpp`: slab_registry (~1.5 KB `.bss` — 64
  entries × ~24 bytes each) moved into `SlabRegistryState` accessed via
  `fl::Singleton<>::instance()`. Elides fully when no `SlabAllocator<T>`
  is ever instantiated. `slab_registry_state()` annotated FL_NO_EXCEPT.

## Public-API allowlist (source-compat)
Public globals users call by name — moving to `Singleton<T>::instance()`
would require `x()` at every call site. Deferred; annotated:
- `fl::cout`, `fl::cin`, `fl::fl_serial`
- `fl::hex`, `fl::dec`, `fl::oct`, `fl::endl` (empty-struct manipulator
  tags — inline constexpr wanted but C++17 only, project targets C++11)

## Structural / inherently-untouchable allowlist
- `fl/stl/singleton.cpp.hpp` registry backing (can't self-reference)
- `platforms/stub/Arduino.cpp.hpp` Serial/Serial1/Serial2/Serial3 (host
  test-only stub, emulates Arduino API globals by name)
- `platforms/wasm/entry_point.cpp.hpp` gEndFrameListener (WASM-only)
- `platforms/wasm/js_fetch.cpp.hpp` wasm_fetch (WASM-only public global)
- `FastLED.cpp.hpp` gControllersData (existing ATtiny85 code-size
  optimization — Singleton would reverse the win)

## Tier 2 driver file-level allowlists (pending sub-issue migrations)
- `platforms/esp/32/drivers/i2s/i2s_esp32dev.cpp.hpp` — #3489
- `platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_diagnostics.cpp.hpp` — #3487
- `platforms/esp/32/drivers/lcd_cam/lcd_rgb_peripheral_esp.cpp.hpp` — #3491
- `platforms/esp/32/drivers/ble/ble_esp32.cpp.hpp` — #3481 (needs new sub-issue)

Each file has a header comment explaining what's pending and where the
migration is tracked. The `FL_LINT_ALLOW_GLOBAL_FILE` marker keeps the
linter passing while the actual driver work happens under its own PR.

## Verification
- `bash lint --cpp`: 0 SingletonElisionChecker violations (16 pre-existing
  unrelated ones remain — LPC drivers, RMT4 mgr, AutoResearch, UnityBuild
  structure — all present on master before this branch).
- `bash test --cpp`: 344/344 pass.

Part of #3481

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

coderabbitai Bot commented Jul 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c063fa42-066d-4baa-a058-29aea3c78807

📥 Commits

Reviewing files that changed from the base of the PR and between aca1bc5 and d482dae.

📒 Files selected for processing (20)
  • .gitignore
  • ci/lint_cpp_rs/src/checkers/singleton_elision.rs
  • ci/lint_cpp_rs/src/lib.rs
  • ci/lint_cpp_rs/src/lint_core/processor_registry_cli.rs
  • ci/scan_singleton_elision.py
  • src/FastLED.cpp.hpp
  • src/fl/stl/allocator.cpp.hpp
  • src/fl/stl/ios.cpp.hpp
  • src/fl/stl/istream.cpp.hpp
  • src/fl/stl/ostream.cpp.hpp
  • src/fl/stl/ostream.h
  • src/fl/stl/singleton.cpp.hpp
  • src/fl/system/serial.cpp.hpp
  • src/platforms/arm/teensy/teensy4_common/drivers/objectfled/objectfled_diagnostics.cpp.hpp
  • src/platforms/esp/32/drivers/ble/ble_esp32.cpp.hpp
  • src/platforms/esp/32/drivers/i2s/i2s_esp32dev.cpp.hpp
  • src/platforms/esp/32/drivers/lcd_cam/lcd_rgb_peripheral_esp.cpp.hpp
  • src/platforms/stub/Arduino.cpp.hpp
  • src/platforms/wasm/entry_point.cpp.hpp
  • src/platforms/wasm/js_fetch.cpp.hpp

📝 Walkthrough

Walkthrough

Introduces a Rust-based CI linter (SingletonElisionChecker) and a companion Python scanner to detect namespace/file-scope global variable definitions blocking linker gc-sections elision. Registers the checker in the CLI, migrates the slab allocator registry to fl::Singleton, and adds FL_LINT_ALLOW_GLOBAL(_FILE) annotations across many files.

Changes

Singleton elision lint tooling and codebase annotations

Layer / File(s) Summary
Rust checker implementation and CLI registration
ci/lint_cpp_rs/src/checkers/singleton_elision.rs, ci/lint_cpp_rs/src/lib.rs, ci/lint_cpp_rs/src/lint_core/processor_registry_cli.rs
New SingletonElisionChecker scans C++ TU files for scope-level variable definitions, honors opt-out annotations, and is wired into the checker registry/CLI dispatch.
Python standalone scanner
ci/scan_singleton_elision.py, .gitignore
Scans src/ for violation patterns, aggregates counts, prints summaries, and writes a JSON report; the generated artifact is gitignored.
Slab allocator singleton migration
src/fl/stl/allocator.cpp.hpp
Replaces the static registry array/counter with a SlabRegistryState wrapped in fl::Singleton, preserving lookup/update logic.
Lint-allow annotations across core and platform files
src/FastLED.cpp.hpp, src/fl/stl/{ios,istream,ostream}.cpp.hpp, src/fl/stl/ostream.h, src/fl/stl/singleton.cpp.hpp, src/fl/system/serial.cpp.hpp, src/platforms/.../objectfled_diagnostics.cpp.hpp, src/platforms/esp/32/drivers/{ble,i2s,lcd_cam}/*, src/platforms/stub/Arduino.cpp.hpp, src/platforms/wasm/{entry_point,js_fetch}.cpp.hpp
Adds documentation and FL_LINT_ALLOW_GLOBAL(_FILE) comments explaining intentional retention of global/static definitions; no functional logic changes.

Estimated code review effort: 3 (Moderate) | ~30 minutes

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#2689: Establishes the Rust-backed C++ linter framework that this PR's new checker registration extends.
  • FastLED/FastLED#3121: Similarly registers a new checker in lib.rs and processor_registry_cli.rs using the same wiring pattern.
  • FastLED/FastLED#3293: Also modifies processor_registry_cli.rs checker registration/dispatch logic.
✨ 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/singleton-elision-lint

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.

@zackees
zackees merged commit 80167aa into master Jul 1, 2026
7 of 10 checks passed
zackees added a commit that referenced this pull request Jul 1, 2026
`bash lint --cpp` is now clean on master. Prior state was 16 pre-existing
violations across 8 checkers (LPC drivers, RMT4 memory manager, AutoResearch
example, UnityBuild structure) — all unrelated to the singleton-elision work
that landed in #3495 but blocking any hard-fail promotion of that checker.

## Fixes by category

### Suppressions (single-line intent statements)
- `rmt_memory_manager_4.h` L168: `bool free(...)` is a member function, not
  C free() — annotated `// ok bare allocation`.
- `rmt_rx_channel_4.cpp.hpp` L605: `new RmtRxChannelImpl(pin)` is inside a
  `shared_ptr<>` factory for a PRIVATE impl type; `make_shared` would need
  to expose it. Annotated `// ok bare allocation`.
- `AutoResearchPwmDmaClockless.h` L58: deep-include of the concrete engine
  header is intentional for the driver-specific validation harness.
  Annotated `// ok platform headers`.
- `spi_arm_lpc_dma.h` L437/438/444: LPC DMA descriptor construction needs
  raw addresses. Three `// ok reinterpret cast` annotations.

### Real fixes
- `channel_drivers_lpc.impl.hpp`: add missing `#include "platforms/arm/is_arm.h"`
  (the file uses `FL_IS_ARM_LPC_845` which requires the ARM detection header).
- `lpc_sct_dma_runtime.h` L137: `fl::span<const u8>(x.data(), x.size())` →
  `fl::span<const u8>(x)` per SpanFromPointerChecker.

### Structural fixes
- **Test relocation**: `tests/fl/channels/lpc_sct_dma_engine.cpp` →
  `tests/platforms/arm/lpc/drivers/sct_dma/channel_engine_lpc_sct_dma.cpp`.
  The test exercises a platform-specific engine, not a `fl/channels/`
  source file, so the mirror-source-directory convention places it under
  `tests/platforms/arm/lpc/drivers/sct_dma/`.
- **Unity build 1-level rule**: introduced `src/platforms/arm/lpc/drivers/_build.cpp.hpp`
  as the intermediate hop so the parent `platforms/arm/lpc/_build.cpp.hpp`
  only reaches one level deep (per UnityBuildChecker convention).
- **Unity section comments**: added `// begin current directory includes`
  and `// begin sub directory includes` markers to `platforms/arm/lpc/_build.cpp.hpp`
  in the required positions (immediately before their include blocks).

### New checker opt-outs (with mandatory reason strings)
The two structural issues below have legitimate technical rationales that
predate the linter. Rather than restructure driver code as part of a lint
cleanup, added minimal file-level opt-outs to UnityBuildChecker:

1. **`UNITY_BUILD_EXCLUDE(<reason>)`** — declared in a `.cpp.hpp` file's
   first 15 lines. Marks the file as intentionally NOT part of the unity
   build. Applied to `i2s_peripheral_esp32dev_esp.cpp.hpp` whose Stage-4
   `driver/gpio.h` symbol set collides with the restored classic driver
   as `ADC: CONFLICT!` at boot. Design rationale is documented in the
   `_build.cpp.hpp` header comment; the marker points reviewers to it.

2. **`UNITY_BUILD_ORDER(<reason>)`** — declared in a `_build.cpp.hpp` file.
   Suppresses the alphabetical-order check for cases where compile-order
   dependency forces non-alphabetical include. Applied to
   `platforms/arm/lpc/drivers/sct_dma/_build.cpp.hpp` where
   `lpc_sct_dma_runtime.cpp.hpp` must precede `channel_engine_lpc_sct_dma.cpp.hpp`
   because the engine instantiates `LpcSctDmaTransmitter` (from runtime)
   as a data member.

Both markers require a non-empty reason argument so the rationale is
visible at every review site.

## Verification

- `bash lint --cpp`: ✅ All C++ linting checks passed
- `bash test --cpp`: 344/344 pass

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jul 1, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 1, 2026
pull Bot pushed a commit to manmuqingshan/FastLED that referenced this pull request Jul 28, 2026
…D#3484)

Last remaining namespace-scope static in allocator.cpp.hpp. The slab registry
(the ~1.5 KB .bss table this issue was mainly about) already moved in FastLED#3495;
this finishes the file.

Safe to call from inside Malloc()/Free(): Singleton<T>::instance()
placement-news into a static char buffer and never touches the heap, so
routing the hook lookup through it cannot recurse back into the allocator.
That property is why this is a Singleton and not a lazily-heap-allocated
holder.

Scope note: gMallocFreeHook sits inside `#if defined(FASTLED_TESTING)`, so it
never existed in firmware builds. This change is about removing the last
file-scope mutable static from the file, not about flash/RAM savings -- there
is no embedded bloat delta to show for it.

Co-Authored-By: Claude <[email protected]>
@zackees
zackees deleted the feat/singleton-elision-lint branch August 21, 2026 19:15
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.

Meta: migrate namespace-scope globals to fl::Singleton<T> for --gc-sections elision

1 participant