Skip to content

feat(lint): split integer constants out of SingletonElisionChecker into PreferConstexprChecker (#3483) - #3790

Merged
zackees merged 1 commit into
masterfrom
feat/3483-prefer-constexpr-checker
Jul 31, 2026
Merged

zackees merged 1 commit into
masterfrom
feat/3483-prefer-constexpr-checker

Conversation

@zackees

@zackees zackees commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Fixes #3483.

The conflation

SingletonElisionChecker reported two unrelated populations under one message:

int PRIORITY_PARLIO = 3;              // wants `constexpr`
QueueHandle_t s_esp_request_queue;    // wants `fl::Singleton<T>`

The advice differs, so the rules should. "Wrap it in fl::Singleton<T>" is strictly worse advice for an integer constant: the singleton hides storage behind a function-local static the linker may drop, while constexpr means the compiler inlines the value and there is no storage to drop at all.

Approach

Both rules now consume one shared scanner (scan_namespace_scope_decls) and partition its output through one predicate, so no declaration can be claimed by both or by neither. That scanner is the ~200 lines of brace-depth tracking, comment stripping and opt-out-marker handling that used to be inline in SingletonElisionChecker — a second copy would have drifted.

Two false-positive classes, both found by running it rather than reasoning

1. Mutable state that merely starts at a literal. bool sInitialized = false; matches "integral type bound to an integer literal" exactly like a real constant does. My first cut flagged 13 of these — SysTick flags, driver init flags, saved pin-mux values. constexpr bool sInitialized = false; does not compile the moment anything assigns to it, and it simultaneously stole the declaration from SingletonElisionChecker, where mutable state belongs. Now excluded by scanning for assignment, compound assignment and inc/dec.

2. State whose writes live in another translation unit. u8 gTimeErrorAccum256ths = 0; is the only mention of itself in its own file — every write happens in clockless_blocking.h, which also declares it extern. A per-file checker cannot see that. The rule now also reads the sibling header and treats an extern declaration or an assignment there as proof of shared mutable state.

Result on the tree, stated plainly

SingletonElisionChecker: 33 across 9 files — unchanged.
PreferConstexprChecker: 0.

That zero deserves explanation rather than burial. The issue predicted ~30 hits, but every example it cited has already been converted to constexpr since it was filed:

issue's example today
channel_manager_esp32.cpp.hpp — 14 × int PRIORITY_* 15 constexpr, no bare ints
equalizer.cpp.hpp — 6 × const int kBass* 7 constexpr
spi_hw_manager_rp.cpp.hpp — int PRIORITY_SPI_HW_8 3 constexpr

So the population the issue describes no longer exists. The rule's value here is (a) removing the wrong-advice conflation and (b) guarding against new instances — not a backlog of work. #3488, which is gated on this split, will therefore not shrink from it.

Tests are the evidence

Since there are no in-tree instances, the tests are the only proof the rule fires. They pin: the motivating shape; hex/binary/suffixed literals; both false-positive classes above; comparison-vs-assignment; whole-identifier matching; and — directly — that exactly one rule claims any given declaration.

One pre-existing test needed updating: singleton_elision_honors_allow_global_marker used static int sCounter = 0;, which after the split belongs to the new rule. Rather than swap the sample, it now asserts the partition itself (singleton_hits + constexpr_hits == 1), which is the stronger property.

Registered warn-only on both Rust and Python sides; ci/tests/test_warn_only_checkers_sync.py passes.

Verification

soldr cargo test: 52 pass. bash test --cpp green. ci/tests: 682 passed.

Pre-existing, not touched

  • rust_lint_source_files_stay_under_one_thousand_lines fails on unity_build.rs (1205 lines) — identical on unmodified master.
  • bash lint gates on a gitignored local scratch file (tmp.sh, matched by .gitignore:87) containing pio run -v. Same failure on master; CI never sees the file. That the C++ linter scans gitignored paths at all looks worth a separate look.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a C++ lint check that identifies eligible namespace-level integer variables that could use constexpr.
    • Added actionable diagnostics and support for common integer literal formats.
  • Bug Fixes

    • Improved declaration analysis and prevented overlapping reports with existing singleton checks.
  • Tests

    • Expanded coverage for valid candidates, exclusions, suppressions, and duplicate-report prevention.
  • Chores

    • Findings are reported as warnings without failing CI during rollout.

…to PreferConstexprChecker (#3483)

SingletonElisionChecker reported two unrelated populations under one message:

    int PRIORITY_PARLIO = 3;              // wants `constexpr`
    QueueHandle_t s_esp_request_queue;    // wants `fl::Singleton<T>`

The advice differs, so the rules should. "Wrap it in fl::Singleton<T>" is
strictly worse advice for an integer constant: the singleton hides storage
behind a function-local static the linker *may* drop, while `constexpr` means
the compiler inlines the value and there is no storage to drop.

Both rules now consume one shared scanner (`scan_namespace_scope_decls`) and
partition its output through one predicate, so no declaration can be claimed
by both or by neither. The scanner is the ~200 lines of brace-depth,
comment-stripping and opt-out-marker tracking that was previously inline in
SingletonElisionChecker; a second copy would have drifted.

Two false-positive classes had to be excluded, both found by running the rule
against the tree rather than by reasoning:

- **Mutable state that merely starts at a literal.** `bool sInitialized =
  false;` matches "integral type bound to an integer literal" exactly like a
  real constant. The first cut flagged 13 of these -- SysTick flags, driver
  init flags, saved pin-mux values. Advising `constexpr` there does not
  compile, and it simultaneously stole the declaration from
  SingletonElisionChecker where mutable state belongs. Now excluded by
  scanning for assignment, compound assignment and inc/dec.
- **State whose writes live in another translation unit.** `u8
  gTimeErrorAccum256ths = 0;` is the only in-file mention of itself; every
  write happens in `clockless_blocking.h`, which also declares it `extern`.
  A per-file checker cannot see that, so the rule also reads the sibling
  header and treats an `extern` declaration or an assignment there as proof
  of shared mutable state.

Net effect on the tree: SingletonElisionChecker still reports 33 across 9
files -- unchanged -- and PreferConstexprChecker reports 0.

That zero is the honest result, and worth stating plainly: the issue predicted
~30 hits, but every example it cited (`int PRIORITY_*` in
channel_manager_esp32, `const int kBassStart` in equalizer, `PRIORITY_SPI_HW_8`
in spi_hw_manager_rp) has already been converted to `constexpr` since it was
filed. Those files now carry 15, 7 and 3 `constexpr` declarations respectively.
The population the issue describes no longer exists, so the rule's value here
is as a guard against new ones plus removing the wrong-advice conflation --
not as a backlog of work.

Because there are no in-tree instances, the tests are the entire evidence that
the rule fires. They pin the motivating shape, hex/binary/suffixed literals,
the two false-positive classes above, comparison-vs-assignment, whole-identifier
matching, and -- directly -- that exactly one rule claims any given
declaration.

Registered warn-only on both the Rust and Python sides (kept in sync;
ci/tests/test_warn_only_checkers_sync.py asserts they match).

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

coderabbitai Bot commented Jul 31, 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: 3ff1d692-0fdb-4b74-86a3-f54604e97bba

📥 Commits

Reviewing files that changed from the base of the PR and between baf9ebc and 20c6e9a.

📒 Files selected for processing (7)
  • ci/lint_cpp/run_all_checkers.py
  • ci/lint_cpp_rs/src/checkers/prefer_constexpr.rs
  • 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/lint_cpp_rs/src/lint_core/tests.rs
  • ci/lint_cpp_rs/src/lint_core/warn_only.rs

📝 Walkthrough

Walkthrough

The PR adds PreferConstexprChecker for namespace-scope integral constants, shares declaration scanning with SingletonElisionChecker, registers the checker as warn-only, and adds coverage for detection, exclusions, suppression, and non-overlapping findings.

Changes

Prefer constexpr linting

Layer / File(s) Summary
Shared namespace-scope declaration scanning
ci/lint_cpp_rs/src/checkers/singleton_elision.rs
Namespace-scope declarations now produce structured records with parsed names, types, initializers, and constexpr status. The scanner handles opt-outs, namespaces, extern "C" blocks, comments, and declaration filtering.
PreferConstexprChecker implementation
ci/lint_cpp_rs/src/checkers/prefer_constexpr.rs, ci/lint_cpp_rs/src/checkers/singleton_elision.rs
The new checker identifies immutable integral variables initialized by supported integer literals and checks same-file and sibling-header mutations. SingletonElisionChecker excludes candidates handled by the new checker.
Checker registration and validation
ci/lint_cpp_rs/src/lib.rs, ci/lint_cpp_rs/src/lint_core/processor_registry_cli.rs, ci/lint_cpp_rs/src/lint_core/warn_only.rs, ci/lint_cpp/run_all_checkers.py, ci/lint_cpp_rs/src/lint_core/tests.rs
The checker is included in the crate, exposed by the CLI, and marked warn-only. Tests cover literal forms, mutable and non-integral exclusions, suppression, existing constexpr, and partitioning from singleton-elision findings.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant LintCLI
  participant PreferConstexprChecker
  participant scan_namespace_scope_decls
  participant SourceFiles
  LintCLI->>PreferConstexprChecker: create and run checker
  PreferConstexprChecker->>scan_namespace_scope_decls: scan namespace-scope declarations
  scan_namespace_scope_decls->>SourceFiles: read source files and sibling headers
  SourceFiles-->>scan_namespace_scope_decls: declarations and assignments
  scan_namespace_scope_decls-->>PreferConstexprChecker: structured declarations
  PreferConstexprChecker-->>LintCLI: constexpr diagnostics
Loading

Possibly related PRs

  • FastLED/FastLED#3752: Directly extends the warn-only configuration and shared declaration-scanning infrastructure.
  • FastLED/FastLED#3754: Also modifies SingletonElisionChecker and related constexpr and literal tests.
✨ 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/3483-prefer-constexpr-checker

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.

@fastled-project-sync fastled-project-sync Bot moved this to Triage in FastLED Tracker Jul 31, 2026
@zackees
zackees merged commit 26cc458 into master Jul 31, 2026
11 of 12 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jul 31, 2026
@zackees
zackees deleted the feat/3483-prefer-constexpr-checker branch July 31, 2026 23:08
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.

lint: split integer-constant globals into PreferConstexprChecker

1 participant