Repository navigation
feat(lint): ban bare libm calls in src/; route power_mgt through fl:: - #3013
Conversation
📝 WalkthroughWalkthroughAdds ChangesBare libm lint enforcement
Numeric JSON conversion precision fixes for no-FPU builds
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
Add `BareLibmChecker` (PR #3012, issue #3002): bans direct `::sqrtf`, `::atan2`, `::powf`, `::ldexpf`, etc. in `src/`, forcing new code to go through `fl::sqrt(x)` / `fl::atan2(y, x)` / ... — which on Low-memory targets route to hand-rolled polynomial / Newton-Raphson approximations rather than dragging libm + libgcc soft-FP into the link. Exemptions: - `fl/math/math.cpp.hpp` / `math.h` — the compat shim itself. - `src/third_party/` — upstream code we don't control. - Pre-existing heavy users staged for migration (fl/audio, fl/fx, fl/gfx, fl/math/{fixed_point,line_simplification,screenmap,transform}, platforms/esp, platforms/wasm). The discipline this checker enforces is "no NEW code that imports libm directly"; the existing subsystems (audio FFT in particular needs full IEEE 754) will be ported through fl:: over a series of focused refactors. Suppression: `// ok libm` at end of line to whitelist a specific call. Fix `src/power_mgt.cpp.hpp:87` — the actual LPC845-BRK blocker. The old `lroundf(powf(normalized, exponent) * 255.0f)` anchored libm's full soft-FP chain on no-FPU targets even though everything else already routes through fl::math. Now uses `fl::powf` / `fl::lroundf` (the float overloads — fl::pow takes double, so passing floats would auto-promote and re-anchor double-precision soft-FP). Co-Authored-By: Claude Opus 4.7 <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
ci/lint_cpp/bare_libm_checker.py (1)
181-184: 💤 Low valueDead code: second condition in EXEMPT_PREFIXES check is ineffective.
The second condition
norm.startswith(prefix)will never match whennormis an absolute file path (which is the case when paths come fromcollect_files_to_check). The first condition"/src/" + prefix in normalready handles the exemption check correctly. The second condition can be removed to clarify intent.♻️ Proposed refactor
for prefix in EXEMPT_PREFIXES: - # Match `src/<prefix>` anywhere in the normalized path. - if "/src/" + prefix in norm or norm.startswith(prefix): + # Match `src/<prefix>` anywhere in the normalized path. + if "/src/" + prefix in norm: return False🤖 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 `@ci/lint_cpp/bare_libm_checker.py` around lines 181 - 184, The second condition `norm.startswith(prefix)` in the EXEMPT_PREFIXES loop is dead code that will never execute because `norm` is always an absolute file path, so it cannot start with a bare prefix. Remove the `or norm.startswith(prefix)` part of the condition, keeping only the first check `if "/src/" + prefix in norm` which correctly handles the exemption logic for absolute paths.
🤖 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 `@ci/lint_cpp/bare_libm_checker.py`:
- Around line 196-211: The code on line 210 only strips trailing `//` comments
using `line.split("//")[0]`, but single-line `/* ... */` block comments are not
removed before the regex matching. This causes false positives when code
contains trailing block comments like `return sqrtf(x); /* TODO: migrate */`.
Modify the comment-stripping logic to remove both `//` and `/* ... */` style
trailing comments from the code variable before the _BANNED_PATTERN regex search
is performed.
- Around line 160-161: The `__init__` method is missing an explicit return type
annotation. Add `-> None` as the return type annotation to the `__init__` method
signature to comply with the coding guidelines requiring explicit return type
annotations on all functions and methods.
---
Nitpick comments:
In `@ci/lint_cpp/bare_libm_checker.py`:
- Around line 181-184: The second condition `norm.startswith(prefix)` in the
EXEMPT_PREFIXES loop is dead code that will never execute because `norm` is
always an absolute file path, so it cannot start with a bare prefix. Remove the
`or norm.startswith(prefix)` part of the condition, keeping only the first check
`if "/src/" + prefix in norm` which correctly handles the exemption logic for
absolute paths.
🪄 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: 983e35d0-c11f-4044-9818-7d728872e3ef
📒 Files selected for processing (3)
ci/lint_cpp/bare_libm_checker.pyci/lint_cpp/run_all_checkers.pysrc/power_mgt.cpp.hpp
| def __init__(self): | ||
| self.violations: dict[str, list[tuple[int, str]]] = {} |
There was a problem hiding this comment.
Add return type annotation to __init__.
The __init__ method is missing an explicit return type annotation. As per coding guidelines, all function return types must have explicit type annotations.
📝 Proposed fix
- def __init__(self):
+ def __init__(self) -> None:
self.violations: dict[str, list[tuple[int, str]]] = {}🤖 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 `@ci/lint_cpp/bare_libm_checker.py` around lines 160 - 161, The `__init__`
method is missing an explicit return type annotation. Add `-> None` as the
return type annotation to the `__init__` method signature to comply with the
coding guidelines requiring explicit return type annotations on all functions
and methods.
Source: Coding guidelines
| if in_block_comment: | ||
| if "*/" in line: | ||
| in_block_comment = False | ||
| continue | ||
| if "/*" in line and "*/" not in line: | ||
| in_block_comment = True | ||
| continue | ||
|
|
||
| if stripped.startswith("//"): | ||
| continue | ||
| if _SUPPRESS in line: | ||
| continue | ||
|
|
||
| # Strip trailing // comment so the regex doesn't match inside it. | ||
| code = line.split("//")[0] | ||
| if _BANNED_PATTERN.search(code): |
There was a problem hiding this comment.
Single-line /* ... */ block comments are not stripped before regex matching.
The comment on lines 194-195 claims that single-line /* ... */ comments are handled by the trailing-comment strip on line 210, but that line only strips // comments using line.split("//")[0]. This means code like:
return sqrtf(x); /* TODO: migrate to fl::sqrtf */will trigger a false positive because the regex will match sqrtf( inside the /* ... */ comment portion. Consider stripping both // and /* ... */ style trailing comments before the regex match.
🔧 Proposed fix to strip single-line block comments
if _SUPPRESS in line:
continue
- # Strip trailing // comment so the regex doesn't match inside it.
- code = line.split("//")[0]
+ # Strip trailing // and /* ... */ comments so the regex doesn't match inside them.
+ code = line.split("//")[0]
+ if "/*" in code and "*/" in code:
+ code = code[:code.index("/*")]
if _BANNED_PATTERN.search(code):Note: This simple fix handles the most common case. A more robust solution would use a proper C++ tokenizer, but that's likely overkill for this linter.
🤖 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 `@ci/lint_cpp/bare_libm_checker.py` around lines 196 - 211, The code on line
210 only strips trailing `//` comments using `line.split("//")[0]`, but
single-line `/* ... */` block comments are not removed before the regex
matching. This causes false positives when code contains trailing block comments
like `return sqrtf(x); /* TODO: migrate */`. Modify the comment-stripping logic
to remove both `//` and `/* ... */` style trailing comments from the code
variable before the _BANNED_PATTERN regex search is performed.
…link Last 692 B of the LPC845-BRK flash deficit (FastLED #3002) came from a chain that started innocently and ended in libgcc's full soft-double set: int_conversion_visitor<i64>::operator()(const float& value) result = static_cast<i64>(value); // <-- __aeabi_f2lz // ↓ _fixsfdi.o → __aeabi_f2ulz // ↓ _fixunssfdi.o → __aeabi_dmul, __aeabi_dsub // ~6 KB of soft-double The cast is reached through `json_value::as_int()`, which `fl::Remote` calls on every incoming RPC to read the request `id` and `timestamp`. Even though the variant only holds `float` (not `double` — see types.h:652), one tag in the variant is enough to instantiate the visitor's float overload and pull in the chain. Fix: route (i64)(float) through (i32)(float) when the value is in range (saturates otherwise). The variant only ever holds float and JSON integers from any sane RPC payload fit in int32, so this is a no-behavior-change refactor for the realistic input set, but it lowers libgcc's chosen helper from `__aeabi_f2lz` (which uses double) to `__aeabi_f2iz` (which doesn't). Also strip the gratuitous `static_cast<double>(...)` casts from the JsonToIntegerVisitor / JsonToBoolVisitor / JsonToFloatVisitor / JsonToStringVisitor warning-formatting paths — they each pulled in `__aeabi_dcmpeq` / `__ledf2` / `__gedf2` / `__aeabi_d2f` for no diagnostic benefit (float has more than enough precision for a "truncated to int" warning string). After: ❯ arm-none-eabi-size firmware.elf text data bss 63088 372 8336 (~2 KB flash headroom on a 64 KB part) Refs: #3002, #3012, #3013. Co-Authored-By: Claude Opus 4.7 <[email protected]>
14780f9 to
1b68887
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (2)
src/fl/stl/json/types.h (2)
275-275: 💤 Low valueRedundant
LLsuffix when casting toi64.
static_cast<i64>(-2147483648LL)— theLLsuffix is unnecessary because thestatic_cast<i64>already ensures the type. Using-2147483648(or keepingLLfor clarity) both work, but the cast makes the suffix redundant.♻️ Simplify by removing redundant suffix
- result = static_cast<i64>(-2147483648LL); + result = static_cast<i64>(-2147483648);🤖 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/stl/json/types.h` at line 275, Remove the redundant `LL` suffix from the literal in the static_cast expression. The cast to `i64` already ensures the proper type conversion, making the `LL` suffix on `-2147483648` unnecessary. Simply change `-2147483648LL` to `-2147483648` in the static_cast<i64>() call to improve code clarity.
274-274: 💤 Low valueRedundant cast on float literal.
static_cast<float>(-2147483648.0f)— the literal is alreadyfloatdue to the.0fsuffix, so thestatic_cast<float>is redundant.♻️ Simplify by removing redundant cast
- } else if (value < static_cast<float>(-2147483648.0f)) { + } else if (value < -2147483648.0f) {🤖 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/stl/json/types.h` at line 274, Remove the redundant `static_cast<float>()` wrapper around the literal `-2147483648.0f` in the comparison expression. Since the literal already has the `.0f` suffix, it is explicitly typed as a float, making the cast unnecessary. Simply replace `static_cast<float>(-2147483648.0f)` with `-2147483648.0f` in the condition.
🤖 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 `@src/fl/stl/json/types.h`:
- Line 275: Remove the redundant `LL` suffix from the literal in the static_cast
expression. The cast to `i64` already ensures the proper type conversion, making
the `LL` suffix on `-2147483648` unnecessary. Simply change `-2147483648LL` to
`-2147483648` in the static_cast<i64>() call to improve code clarity.
- Line 274: Remove the redundant `static_cast<float>()` wrapper around the
literal `-2147483648.0f` in the comparison expression. Since the literal already
has the `.0f` suffix, it is explicitly typed as a float, making the cast
unnecessary. Simply replace `static_cast<float>(-2147483648.0f)` with
`-2147483648.0f` in the condition.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: d38dee93-591f-4dcf-9d21-68604dc1ebf0
📒 Files selected for processing (5)
ci/lint_cpp/bare_libm_checker.pyci/lint_cpp/run_all_checkers.pysrc/fl/remote/rpc/json_visitors.hsrc/fl/stl/json/types.hsrc/power_mgt.cpp.hpp
🚧 Files skipped from review as they are similar to previous changes (3)
- src/power_mgt.cpp.hpp
- ci/lint_cpp/run_all_checkers.py
- ci/lint_cpp/bare_libm_checker.py
Summary
Follow-up to #3012 (libm-free
fl::math). Adds the lint discipline that keeps that gate honest, and migrates the last remaining direct libm caller insrc/.BareLibmChecker— bans direct::sqrtf/::atan2/::powf/::ldexpf/ etc. insrc/, forcing new code to go throughfl::sqrt(x)/fl::atan2(y, x)/ ... — which on Low-memory targets routes to hand-rolled polynomial / Newton-Raphson approximations rather than dragging libm + libgcc soft-FP into the link.src/power_mgt.cpp.hpp:87— the actual LPC845-BRK blocker. Oldlroundf(powf(...))anchored libm's full soft-FP chain on no-FPU targets. Now usesfl::powf/fl::lroundf(the float overloads —fl::powtakesdouble, so passing floats would auto-promote and re-anchor double-precision soft-FP).Exemptions
fl/math/math.cpp.hpp/math.h— the compat shim itself.src/third_party/— upstream code we don't control.fl/audio,fl/fx,fl/gfx,fl/math/{fixed_point,line_simplification,screenmap,transform},platforms/esp,platforms/wasm. The discipline this checker enforces is "no NEW code that imports libm directly"; the existing subsystems (audio FFT in particular needs full IEEE 754) will be ported throughfl::over a series of focused refactors.Suppression:
// ok libmat end of line whitelists a specific call.Refs: #3002, #3012.
Test plan
uv run python ci/lint_cpp/bare_libm_checker.py— no violations.uv run python ci/lint_cpp/run_all_checkers.py— full lint suite passes.bash test fl/math/math.cpp --cpp— host math tests pass.bash test power --cpp— power_mgt host tests pass with float overloads.🤖 Generated with Claude Code
Summary by CodeRabbit
libmmath calls and guide usage toward standardized math wrappers.float.float→i64conversions to the 32-bit signed range for safer conversions.