Skip to content

feat(lint): ban bare libm calls in src/; route power_mgt through fl:: - #3013

Merged
zackees merged 2 commits into
masterfrom
feat/bare-libm-checker
Jun 14, 2026
Merged

zackees merged 2 commits into
masterfrom
feat/bare-libm-checker

Conversation

@zackees

@zackees zackees commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

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 in src/.

  • New checker BareLibmChecker — 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 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. Old lroundf(powf(...)) anchored libm's full soft-FP chain on no-FPU targets. 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).

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 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.
  • CI: confirm LPC845 link flash gap closes the remaining 760-byte deficit.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added a standalone C++ lint checker to detect direct bare libm math calls and guide usage toward standardized math wrappers.
    • Integrated the new checker into the unified C++ linting run.
  • Bug Fixes
    • Improved JSON numeric conversion warnings/formatting in no-FPU builds by switching precision handling to float.
    • Clamped float→i64 conversions to the 32-bit signed range for safer conversions.
  • Chores
    • Updated power management LUT rebuild behavior for large-memory builds to use standardized math wrappers.

@coderabbitai

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Adds BareLibmChecker, a new CI lint checker that scans C++/header files under src/ for direct bare libm calls (e.g., sqrtf, atan2, ldexpf) using a compiled regex with comment-stripping and // ok libm suppression. The checker is registered in run_all_checkers.py, and src/power_mgt.cpp.hpp is updated to use fl::powf/fl::lroundf and conditionally include fl/math/math.h to comply. Additionally, JSON visitor conversions and int_conversion_visitor<i64> are updated to use float-based formatting and clamping instead of double promotion in no-FPU builds.

Changes

Bare libm lint enforcement

Layer / File(s) Summary
Banned function list, exemptions, and compiled regex
ci/lint_cpp/bare_libm_checker.py
Defines SRC_ROOT, exempt file/prefix lists, the full banned libm function name set, and the compiled regex that matches call sites while permitting fl:: prefixed variants.
BareLibmChecker implementation and standalone entrypoint
ci/lint_cpp/bare_libm_checker.py
Implements BareLibmChecker: file-filter logic, line scanning with comment-block skipping and // ok libm suppression, trailing-comment stripping before regex match, and violation recording. Adds main() wired to run_checker_standalone for .cpp/.h/.hpp under src/.
Register BareLibmChecker in global linter
ci/lint_cpp/run_all_checkers.py
Imports and appends BareLibmChecker() to the global checker list so it runs in the unified multi-checker pass over src/, examples/, and tests/.
power_mgt.cpp.hpp: replace bare powf/lroundf with fl:: wrappers
src/power_mgt.cpp.hpp
Guards fl/math/math.h and fl/stl/array.h inclusion under SKETCH_HAS_LARGE_MEMORY (removing unconditional <math.h>), and replaces powf/lroundf calls in the LUT rebuild loop with fl::powf/fl::lroundf.

Numeric JSON conversion precision fixes for no-FPU builds

Layer / File(s) Summary
Truncation checks and i64 clamping
src/fl/remote/rpc/json_visitors.h, src/fl/stl/json/types.h
JsonToIntegerVisitor changes truncation/overflow check from double-based round-trip to single-precision comparison. int_conversion_visitor<i64> clamps float input to int32 range and converts through i32 intermediate with ABI rationale comments.
Float formatting in JSON visitor conversions
src/fl/remote/rpc/json_visitors.h
JsonToBoolVisitor, JsonToFloatVisitor (bool and string overloads), and JsonToStringVisitor update warning/formatting to use fl::to_string with float precision instead of double conversion, eliminating double promotion.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • FastLED/FastLED#2715: Both PRs modify ci/lint_cpp/run_all_checkers.py to register additional CI lint checkers (main: BareLibmChecker, retrieved: PublicSettingsPatternChecker).

Poem

🐇 Hippity-hop through the math-land of C++,
No bare sqrtf or powf shall slip past my check!
With fl:: wrappers I wrap every call,
And the linter watches, guarding them all.
Comment // ok libm if you dare,
But the rabbit's regex is always aware! 🔍

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 primary change: introducing a linter to ban bare libm calls in src/ and updating power_mgt to use fl:: wrappers instead.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ 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/bare-libm-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 and usage tips.

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]>

@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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
ci/lint_cpp/bare_libm_checker.py (1)

181-184: 💤 Low value

Dead code: second condition in EXEMPT_PREFIXES check is ineffective.

The second condition norm.startswith(prefix) will never match when norm is an absolute file path (which is the case when paths come from collect_files_to_check). The first condition "/src/" + prefix in norm already 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3acd440 and 14780f9.

📒 Files selected for processing (3)
  • ci/lint_cpp/bare_libm_checker.py
  • ci/lint_cpp/run_all_checkers.py
  • src/power_mgt.cpp.hpp

Comment on lines +160 to +161
def __init__(self):
self.violations: dict[str, list[tuple[int, str]]] = {}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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

Comment on lines +196 to +211
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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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]>
@zackees
zackees force-pushed the feat/bare-libm-checker branch from 14780f9 to 1b68887 Compare June 14, 2026 02:53

@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)
src/fl/stl/json/types.h (2)

275-275: 💤 Low value

Redundant LL suffix when casting to i64.

static_cast<i64>(-2147483648LL) — the LL suffix is unnecessary because the static_cast<i64> already ensures the type. Using -2147483648 (or keeping LL for 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 value

Redundant cast on float literal.

static_cast<float>(-2147483648.0f) — the literal is already float due to the .0f suffix, so the static_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

📥 Commits

Reviewing files that changed from the base of the PR and between 14780f9 and 1b68887.

📒 Files selected for processing (5)
  • ci/lint_cpp/bare_libm_checker.py
  • ci/lint_cpp/run_all_checkers.py
  • src/fl/remote/rpc/json_visitors.h
  • src/fl/stl/json/types.h
  • src/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

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