Skip to content

docs(cpp): add 8 code-gen rules from 2-week CodeRabbit survey (closes #2717) - #2718

Merged
zackees merged 3 commits into
masterfrom
chore/cpp-style-coderabbit-survey-2week-rules
Jun 4, 2026
Merged

zackees merged 3 commits into
masterfrom
chore/cpp-style-coderabbit-survey-2week-rules

Conversation

@zackees

@zackees zackees commented Jun 3, 2026 •

Copy link
Copy Markdown
Member

Closes #2717.

Summary

Surveyed CodeRabbit's findings across 94 PRs updated 2026-05-20 → 2026-06-03 (59 with CodeRabbit activity, ~95 substantive findings examined). Adds 8 new rules to agents/docs/cpp-standards.md capturing the recurring themes that are preventable at code-generation time by a written rule.

See issue #2717 for the full survey methodology, raw statistics, and the dropped recommendations.

Rules added (in order, append-only)

# Rule Findings prevented
1 Singleton-Stored Configuration: own by value, never borrowed pointer #2554, #2560, #2588, #2683, #2682
2 In-Place Profile Mutation Bumps a Version (cache invalidation) #2554, #2589, #2707, #2711
3 Contract Change Fanout (broadens existing API Unit Change rule) #2621, #2648, #2669, #2682
4 fl::span for Callback Typedefs and Small Fixed-Size Arrays #2560, #2683, #2711
5 ISR-Shared State: fl::atomic or Critical Section, Never Bare volatile #2682, #2703
6 Unsigned Narrowing Cast Must Clamp #2560 (×2)
7 Test Mirrors Must Call Production Symbols, Not Redeclare Them #2683, #2707, #2709
8 ASCII-Only in Source Files #2648, #2709

Key design notes

Test plan

Related PRs

No textual conflict with #2715 / #2716 — they edit different files (code_review.md, architecture-reviewer-agent.md, .coderabbit.yaml, src/FastLED.h, ci/lint_cpp/) and a different section of cpp-standards.md (Public Settings Pattern is appended above Naming Conventions; this PR appends below). Whichever lands second will merge cleanly.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Documentation
    • Updated C++ coding standards: rules for value-owned configuration, cache-invalidation on in-place mutation, coordinated PR updates for contract changes, stricter callback/array typedef guidance, atomic/shared-state ordering requirements, numeric clamping before unsigned narrowing, test mirror usage, and ASCII-only code content.
  • Chores
    • Minor platform header/include compatibility updates for ESP32 builds.

Closes #2717.

Adds 8 new rules to agents/docs/cpp-standards.md capturing the recurring
themes CodeRabbit flagged across 94 PRs (2026-05-20 → 2026-06-03, 59
with CodeRabbit activity, ~95 substantive findings). All 8 are
preventable at code-generation time with a written rule.

Rules added (in order, append-only at end of file):

1. Singleton-Stored Configuration: Own by Value, Never by Borrowed
   Pointer — prevents use-after-scope when callers pass a stack
   temporary to a `set_X(const T*)` that stashes the pointer in process
   state. Pairs with the Public Settings Pattern (PR #2715 — where the
   setter lives; this rule — how it stores the value).

2. In-Place Profile Mutation Bumps a Version — cache-invalidation
   contract for `set_X(T* obj, ...)` patterns. Without a version bump
   and key, derived-value caches keyed on `(obj_ptr, ...)` return
   stale data when the same pointer is mutated across frames.

3. Contract Change Fanout — broadens the existing "API Unit Change"
   rule (§595-604) from `_ms` / `_us` suffixes to any bound, enum
   range, or struct shape change. PRs must touch producer +
   validator + tests + docs + debug-metrics in one diff.

4. `fl::span` for Callback Typedefs and Small Fixed-Size Arrays —
   extends the existing span rule with two shapes that kept slipping
   through: `fl::function<...(const u8*, size_t)>` typedefs and
   `const float xy[2]` fixed-size arrays.

5. ISR-Shared State: `fl::atomic` or Critical Section, Never Bare
   `volatile` — uses `fl::atomic<T>` (not `std::atomic`, per the
   project-wide "prefer fl:: over std::" rule) with explicit memory
   order, OR `portENTER_CRITICAL_ISR` guarded access. Plain `volatile`
   is not sufficient on dual-core MCUs.

6. Unsigned Narrowing Cast Must Clamp — sibling to the existing
   Signed Integer Overflow rule. `static_cast<u8>(x)` wraps silently
   when x > 255 — defined behavior, wrong behavior. The signed-UB
   rule explicitly does NOT cover this case.

7. Test Mirrors Must Call Production Symbols, Not Redeclare Them —
   local lambda re-implementations in test files silently pass when
   the production code regresses. Test must `#include` and call the
   production symbol.

8. ASCII-Only in Source Files — emoji and Unicode math glyphs
   (`⚠️`, `×`, `−`, `ρ`, `∆`) in C++ comments and Python source
   confuse toolchains and obscure compile errors. Markdown (`*.md`)
   files exempt.

Rule dropped from the original recommendation: mirror the
KeyboardInterrupt pattern into `agents/docs/python-standards.md` — on
inspection the rule is already present there at lines 17-46. The
recurring violations come from agents reading other docs first; that
is a discovery problem, not a documentation gap.

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

coderabbitai Bot commented Jun 3, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 773a2e92-aff0-4b4e-8ea4-e80a0352c4a1

📥 Commits

Reviewing files that changed from the base of the PR and between 9b14b30 and 18f7426.

📒 Files selected for processing (1)
  • agents/docs/cpp-standards.md
✅ Files skipped from review due to trivial changes (1)
  • agents/docs/cpp-standards.md

📝 Walkthrough

Walkthrough

Adds eight C++ coding-standard rules to documentation addressing ownership, cache contracts, contract-change fanout, span usage, ISR/shared-state, unsigned narrowing casts, test mirroring, and ASCII-only sources; also adds conditional FreeRTOS includes to an ESP32 LCD SPI driver header.

Changes

C++ Standards Documentation

Layer / File(s) Summary
API contract and memory safety
agents/docs/cpp-standards.md
Singleton-stored configuration must copy values (no retained borrowed pointers); in-place mutation APIs must bump/invalidate cache versions; contract changes must update producer, validator, tests, docs, and metrics together; fl::span guidance extended to forbid (ptr,size) callbacks and raw fixed-size array parameters.
Concurrency and numeric correctness
agents/docs/cpp-standards.md
ISR-shared state must use fl::atomic with explicit memory ordering or critical-section guards (forbids volatile and std::atomic). Unsigned narrowing casts must clamp/saturate before narrowing (e.g., u8, u16).
Test practices and code hygiene
agents/docs/cpp-standards.md
Tests must invoke production symbols rather than redeclaring algorithms (except for explicit byte-for-byte mirror checks). C++ and Python source files must be 7-bit ASCII; non-ASCII glyphs are disallowed in code/comments.

ESP32 driver include

Layer / File(s) Summary
FreeRTOS includes in LCD SPI driver
src/platforms/esp/32/drivers/lcd_spi/channel_driver_lcd_clockless.cpp.hpp
Adds conditional includes for freertos/FreeRTOS.h and freertos/task.h under the ESP32 guard and marks them with IWYU keep pragmas.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

I'm a rabbit in the code tonight,
I pen eight rules to keep things tight,
Caches bump when setters change the plot,
Atoms stand guard, narrow casts are not,
Small includes tucked in, all set right.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR includes a minor out-of-scope change: adding FreeRTOS includes with IWYU pragmas to channel_driver_lcd_clockless.cpp.hpp, which is unrelated to the primary documentation objective of adding C++ code-generation rules. Remove the unrelated FreeRTOS include changes from channel_driver_lcd_clockless.cpp.hpp or merge into a separate PR focused on include management, keeping this PR documentation-only.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main change: adding 8 C++ code-generation rules to documentation derived from a CodeRabbit survey, directly corresponding to the changeset.
Linked Issues check ✅ Passed The PR successfully implements all 8 rules specified in issue #2717 (singleton ownership, cache invalidation, contract fanout, fl::span extension, ISR-shared state, unsigned narrowing casts, test mirrors, ASCII-only content) with proper documentation style and survey rationale.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch chore/cpp-style-coderabbit-survey-2week-rules

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.

🧹 Nitpick comments (2)
agents/docs/cpp-standards.md (2)

273-276: ⚡ Quick win

Document scoped exception for deferred callback-shape migrations.

This rule is good as the default, but it should explicitly allow documented temporary exceptions for legacy layers that require full-layer atomic migration (to avoid one-off typedef churn and inconsistent handler APIs).

Based on learnings: In src/fl/stl/cstdio.h, raw pointer+length handler signatures are intentionally retained until a full-layer sweep.

🤖 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 `@agents/docs/cpp-standards.md` around lines 273 - 276, Update the
cpp-standards.md rule `#1` to explicitly allow a documented, scoped exception for
legacy layers that cannot migrate typedefs atomically: add a short paragraph
after the rule stating that temporary exceptions are permitted when a full-layer
sweep is required, and require the exception to be recorded in the codebase
(e.g., a comment pointing to the migration plan) and to reference the legacy
location (for example src/fl/stl/cstdio.h) where raw pointer+length handlers are
intentionally retained; mention the requirement that such exceptions be
timeboxed and revisited during the next layer migration to avoid permanent
divergence.

193-219: ⚡ Quick win

Clarify nullable-reset exception for singleton setters.

The hard “MUST take const T&” wording conflicts with established copy-by-value setters that accept const T* only to support nullptr reset semantics (while still never storing the pointer). Please add a narrow exception so this rule enforces ownership without banning valid reset APIs.

Suggested wording tweak
-**Core Principle**: Any public `fl::set_*` API that stores a configuration profile / settings object in process-wide (or static / namespace-scope) state MUST take the value `const T&` and **copy** it.
+**Core Principle**: Any public `fl::set_*` API that stores a configuration profile / settings object in process-wide (or static / namespace-scope) state MUST store by value (copy/move) and never retain caller-owned pointers.
+Setter parameters should prefer `const T&` (or `T&&`), except when `nullptr` is explicitly used as a reset signal; in that case, pointer-taking APIs are allowed only if they immediately copy on non-null and never store the pointer.

Based on learnings: “Read cpp-standards.md for writing/editing C++ code or creating API wrapper types.”

🤖 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 `@agents/docs/cpp-standards.md` around lines 193 - 219, Update the rule text
for fl::set_* setters to add a narrow exception allowing APIs that accept a
const T* only to express nullable-reset semantics, but require that such setters
never store the raw pointer and instead copy/move the pointed-to value into the
library-owned storage (or clear it when nullptr); in practice change the Rule 1
wording and the Check Process to state that a const T* parameter is acceptable
only if the implementation of the setter (e.g. set_rgbww_colorimetric_profile)
copies the pointed-to value into a value-typed namespace/static slot or resets
that owned slot on nullptr, and flag as HIGH only when both the parameter and
the storage are raw const T* (i.e., the pointer itself is stored).
🤖 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.

Nitpick comments:
In `@agents/docs/cpp-standards.md`:
- Around line 273-276: Update the cpp-standards.md rule `#1` to explicitly allow a
documented, scoped exception for legacy layers that cannot migrate typedefs
atomically: add a short paragraph after the rule stating that temporary
exceptions are permitted when a full-layer sweep is required, and require the
exception to be recorded in the codebase (e.g., a comment pointing to the
migration plan) and to reference the legacy location (for example
src/fl/stl/cstdio.h) where raw pointer+length handlers are intentionally
retained; mention the requirement that such exceptions be timeboxed and
revisited during the next layer migration to avoid permanent divergence.
- Around line 193-219: Update the rule text for fl::set_* setters to add a
narrow exception allowing APIs that accept a const T* only to express
nullable-reset semantics, but require that such setters never store the raw
pointer and instead copy/move the pointed-to value into the library-owned
storage (or clear it when nullptr); in practice change the Rule 1 wording and
the Check Process to state that a const T* parameter is acceptable only if the
implementation of the setter (e.g. set_rgbww_colorimetric_profile) copies the
pointed-to value into a value-typed namespace/static slot or resets that owned
slot on nullptr, and flag as HIGH only when both the parameter and the storage
are raw const T* (i.e., the pointer itself is stored).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: dcdc517f-5f31-45bf-acdc-9da831aaba1e

📥 Commits

Reviewing files that changed from the base of the PR and between ca258f4 and 561181f.

📒 Files selected for processing (1)
  • agents/docs/cpp-standards.md

zackees and others added 2 commits June 3, 2026 16:37
…agma keep

Same pre-existing IWYU violation as on PR #2715 — this branch was cut
from master before that fix landed, so the linter flags it again. Same
one-line fix: `// IWYU pragma: keep` on each freertos system header.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two "Quick win" nitpicks from CodeRabbit on the survey-rules PR:

1. **Rule 1 (Singleton-Stored Configuration)** — softens the "MUST take
   const T&" wording to allow `const T*` parameters when the pointer
   is used as a nullable-reset signal (nullptr → revert to default).
   The existing `set_rgbww_colorimetric_profile(const T*)` is the
   in-repo example of this idiom; it copies on non-null and resets on
   null, which is correct even though the parameter shape is `T*`.
   The HIGH-severity flag now fires only when BOTH parameter and
   storage are `const T*` (the actual use-after-scope shape).

2. **Rule 4 (`fl::span` for callback typedefs)** — adds a scoped
   exception for deferred legacy migrations. A `(ptr, size)` typedef
   may be retained temporarily when migrating all callers in one PR
   isn't tractable, provided the typedef site carries a comment
   pointing at the tracking issue and the exception is timeboxed.
   Cited example: `src/fl/stl/cstdio.h`. Without this carve-out the
   rule would push engineers toward unprincipled mixed APIs.

Both rules remain "use value semantics / spans by default" — the
exceptions are explicit, documented, and bounded.

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

zackees commented Jun 3, 2026

Copy link
Copy Markdown
Member Author

Addressed both CodeRabbit nitpicks in commit 18f7426:

Rule 1 (Singleton-Stored Configuration) — added a nullable-reset exception. const T* parameters are now permitted IF the storage is value-typed AND the body copies on non-null + resets on null. Added a third "✅ Good" example showing the set_rgbww_colorimetric_profile(const T*) shape as the canonical idiom for "pass nullptr to revert." The HIGH-severity flag now fires only when BOTH parameter and storage are const T* (the actual use-after-scope shape).

Rule 4 (fl::span for callback typedefs) — added a "Scoped exception — deferred legacy migrations" subsection. (ptr, size) typedefs may be temporarily retained in legacy layers when migrating every caller in one PR isn't tractable, with three requirements: (a) typedef-site comment pointing at the tracking issue, (b) named legacy location (e.g. src/fl/stl/cstdio.h), (c) timeboxed to the next layer-wide migration window.

Both defaults remain "value semantics / spans"; the exceptions are explicit, documented, and bounded.

@zackees
zackees merged commit cf80f80 into master Jun 4, 2026
5 checks passed
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 4, 2026
zackees added a commit that referenced this pull request Jun 4, 2026
… form

#2718 also touched the FreeRTOS-include block in lcd_spi/channel_driver_lcd_clockless.cpp.hpp
and picked the inline `// IWYU pragma: keep` form (cleaner than the
`begin_keep`/`end_keep` wrapper this branch had added as a drive-by).
Taking master's resolution; both forms satisfy the same lint check and
master is the canonical style.
@zackees
zackees deleted the chore/cpp-style-coderabbit-survey-2week-rules 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.

Add 8 new C++ code-gen rules to cpp-standards.md from 2-week CodeRabbit survey

1 participant