Skip to content

fix(lint): port the real literal tokenizer to SingletonElisionChecker (#3486) - #3754

Merged
zackees merged 2 commits into
masterfrom
fix/3486-audio-detector-singleton
Jul 28, 2026
Merged

zackees merged 2 commits into
masterfrom
fix/3486-audio-detector-singleton

Conversation

@zackees

@zackees zackees commented Jul 28, 2026 •

Copy link
Copy Markdown
Member

Investigating #3486 (migrate fl/audio/detector state to fl::Singleton) showed that all 11 flagged sites in that directory were false positives. So this fixes the checker rather than performing the migration.

Why the migration was not performed

I implemented it first, then measured it. It is a regression on every axis it claims to improve:

  • Zero elision gained. Builds already pass -ffunction-sections -fdata-sections (ci/boards.py:795). A file-scope static int therefore lands in its own .bss section, and --gc-sections already drops it in sketches that never link the detector.
  • Strictly larger when the detector is used. Storage grows from one 4-byte object to aligned storage plus a T* (8-12 B), and each access site gains a null-check plus a cold placement-new tail — roughly +100-140 B flash on Thumb-2 -Os across the six sites.
  • Introduces an init data race. Singleton<T>::instance() hand-rolls if (!ptr) { ptr = new (&storage) T(); }, bypassing the C++11 magic-static guard. The old constant-initialized static had no init window at all. On ESP32 the audio task calling Vibe::update() and loop() calling getPrivateFFTCount() can both first-touch, both placement-new, and the second construction silently re-zeroes the counter.

The two diagnostic counters therefore stay plain statics, now carrying FL_LINT_ALLOW_GLOBAL with that rationale inline.

The actual defect

The checker's constexpr-triviality test used str::parse. Rust's numeric parsers reject both the 0x/0b prefixes and the C++ u/l/f suffixes, so ordinary constants were misreported as non-literal and flagged.

ci/scan_singleton_elision.py already contained a correct tokenizer (TRIVIAL_RHS_RE), and its docstring states it mirrors this checker — so this ports that regex over instead of re-deriving one.

Tree-wide violations drop 76 -> 39, entirely by removing false positives. src/platforms/arm/lpc/rx_sct_capture.cpp.hpp alone had 41 hex register masks flagged and is now clean — those are exactly the driver files the checker's own header comment says it was written for.

Also in this PR

  • const -> constexpr for the nine compile-time constants in equalizer.cpp.hpp / frequency_bands.cpp.hpp. No size change (they were already folded); this just states the intent.
  • FL_NO_EXCEPT on the four diagnostic accessors — fixes a decl/def mismatch in vibe.h and satisfies NoexceptAstChecker. FL_NO_EXCEPT is a documented no-op, so this is cosmetic.
  • First tests for this checker (it had none): 4 cases in lint_core/tests.rs, the home agents/docs/linter-architecture.md:109 prescribes, using its file() helper so paths get normalize_path. Covers the literal grammar, the allow-marker, and the third_party/header exclusions.
  • First coverage for getPrivateFFTCount/resetPrivateFFTCount. Delta form on purpose — the counter is process-wide and these headers link into a shared DLL alongside the other detector suites.

Verification

  • bash test --cpp --clean — 357/357 pass
  • bash lint — exit 0
  • Rust checker unit tests — 4/4 pass
  • Both new C++ tests mutation-checked (wrong expected value → they fail), because bash test --cpp audio builds fl_audio while these compile into fl_audio_detector_vibe / fl_audio_detectors.

Notes for the reviewer

  • singleton: migrate fl/audio/detector state (Tier 1c) #3486 should not be closed as "migrated." The finding generalizes: Singleton elision pays off for objects with dynamic initialization (whose .init_array entries resist gc), not for constant-initialized PODs. Several sibling issues under Meta: migrate namespace-scope globals to fl::Singleton<T> for --gc-sections elision #3481 target trivial scalars and likely warrant the same re-scoping. I did not change the checker's policy on those unilaterally.
  • Pre-existing, not fixed here: the Rust lint test suite fails rust_lint_source_files_stay_under_one_thousand_lines because checkers/unity_build.rs is 1205 lines. It is 1205 on master too.
  • Pre-existing latent bug, not fixed here: FrequencyBands::update() dereferences context with no null check, while the sibling Vibe::update() guards with if (!context) return;.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved detection of trivial compile-time constants across more numeric, symbolic, string, character, and shift-expression formats.
    • Added support for file- and comment-based lint exclusions.
    • Clarified which scanner provides authoritative lint results.
  • Refactor

    • Converted audio detector configuration values to compile-time constants.
    • Strengthened diagnostic counter APIs for reliable non-throwing behavior.
  • Tests

    • Expanded lint coverage for literal handling, exclusions, and file scoping.
    • Added coverage confirming FFT diagnostic counters increment and reset correctly.

…#3486)

Investigating #3486 (migrate fl/audio/detector state to fl::Singleton)
showed all 11 flagged sites in that directory were false positives, so
this fixes the checker instead of performing the migration.

Why the migration was not done:

- Builds already pass -ffunction-sections -fdata-sections (ci/boards.py
  :795). A file-scope `static int` therefore lands in its own .bss
  section and --gc-sections already drops it when the detector is not
  linked. Elision gained by wrapping it: 0 bytes.
- The Singleton form is strictly larger when the detector IS used:
  storage grows from one 4-byte object to aligned storage PLUS a `T*`,
  and every access gains a null-check and a cold placement-new tail.
- Singleton<T>::instance() hand-rolls `if (!ptr) { ptr = new(...) T(); }`,
  which bypasses the C++11 magic-static init guard. The old
  constant-initialized static had no init race; the wrapped form lets an
  ESP32 audio task and loop() both first-touch, both placement-new, and
  the second construction silently re-zero the counter.

So the two diagnostic counters stay plain statics, now carrying
FL_LINT_ALLOW_GLOBAL with that rationale.

The real defect was in the checker. Its constexpr-triviality test used
`str::parse`, but Rust's numeric parsers reject both the `0x`/`0b`
prefixes and the C++ `u`/`l`/`f` suffixes, so ordinary constants were
misreported as non-literal. `ci/scan_singleton_elision.py` already had a
correct tokenizer (TRIVIAL_RHS_RE) and its docstring says it mirrors this
checker, so that regex is ported over rather than re-derived. Tree-wide
violations drop 76 -> 39, entirely by removing false positives:
src/platforms/arm/lpc/rx_sct_capture.cpp.hpp alone had 41 hex register
masks flagged and is now clean.

Also:
- const -> constexpr for the nine compile-time constants in
  equalizer.cpp.hpp / frequency_bands.cpp.hpp (no size change; they were
  already folded, this just states the intent).
- FL_NO_EXCEPT on the four diagnostic accessors, fixing a decl/def
  mismatch in vibe.h and satisfying NoexceptAstChecker. FL_NO_EXCEPT is
  a documented no-op, so this is cosmetic.
- First tests for this checker: 4 cases in lint_core/tests.rs (the home
  linter-architecture.md prescribes), covering the literal grammar, the
  allow-marker, and the third_party/header exclusions.
- First coverage for the getPrivateFFTCount/resetPrivateFFTCount API.
  Delta form, since the counter is process-wide and these headers link
  into a shared DLL.

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 28, 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 Plus

Run ID: 00db8f76-078a-4a59-bb42-323789a13875

📥 Commits

Reviewing files that changed from the base of the PR and between 0c6356c and 0f110ea.

📒 Files selected for processing (9)
  • ci/lint_cpp_rs/src/checkers/singleton_elision.rs
  • ci/lint_cpp_rs/src/lint_core/tests.rs
  • ci/scan_singleton_elision.py
  • src/fl/audio/detector/equalizer.cpp.hpp
  • src/fl/audio/detector/frequency_bands.cpp.hpp
  • src/fl/audio/detector/frequency_bands.h
  • src/fl/audio/detector/vibe.cpp.hpp
  • tests/fl/audio/detector/frequency_bands.hpp
  • tests/fl/audio/detector/vibe.hpp

📝 Walkthrough

Walkthrough

The PR expands singleton-elision constexpr detection and opt-out handling, updates the accompanying Python scanner, converts audio detector constants to constexpr, marks diagnostic counter accessors FL_NO_EXCEPT, and adds counter tests.

Changes

Singleton elision checker

Layer / File(s) Summary
Trivial constexpr detection
ci/lint_cpp_rs/src/checkers/singleton_elision.rs, ci/lint_cpp_rs/src/lint_core/tests.rs
A cached regex recognizes additional literal-like constexpr RHS forms, with tests for accepted literals and rejected expressions.
Python scanner alignment
ci/scan_singleton_elision.py
The scanner broadens float matching, supports file and carried-line opt-out markers, and documents its non-authoritative status.
Checker path and marker coverage
ci/lint_cpp_rs/src/lint_core/tests.rs
Tests cover FL_LINT_ALLOW_GLOBAL and processing rules for third-party, checker-owned, and unrelated headers.

Audio detector constants and counters

Layer / File(s) Summary
Detector declarations and implementations
src/fl/audio/detector/equalizer.cpp.hpp, src/fl/audio/detector/frequency_bands.*, src/fl/audio/detector/vibe.cpp.hpp
Detector constants use constexpr; FFT counter accessors are marked FL_NO_EXCEPT, with updated counter comments.
Diagnostic counter tests
tests/fl/audio/detector/frequency_bands.hpp, tests/fl/audio/detector/vibe.hpp
Tests verify counter reset, reads, and increments during detector updates.

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

Sequence Diagram(s)

sequenceDiagram
  participant SourceFile
  participant SingletonElisionChecker
  participant LiteralMatcher
  SourceFile->>SingletonElisionChecker: check constexpr declaration
  SingletonElisionChecker->>LiteralMatcher: match RHS grammar
  LiteralMatcher-->>SingletonElisionChecker: trivial or non-trivial result
  SingletonElisionChecker-->>SourceFile: skip or report violation
Loading

Possibly related issues

Possibly related PRs

  • FastLED/FastLED#3752 — Both PRs modify SingletonElisionChecker behavior in the same implementation file.
✨ 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 fix/3486-audio-detector-singleton

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.

… the opt-out markers

Follow-up to review on #3754.

1. The comment on trivial_rhs_regex() cited
   `test_singleton_elision_rust_python_parity` as pinning the two
   implementations together. No such test exists -- the only match in the
   tree was that comment. Replaced with the real test names and an
   explicit statement that the grammars are kept in sync by hand.

2. ci/scan_singleton_elision.py recognized only [[gnu::used]] /
   __attribute__((used)) / FL_KEEP, so it re-reported the two counters
   this branch had just annotated with FL_LINT_ALLOW_GLOBAL. It also
   strips comments before testing for markers, which made the preferred
   preceding-comment form invisible. Added all three opt-out forms the
   Rust checker honors, matched off the raw line: inline,
   comment-carry-over, and the first-15-lines FL_LINT_ALLOW_GLOBAL_FILE.
   Python total 92 -> 62; fl/audio/detector now clean in both tools.

3. The float alternative missed exponent, trailing-dot, and long-double
   spellings, so `1e-6f`, `2.5e3f`, `10.f`, `1.5L` stayed false-positive
   in both. Widened in both regexes and pinned in the Rust test.

The two tools still disagree on the total (62 vs 39) because the Rust
checker carries skip heuristics this scanner lacks. Rather than claim a
parity that does not hold, the scanner docstring now states it is not
authoritative and points at the Rust checker as the enforcement path.

Co-Authored-By: Claude <[email protected]>
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