Skip to content

feat(json): gate float out of variant on FL_JSON_HAS_FLOAT=0 (#3022 phase 1) - #3027

Closed
zackees wants to merge 2 commits into
masterfrom
feat/3022-json-no-float
Closed

zackees wants to merge 2 commits into
masterfrom
feat/3022-json-no-float

Conversation

@zackees

@zackees zackees commented Jun 14, 2026 •

Copy link
Copy Markdown
Member

Summary

Phase 1 of #3022. Eliminates ~13 KB of libgcc soft-FP cascade from the LPC845 / no-FPU ARM fl::json code path by gating the float and fl::vector<float> alternatives out of json_value::variant_t when FL_JSON_HAS_FLOAT=0 (defaults to FL_PLATFORM_HAS_LARGE_MEMORY, the canonical name from #3019 / #3000).

Closes #3022 (phase 1 — the structural gate). The fl::json_number packed-tagged-union design from the issue body lands in phase 2; see the in-flight design-clarification comment for the parser-truncation placeholder.

Verification (LPC845-BRK, examples/AutoResearchLpc/AutoResearchLpc.ino)

Metric Before After Δ
text 64 204 B 51 280 B −12 924 B
Flash usage 64.20 / 64.00 KB (~98 %) 50.44 / 64.00 KB (78.8 %) +13.6 KB margin
__aeabi_d* / __aeabi_f* symbols dadd, dmul, d2f, fadd, fsub, fmul, fdiv, fcmp*, f2iz, __eqsf2 none —

Verification command (now documented in CLAUDE.md):

fbuild build -e lpc845brk
arm-none-eabi-nm -C .fbuild/build/lpc845brk/release/firmware.elf \
  | grep -E '(aeabi_d|aeabi_f|__[gle]q?[ds]f|scalbn|lround|fmod|atan|acos)'
# (empty output — goal met)

Or via fbuild's wrapper that auto-resolves the cross nm/c++filt from build_info.json:

fbuild symbols .fbuild/build/lpc845brk/release/firmware.elf

What changed

  • FL_JSON_HAS_FLOAT macro in fl/stl/json/types.h, defaulting to FL_PLATFORM_HAS_LARGE_MEMORY. Users can force -DFL_JSON_HAS_FLOAT=1 on a Low-memory part to re-enable floats (paying the soft-FP cost).
  • Variant gating: float and fl::vector<float> drop out of variant_t on FL_JSON_HAS_FLOAT=0. All visit_fn<float, Visitor> instantiations vanish, breaking the chain that pulled the unused operator()(const float&) visitor overloads (and their FP arithmetic) into the link.
  • Parser gating in fl/stl/json.cpp.hpp: JsonTokenizer::scan_array_lookahead, JsonBuilder::parse_float_array, JsonToken::ARRAY_FLOAT, JsonToken::NUMBER (float path), canBeRepresentedAsFloat(double), optimize_array's ALL_FLOATS arm, classify_array's has_float check. fl::parseFloat is no longer reachable.
  • Public constructors preserved. json(float) / json(double) / operator= / set(key, float) stay available; on FL_JSON_HAS_FLOAT=0 the library takes over the conversion by truncating to i64 storage. Cost: a single __aeabi_f2iz / __aeabi_d2iz (~64 B) helper at the call site, gc-sectioned away when not used.
  • as_float() / as_double() bodies unchanged. With float gone from the variant, the visitor naturally dispatches through the i64 arm via static_cast<FloatType>(value). Sketches that actually call as_float() pay one __aeabi_l2f helper; sketches that don't (like AutoResearchLpc.ino) pay zero.
  • ScreenMap: ParseJson / toJson use float coordinates and a float diameter, so they extend the existing FASTLED_NO_JSON early-bail to also bail on !FL_JSON_HAS_FLOAT. A 16 KB-SRAM part has no business deserializing 2D map metadata.
  • CLAUDE.md gains a short pointer to fbuild symbols <elf> and the build_info.json toolchain-path schema, so future agents stop hunting for arm-none-eabi-nm under PlatformIO package dirs.

Test plan

  • fbuild build -e lpc845brk succeeds on examples/AutoResearchLpc/AutoResearchLpc.ino
  • arm-none-eabi-nm -C firmware.elf | grep -E '(aeabi_d|aeabi_f|...)' emits zero matches (was 14 symbols before)
  • Flash usage drops 64.20 KB → 50.44 KB (≥ 13.6 KB margin, exceeds the issue's ≥ 4 KB margin acceptance criterion)
  • bash test --cpp JSON suite passes on host (host keeps FL_JSON_HAS_FLOAT=1)
  • bash lint --cpp clean

Phase 2 (separate PR)

  • fl::json_number packed 64-bit tagged union with Q30.31 / Q15.46 / UQ32.29 Tags per the issue body
  • Replace the placeholder integer-prefix-only parse for fractional JSON numbers (currently truncates "3.14" to 3 — flagged with a TODO(#3022 phase 2) comment) with a Q-format integer parse so the library preserves fractional precision without ever invoking IEEE-754
  • to_q30_31() / to_qN_M() extractors
  • sizeof(fl::json_number) == 8 && alignof(fl::json_number) == 8 round-trip tests

Closes #3022

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Documentation

    • Added a new “Key Commands” guide for inspecting already-built embedded ELF files with fbuild symbols, including example usage and where cross-tool paths are recorded in build info outputs.
  • Chores

    • JSON floating-point support is now conditionally enabled via FL_JSON_HAS_FLOAT, affecting JSON parsing/serialization and UI components that rely on float-backed JSON types.
  • Bug Fixes

    • Builds without float JSON support now consistently use the same early-return/warn behavior for screen map JSON parsing/serialization as other float-disabled configurations.

…OAT=0 (#3022 phase 1)

`fl::json_value::variant_t` carries `float` and `fl::vector<float>` as
two of its ten alternatives, which forces the compiler to instantiate
`visit_fn<float, Visitor>` and `visit_fn<vector<float>, Visitor>` for
every visitor that runs against the variant. On no-FPU ARM
(LPC845/M0+, ATmega-class AVR, STM32F1) those instantiations anchor
libgcc's full soft-FP cascade — `__aeabi_dadd / __aeabi_dmul /
__aeabi_dsub / __aeabi_d2f / __aeabi_fadd / __aeabi_fsub / __aeabi_fmul
/ __aeabi_fdiv / __aeabi_fcmp* / __eqsf2 / __aeabi_f2iz / __udivmoddi4`
— that the LPC AutoResearch RPC echo sketch never needs, eating ~13 KB
of a 64 KB flash budget.

Phase 1 of #3022 lands the structural gate without the full
`json_number` packed-tagged-union design from the issue body:

  * `FL_JSON_HAS_FLOAT` is a new macro defaulting to
    `FL_PLATFORM_HAS_LARGE_MEMORY` (#3019 / #3000 canonical name) — 1
    on host / High / Huge tiers, 0 on Low / Tiny. Users can force-set.
  * `json_value::variant_t` drops `float` and `fl::vector<float>` when
    the gate is 0. All `visit_fn<float, …>` instantiations vanish, and
    `--gc-sections` strips the dead `operator()(const float&)` /
    `operator()(const fl::vector<float>&)` visitor overloads that
    transitively pulled in the soft-FP helpers.
  * Parser float branches in `json.cpp.hpp`
    (`JsonTokenizer::scan_array_lookahead`,
    `JsonBuilder::parse_float_array`, `JsonToken::NUMBER`,
    `JsonToken::ARRAY_FLOAT`) are gated. `fl::parseFloat` is no
    longer reachable. The placeholder for fractional JSON numbers
    parses the integer prefix only — phase 2 will replace it with the
    `Q30.31` fixed-point extractors from the issue body so the
    library owns the conversion (rather than silently truncating —
    flagged in the issue comment too).
  * Public `json(float)` / `json(double)` constructors, `operator=` for
    float/double, and `set(key, float/double)` stay available so caller
    code (UI sliders, ScreenMap, diagnostics) keeps compiling. On
    `FL_JSON_HAS_FLOAT=0` the library takes over the conversion by
    truncating to `i64` storage — a single `__aeabi_f2iz` / `__aeabi_d2iz`
    (~64B) helper at the call site, gc-sectioned away when not used.
  * `as_float()` / `as_double()` bodies are untouched: with `float` gone
    from the variant the visitor dispatches through the `i64` arm
    (`static_cast<FloatType>(value)`), so callers get a sane value if
    the slot holds an integer. The cost (a single `__aeabi_l2f`) only
    materializes at sketches that actually call the extractor.

ScreenMap's `ParseJson` / `toJson` use float coordinates + a float
diameter, so they extend the existing `FASTLED_NO_JSON` early-bail
to also bail on `!FL_JSON_HAS_FLOAT` — a 16 KB-SRAM part has no
business deserializing the 2D map metadata anyway.

CLAUDE.md gains a short pointer to `fbuild symbols <elf>` /
`build_info.json` for future agents: the toolchain paths (cross `nm`,
`objdump`, `c++filt`, etc.) are recorded there and should be read,
not hunted for under PlatformIO package dirs. Saves the
"unsupported platform" flailing this PR went through during the
verification step.

Verification on `lpc845brk` AutoResearchLpc.ino (Cortex-M0+, 64 KB):

  Before: text 64 204 B, flash 64.20 / 64.00 KB (~98 %, no margin);
          ELF carries __aeabi_d2f/dadd/dmul, __aeabi_fadd/fsub/fmul/
          fdiv/fcmp*, __aeabi_f2iz, __eqsf2 (~7 KB soft-FP cascade).
  After:  text 51 280 B, flash 50.44 / 64.00 KB (78.8 %, +13.6 KB
          margin); `arm-none-eabi-nm -C firmware.elf | grep -E
          '(aeabi_d|aeabi_f|__[gle]q?[ds]f|scalbn|lround|fmod|atan|
          acos)'` is empty.

Host `bash test --cpp` json suite passes unmodified (existing
`as_float()` / `is_int()` round-trip tests stay green; the host build
keeps `FL_JSON_HAS_FLOAT=1`).

Closes #3022 (phase 1 — the structural gate). Phase 2 lands the
`fl::json_number` Q-format extractors so fractional JSON numbers
on Low-memory targets stop being truncated.

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

coderabbitai Bot commented Jun 14, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Introduces the FL_JSON_HAS_FLOAT compile-time macro (defaulting to FL_PLATFORM_HAS_LARGE_MEMORY) to gate all float and fl::vector<float> JSON support. The macro propagates through json_value type definitions, json class constructors/operators, the JSON parser/serializer internals, platform UI implementations, and ScreenMap serialization guards. A documentation section for fbuild symbols is also added to CLAUDE.md.

Changes

FL_JSON_HAS_FLOAT JSON float gating

Layer / File(s) Summary
FL_JSON_HAS_FLOAT macro and json_value type contract
src/fl/stl/json/types.h
Defines FL_JSON_HAS_FLOAT defaulting to FL_PLATFORM_HAS_LARGE_MEMORY; conditionally excludes float and fl::vector<float> from json_value::variant_t; gates constructors, assignment operators, type-query methods (is_float(), is_double(), is_floats()), and the clone_array() float-conversion branch.
json class public API and fixed-point integration
src/fl/stl/json.h
Guards json(float)/json(double) constructors with static_assert guidance when disabled; gates json(fl::vector<float>) constructor; wraps operator=(float/double/fl::vector<float>) and set() methods; adds the new public as_fixed_point<FP>() extractor; includes fixed-point detection trait and fixed-point constructor/operator paths; gates packed-array fl::vector<float> element-access branch.
JSON parser and serializer float gating
src/fl/stl/json.cpp.hpp
Gates canBeRepresentedAsFloat debug helper, tokenizer float-precision lookahead, classify_array float analysis and ALL_FLOATS classification, optimize_array ALL_FLOATS specialization, JsonBuilder::parse_float_array and ARRAY_FLOAT token handling, NUMBER parsing split (fl::parseFloat vs. fl::parseInt+i64 placeholder), and SerializerVisitor float/float-vector overloads behind FL_JSON_HAS_FLOAT.
Platform JSON UI implementations float gating
src/platforms/shared/ui/json/number_field.cpp.hpp, src/platforms/shared/ui/json/slider.cpp.hpp, src/platforms/shared/ui/json/json_console.cpp.hpp
Conditionally compiles number_field, slider, and json_console implementations behind FL_JSON_HAS_FLOAT; each translation unit is wrapped with preprocessor guards and comments explaining that float-based JSON values are unavailable on low-memory/soft-FP builds to prevent undefined-link failures.
ScreenMap float guard propagation
src/fl/math/screenmap.cpp.hpp
Expands ScreenMap::ParseJson and ScreenMap::toJson preprocessor guards to FASTLED_NO_JSON || !FL_JSON_HAS_FLOAT, triggering early-return behavior when float JSON support is absent.

Developer tooling documentation

Layer / File(s) Summary
fbuild symbols ELF inspection docs
CLAUDE.md
Adds a new subsection describing fbuild symbols usage, toolchain path sourcing from build_info.json, and how bash compile --build-info emits that metadata.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related issues

Poem

🐇 Hoppity-hop through the preprocessor gate,
Where floats may or may not participate!
On tiny chips with no FPU to speak,
We truncate to i64 — clean, not bleak.
FL_JSON_HAS_FLOAT decides the fate,
Of every double at compile-time rate! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 17.02% 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 'feat(json): gate float out of variant on FL_JSON_HAS_FLOAT=0 (#3022 phase 1)' clearly and specifically describes the main change: adding a compile-time gate to control float support in JSON via the FL_JSON_HAS_FLOAT macro.
Linked Issues check ✅ Passed The PR implements Phase 1 of issue #3022 by introducing the FL_JSON_HAS_FLOAT macro to gate float/vector alternatives out of json_value::variant_t and preventing float-related parser branches on low-memory builds, which aligns with the structural gating objective.
Out of Scope Changes check ✅ Passed All changes are within scope: the PR gates float support infrastructure (CLAUDE.md documentation, json headers/types, parser/serializer implementations, and UI module compilation) without introducing the full json_number type or fixed-point extractors that belong to Phase 2.

✏️ 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/3022-json-no-float

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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/fl/math/screenmap.cpp.hpp (1)

101-113: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Differentiate !FL_JSON_HAS_FLOAT from FASTLED_NO_JSON in the diagnostics.

These branches now fire even when JSON is enabled, so logging FASTLED_NO_JSON and returning JSON is not supported in this build sends callers down the wrong debugging path. Please report the actual requirement here instead, e.g. that ScreenMap JSON needs FL_JSON_HAS_FLOAT=1.

Also applies to: 266-272

🤖 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/math/screenmap.cpp.hpp` around lines 101 - 113, The diagnostic
messages in the ScreenMap::ParseJson method are misleading when FASTLED_NO_JSON
is false but FL_JSON_HAS_FLOAT is false. The FL_WARN log currently reports
FASTLED_NO_JSON and the error message states "JSON is not supported in this
build", but JSON is actually supported—only float support is missing. Replace
the warning message to clarify that ScreenMap requires FL_JSON_HAS_FLOAT=1 and
update the error message assigned to err to indicate that float JSON support is
required rather than stating JSON is unsupported. Apply this same diagnostic
improvement at the second affected location (lines 266-272) where the identical
issue occurs.
🤖 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 `@CLAUDE.md`:
- Around line 37-44: The CLAUDE.md documentation incorrectly documents the field
names for toolchain paths in build_info.json. The documented top-level keys like
nm_path, cppfilt_path, objdump_path, readelf_path, size_path, objcopy_path,
ar_path, cc_path, and cxx_path do not match the actual structure which stores
these under a nested aliases dictionary (aliases.nm, aliases.c++filt, etc.).
Additionally, these field names represent planned future names pending
fbuild#428 completion, not the current implementation. Correct the bullet point
that lists "Toolchain paths live in build_info.json..." by either updating the
field name references to accurately reflect the current aliases dictionary
structure with proper nesting, or by explicitly clarifying in the documentation
that these are planned field names expected post-fbuild#428. Ensure any
references to these paths throughout the section match whichever documentation
approach you choose.

In `@src/fl/stl/json.cpp.hpp`:
- Around line 1034-1057: The fl::parseInt function in the FL_JSON_HAS_FLOAT==0
branch silently prefix-parses JSON numbers, corrupting valid tokens like 1e3,
9.9e1, and 2E6 by truncating them to 1, 9, and 2. Instead of using fl::parseInt
which only consumes the integer prefix, validate that the value string does not
contain decimal points or exponent characters (., e, E) and reject or handle
such tokens appropriately to prevent silent data corruption. Additionally,
according to coding guidelines, update all in-repository consumers of
fl::json::parse() to ensure their behavior aligns with this change in the JSON
number parsing semantics.

In `@src/fl/stl/json.h`:
- Around line 141-158: Create a safe conversion helper function that prevents
undefined behavior when converting float and double values to i64, by checking
for and handling NaN, infinity, and out-of-range values (either clamping them to
valid i64 bounds or converting them to a safe default like 0). Then replace all
unguarded static_cast<i64> calls in the FL_JSON_HAS_FLOAT==0 fallback branches
with this helper: the float and double constructors in the json class at lines
141-158, and the corresponding float and double assignment operators at lines
225-247.

In `@src/fl/stl/json/types.h`:
- Around line 675-696: The variant methods is<T>() and ptr<T>() use compile-time
constraints that will fail when float and fl::vector<float> are removed from the
variant (when FL_JSON_HAS_FLOAT=0). All direct probes of these types must be
guarded with preprocessor directives to prevent compilation errors. Wrap each
ungated is<fl::vector<float>>() and ptr<fl::vector<float>>() call with `#if`
FL_JSON_HAS_FLOAT and `#endif` guards. The six affected locations are:
src/fl/stl/json.h:581 in operator[] (public method), src/fl/stl/json.h:795 in
push_back (public method), src/fl/stl/json/types.h:1232 in
SizeVisitor::get_size(), src/fl/stl/json/types.h:1306 in
array_iterator::get_value(), src/fl/stl/json/types.h:1406 in
json_value::operator[] (public method), and src/fl/stl/json/types.h:1472 in
json_value::contains (public method). For each site, add the conditional
compilation guards directly around the problematic probe statement.

---

Outside diff comments:
In `@src/fl/math/screenmap.cpp.hpp`:
- Around line 101-113: The diagnostic messages in the ScreenMap::ParseJson
method are misleading when FASTLED_NO_JSON is false but FL_JSON_HAS_FLOAT is
false. The FL_WARN log currently reports FASTLED_NO_JSON and the error message
states "JSON is not supported in this build", but JSON is actually
supported—only float support is missing. Replace the warning message to clarify
that ScreenMap requires FL_JSON_HAS_FLOAT=1 and update the error message
assigned to err to indicate that float JSON support is required rather than
stating JSON is unsupported. Apply this same diagnostic improvement at the
second affected location (lines 266-272) where the identical issue occurs.
🪄 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: e1b3096a-3984-445e-8698-223f25e3b176

📥 Commits

Reviewing files that changed from the base of the PR and between 6157361 and 2463111.

📒 Files selected for processing (5)
  • CLAUDE.md
  • src/fl/math/screenmap.cpp.hpp
  • src/fl/stl/json.cpp.hpp
  • src/fl/stl/json.h
  • src/fl/stl/json/types.h

Comment thread CLAUDE.md
Comment on lines +37 to +44
**Inspecting an already-built embedded ELF (e.g. for soft-FP / libgcc / symbol audits):**

Do NOT spend time hunting for `arm-none-eabi-nm` / `xtensa-esp32s3-elf-objdump` / etc. across PlatformIO package dirs. fbuild already records the right cross-tools for the board.

- `fbuild symbols <PATH-to-elf-or-build-dir>` — runs `nm --print-size --size-sort -S | c++filt` with the board's correct cross-tools, auto-locating `build_info.json` for the toolchain path resolution. Add `--top N` for a longer per-archive / per-symbol table; `--json <path>` for machine output.
- Toolchain paths live in `build_info.json` (or `build_info_<env>.json`) under: `nm_path`, `cppfilt_path`, `objdump_path`, `readelf_path`, `size_path`, `objcopy_path`, `ar_path`, `cc_path`, `cxx_path`. Read these instead of guessing the toolchain version under `~/.platformio/packages/` or `~/.fbuild/prod/cache/toolchains/`.
- `bash compile <board> --build-info <out.json>` emits the `build_info.json` next to the build artifact even if one is not already present.
- LPC845 example: after `fbuild build -e lpc845brk`, run `fbuild symbols .fbuild/build/lpc845brk/release/firmware.elf` — it picks up the correct `arm-none-eabi-nm` from `build_info.json` automatically.

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect build_info.json schema to confirm field names match documentation

# Check for an existing build_info.json and display its root keys
fd -name 'build_info*.json' --max-depth 5 | head -1 | xargs -I{} jq 'keys' {} 2>/dev/null || echo "No build_info.json found in repo; checking ci/compiler/build_config.py for insert_tool_aliases implementation"

# If no build_info.json exists, search for the insert_tool_aliases function to confirm field names
rg -A 30 'def insert_tool_aliases' ci/

Repository: FastLED/FastLED

Length of output: 2490


🏁 Script executed:

#!/bin/bash
# Search for where build_info.json fields are written/populated
echo "=== Searching for build_info.json field assignments ==="
rg 'nm_path|cppfilt_path|objdump_path|readelf_path|size_path|objcopy_path' ci/ -A 2

echo ""
echo "=== Searching for build_info.json structure creation ==="
rg -B 5 -A 10 'build_info.*json|BuildInfo' ci/ | head -80

echo ""
echo "=== Searching for fbuild symbols implementation ==="
fd -name fbuild -o -name '*.py' | xargs rg -l 'symbols' | head -5

Repository: FastLED/FastLED

Length of output: 21251


🏁 Script executed:

#!/bin/bash
echo "=== Searching for fbuild symbols command in ci/bloat.py ==="
rg -B 5 -A 15 "fbuild.*symbols|BuildInfo.*carries" ci/bloat.py

echo ""
echo "=== Searching for where build_info.json is actually written/generated ==="
rg -B 3 -A 10 "json.dump|write.*build_info|generate_build_info" ci/

echo ""
echo "=== Searching for size_path, ar_path references ==="
rg "size_path|ar_path" ci/

Repository: FastLED/FastLED

Length of output: 50371


🏁 Script executed:

#!/bin/bash
echo "=== Looking for actual field names written to build_info.json ==="
rg -B 5 -A 5 'aliases.*nm|aliases.*objdump' ci/util/create_build_dir.py

echo ""
echo "=== Checking for fbuild#428 references or issue tracking ==="
rg "fbuild.*428|BuildInfo.*carries" ci/

echo ""
echo "=== Checking lpc845brk build directory structure ==="
find . -type d -name "*lpc845*" 2>/dev/null | head -5

echo ""
echo "=== Searching for build directory output examples ==="
rg ".fbuild/build|.pio/build" ci/ | head -20

Repository: FastLED/FastLED

Length of output: 3315


🏁 Script executed:

#!/bin/bash
echo "=== Checking how board_info structure is actually created ==="
rg -B 10 -A 10 'board_info\[' ci/util/create_build_dir.py | head -60

echo ""
echo "=== Checking what pio.run_cmd returns and how it's parsed ==="
rg -B 5 -A 15 'def run_cmd|data.*=.*pio' ci/compiler/pio.py | head -80

echo ""
echo "=== Status of fbuild#428 - checking if it's marked as complete ==="
rg "fbuild.*428|BuildInfo.*nm_path" ci/ | grep -v ".pyc"

Repository: FastLED/FastLED

Length of output: 427


🏁 Script executed:

#!/bin/bash
echo "=== Find create_build_dir.py and check full context ==="
cat ci/util/create_build_dir.py | head -200

echo ""
echo "=== Search for where board_info gets the aliases dict ==="
rg -A 20 "def generate_build_info_json_from_existing_build" ci/compiler/pio.py | head -50

Repository: FastLED/FastLED

Length of output: 7065


🏁 Script executed:

#!/bin/bash
echo "=== Searching for generate_build_info_json_from_existing_build ==="
rg -l "generate_build_info_json_from_existing_build" ci/

echo ""
echo "=== Get full file content of pio.py compiler module ==="
find ci/compiler -name "pio.py" -exec wc -l {} \;

echo ""
echo "=== Extract relevant function from pio.py ==="
rg -B 3 -A 30 "def generate_build_info_json_from_existing_build" ci/compiler/pio.py

Repository: FastLED/FastLED

Length of output: 369


🏁 Script executed:

#!/bin/bash
echo "=== Search in ci/compiler/build_config.py for generate_build_info ==="
rg -B 5 -A 30 "def generate_build_info" ci/compiler/build_config.py

echo ""
echo "=== Search for where aliases are populated with tool paths ==="
rg -B 2 -A 8 'aliases\[' ci/util/create_build_dir.py | tail -60

Repository: FastLED/FastLED

Length of output: 2335


🏁 Script executed:

#!/bin/bash
echo "=== Check the actual structure - view a real access pattern from symbol_analysis.py ==="
rg -B 5 -A 5 'board_info\["aliases"\]' ci/util/symbol_analysis.py

echo ""
echo "=== Check if fbuild symbols actually auto-locates build_info.json ==="
rg -B 10 -A 10 "fbuild.*symbols|auto.*locate|build_info" ci/bloat.py | head -50

echo ""
echo "=== Verify: is fbuild#428 merged/complete? Check bloat.py timeline ==="
cat ci/bloat.py | head -100

Repository: FastLED/FastLED

Length of output: 8518


🏁 Script executed:

#!/bin/bash
echo "=== Verify the exact structure by reading build_info_analyzer.py ==="
rg -B 3 -A 15 "get_toolchain_aliases" ci/util/build_info_analyzer.py | head -40

echo ""
echo "=== Check if there's any mention of fbuild#428 being complete/merged ==="
git log --all --grep="428" --oneline 2>/dev/null | head -10 || echo "Git log not available"

echo ""
echo "=== Check CLAUDE.md to see the exact documented field names ==="
sed -n '37,44p' CLAUDE.md

Repository: FastLED/FastLED

Length of output: 3414


The documented field names in build_info.json are incorrect and misleading.

The CLAUDE.md section claims toolchain paths live at top-level keys like nm_path, cppfilt_path, objdump_path, readelf_path, size_path, objcopy_path, ar_path, cc_path, cxx_path in build_info.json. However, the actual structure in the codebase stores these under a nested aliases dictionary: build_info.json[board]["aliases"]["nm"], build_info.json[board]["aliases"]["c++filt"], etc.

Additionally, the ci/bloat.py file explicitly documents that fbuild#428 is not yet complete: "Until fbuild#428 lands (BuildInfo carries nm_path + cppfilt_path), we resolve directly against the PIO packages directory." This indicates the field names documented in CLAUDE.md are future names (post-fbuild#428), not the current field structure.

The fbuild symbols auto-locate behavior is also unconfirmed—bloat.py comments indicate it currently cannot read toolchain paths from build_info.json and must hard-code PIO package directory lookup.

Correct the field name references to use the actual aliases dictionary structure (aliases.nm, aliases.c++filt, etc.) or clarify these are planned fields pending fbuild#428 completion.

🤖 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 `@CLAUDE.md` around lines 37 - 44, The CLAUDE.md documentation incorrectly
documents the field names for toolchain paths in build_info.json. The documented
top-level keys like nm_path, cppfilt_path, objdump_path, readelf_path,
size_path, objcopy_path, ar_path, cc_path, and cxx_path do not match the actual
structure which stores these under a nested aliases dictionary (aliases.nm,
aliases.c++filt, etc.). Additionally, these field names represent planned future
names pending fbuild#428 completion, not the current implementation. Correct the
bullet point that lists "Toolchain paths live in build_info.json..." by either
updating the field name references to accurately reflect the current aliases
dictionary structure with proper nesting, or by explicitly clarifying in the
documentation that these are planned field names expected post-fbuild#428.
Ensure any references to these paths throughout the section match whichever
documentation approach you choose.

Comment thread src/fl/stl/json.cpp.hpp
Comment on lines 1034 to +1057
fl::shared_ptr<json_value> num_val;
if (is_float) {
#if FL_JSON_HAS_FLOAT
float f = fl::parseFloat(value.data(), value.size());
num_val = fl::make_shared<json_value>(f);
#else
// FL_JSON_HAS_FLOAT==0: variant has no float alternative
// and `fl::parseFloat` would pull in libgcc's soft-FP
// cascade. The library MUST own the fractional-number
// conversion path here (not silently truncate). For
// phase 1 of FastLED #3022 we land a placeholder that
// parses only the integer prefix — phase 2 will replace
// this with the `Q30.31` fixed-point parse and the
// `to_q30_31()` extractors from the issue body, so
// callers that need fractional precision on Low-memory
// targets keep it without ever invoking IEEE-754.
// See: github.com/FastLED/FastLED/issues/3022 — the
// design-clarification comment on the placeholder
// semantics is intentional and not a long-term contract.
// TODO(#3022 phase 2): Replace with Q-format parse.
int i = fl::parseInt(value.data(), value.size());
i64 i64_val = static_cast<i64>(i);
num_val = fl::make_shared<json_value>(i64_val);
#endif

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 | 🟠 Major | ⚡ Quick win

Don't prefix-parse valid JSON numbers in the float-disabled path.

fl::parseInt(value.data(), value.size()) only consumes the integer prefix, so valid tokens like 1e3, 9.9e1, and 2E6 become 1, 9, and 2 here instead of the truncated numeric value. That silently corrupts payloads coming through fl::json::parse(). If phase 2 is not in scope yet, rejecting decimal / exponent tokens in this branch is safer than misparsing them.

Suggested safe interim behavior
 `#else`
-                    int i = fl::parseInt(value.data(), value.size());
-                    i64 i64_val = static_cast<i64>(i);
-                    num_val = fl::make_shared<json_value>(i64_val);
+                    return ParseState::ERROR;
 `#endif`
As per coding guidelines, "when you change a public API semantic/bounds ... update all in-repo consumers ... so producer/consumer behavior stays aligned."
🤖 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.cpp.hpp` around lines 1034 - 1057, The fl::parseInt function
in the FL_JSON_HAS_FLOAT==0 branch silently prefix-parses JSON numbers,
corrupting valid tokens like 1e3, 9.9e1, and 2E6 by truncating them to 1, 9, and
2. Instead of using fl::parseInt which only consumes the integer prefix,
validate that the value string does not contain decimal points or exponent
characters (., e, E) and reject or handle such tokens appropriately to prevent
silent data corruption. Additionally, according to coding guidelines, update all
in-repository consumers of fl::json::parse() to ensure their behavior aligns
with this change in the JSON number parsing semantics.

Source: Coding guidelines

Comment thread src/fl/stl/json.h Resolved
Comment thread src/fl/stl/json/types.h
Comment on lines +675 to +696
// The variant holds exactly one of these alternatives.
//
// `float` and `fl::vector<float>` are gated by `FL_JSON_HAS_FLOAT`
// (FastLED #3022). On Low-memory / no-FPU targets they are absent so
// the soft-FP cascade (libgcc `__aeabi_d*` / `__aeabi_f*` helpers,
// ~7 KB on LPC845) cannot be reached from this code path.
using variant_t = fl::variant<
fl::nullptr_t, // null
bool, // true/false
i64, // integer
float, // floating-point (changed from double to float)
i64, // integer
#if FL_JSON_HAS_FLOAT
float, // floating-point (host / Large-memory targets only)
#endif
fl::string, // string
json_array, // array
json_object, // object
json_array, // array
json_object, // object
fl::vector<i16>, // audio data (specialized array of int16_t)
fl::vector<u8>, // byte data (specialized array of uint8_t)
fl::vector<u8> // byte data (specialized array of uint8_t)
#if FL_JSON_HAS_FLOAT
,
fl::vector<float> // float data (specialized array of float)
#endif

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Inspect fl::variant constraints"
rg -n -C3 'static_assert|enable_if|is<|ptr<|index_of|contains' src/fl/stl/variant.h

echo
echo "Find remaining direct probes of float alternatives"
rg -n -C2 'is<fl::vector<float>>|ptr<fl::vector<float>>|is<float>|ptr<float>' \
  src/fl/stl/json/types.h src/fl/stl/json.h src/fl/math/screenmap.cpp.hpp

Repository: FastLED/FastLED

Length of output: 10399


🏁 Script executed:

# Check context around json.h ungated probes
echo "=== json.h line 581 context ==="
sed -n '570,590p' src/fl/stl/json.h

echo "=== json.h line 795 context ==="
sed -n '785,805p' src/fl/stl/json.h

echo "=== types.h line 1232 context ==="
sed -n '1225,1245p' src/fl/stl/json/types.h

echo "=== types.h line 1306 context ==="
sed -n '1298,1318p' src/fl/stl/json/types.h

echo "=== types.h line 1406 context ==="
sed -n '1398,1418p' src/fl/stl/json/types.h

echo "=== types.h line 1472 context ==="
sed -n '1465,1480p' src/fl/stl/json/types.h

Repository: FastLED/FastLED

Length of output: 5267


Add #if FL_JSON_HAS_FLOAT guards to all direct probes of float and fl::vector<float> in variant methods.

When float and fl::vector<float> are removed from json_value::variant_t (FL_JSON_HAS_FLOAT=0), the fl::variant template methods is<T>() and ptr<T>() use enable_if<contains_type<T, Types...>::value> to enforce compile-time constraints. Direct probes of dropped types will fail compilation, not silently return false or nullptr.

Six ungated probe sites will break when FL_JSON_HAS_FLOAT=0:

  • src/fl/stl/json.h:581 in operator[] (public method)
  • src/fl/stl/json.h:795 in push_back (public method)
  • src/fl/stl/json/types.h:1232 in SizeVisitor::get_size()
  • src/fl/stl/json/types.h:1306 in array_iterator::get_value()
  • src/fl/stl/json/types.h:1406 in json_value::operator[] (public method)
  • src/fl/stl/json/types.h:1472 in json_value::contains (public method)

Wrap each ungated is<fl::vector<float>>() and ptr<fl::vector<float>>() call in #if FL_JSON_HAS_FLOAT / #endif`` guards.

🤖 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` around lines 675 - 696, The variant methods is<T>()
and ptr<T>() use compile-time constraints that will fail when float and
fl::vector<float> are removed from the variant (when FL_JSON_HAS_FLOAT=0). All
direct probes of these types must be guarded with preprocessor directives to
prevent compilation errors. Wrap each ungated is<fl::vector<float>>() and
ptr<fl::vector<float>>() call with `#if` FL_JSON_HAS_FLOAT and `#endif` guards. The
six affected locations are: src/fl/stl/json.h:581 in operator[] (public method),
src/fl/stl/json.h:795 in push_back (public method), src/fl/stl/json/types.h:1232
in SizeVisitor::get_size(), src/fl/stl/json/types.h:1306 in
array_iterator::get_value(), src/fl/stl/json/types.h:1406 in
json_value::operator[] (public method), and src/fl/stl/json/types.h:1472 in
json_value::contains (public method). For each site, add the conditional
compilation guards directly around the problematic probe statement.

@zackees

zackees commented Jun 14, 2026

Copy link
Copy Markdown
Member Author

Note from review: #3029 tracks the gap exposed by this PR — the FastLED-internal float→i64 truncation fallback in json.h (json(float) / json(double) / operator= / set(key, float)) violates the mandate that the library must not pull in FP ops on Low-memory targets. Same for the UI-control .cpp.hpp files (slider, number_field, json_console) which call json::set(key, float) from library code. Phase 1.5 PR will remove the truncation fallback (hard compile error pointing callers at fl::fixed_point<>) and gate the UI-control TUs the same way ScreenMap is already gated here. Manual as_fixed_point<>() / set(key, fixed_point) API is the destination — design sketched in #3029 §B.

…closes #3029)

Phase 1.5 of #3022: tighten the FL_JSON_HAS_FLOAT=0 contract so the
FastLED library never reaches an IEEE-754 helper on Low-memory targets,
regardless of which sketch is linked.

src/fl/stl/json.h:
  * Drop the #else truncation fallback in json(float/double),
    operator=(float/double), and set(key, float/double). On
    FL_JSON_HAS_FLOAT=0 these are now SFINAE-templated static_assert
    overloads that name the migration path (fl::fixed_point<>) — a
    silent static_cast<i64>(f) inside the library was pulling
    __aeabi_f2iz / __aeabi_d2iz (~64B each) into the link at every
    call site, even when the user only ever wanted integer storage.
  * Add fl::json ↔ fl::fixed_point setter / extractor API. Our number
    format is itself a super fixed point — the i64 variant slot is the
    natural carrier for any Q-format value, so the new templated
    json(FP), operator=(FP), set(key, FP), and as_fixed_point<FP>()
    overloads pack/unpack the raw integer representation directly.
    SFINAE detects fixed_point-shaped types via INT_BITS / FRAC_BITS /
    raw() / from_raw() member probes (works for s16x16, s0x32, u24x8,
    s12x4, and so on — see src/fl/math/fixed_point/).

src/platforms/shared/ui/json/{slider,number_field}.cpp.hpp:
  * Wrap whole-TU bodies in #if FL_JSON_HAS_FLOAT. JsonSliderImpl and
    JsonNumberFieldImpl carry intrinsically-float value/min/max/step
    storage and serialize via json.set(key, float); gating the TU keeps
    the soft-FP cascade out of the library archive on Low-memory
    builds. Sketches that don't instantiate these widgets see zero
    impact; sketches that try to fail at link with `undefined
    reference`, mirroring the existing FASTLED_NO_JSON ergonomics in
    ScreenMap. Phase-2 plan tracked under #3022: add fixed-point
    widget variants (JsonSliderImplFixed<Q16x16>) so Low-memory
    sketches still have working sliders.

src/platforms/shared/ui/json/json_console.cpp.hpp:
  * Tighten the existing SKETCH_HAS_LARGE_MEMORY gate to
    SKETCH_HAS_LARGE_MEMORY && FL_JSON_HAS_FLOAT. JsonConsole parses
    serial input through strtod and routes float values into
    json::set(key, float); the secondary gate makes the TU drop out
    under user opt-out via -DFL_JSON_HAS_FLOAT=0 on a Large-memory
    part too.

Note on local verification: lint passes; the worktree's `bash test`
runner is blocked by a Windows-worktree meson_native.txt lifecycle
race against ninja regeneration (file gets purged between meson setup
and the first build action) — relying on PR CI for the test/compile
matrix.

Closes #3029.

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

🤖 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 `@src/fl/stl/json.h`:
- Around line 133-140: Replace all non-ASCII punctuation characters in the newly
added comments with ASCII equivalents throughout src/fl/stl/json.h.
Specifically, convert em-dashes (—) to hyphens (-) or double-hyphens (--), and
replace any other non-ASCII characters like right arrows (→) and hyphens (‑)
with their ASCII equivalents. Apply these replacements at the anchor location
(lines 133-140) where the SFINAE trait comment block describes the detection
probes, and also at the sibling location (lines 170-187) that contains similar
newly added comment blocks. Ensure all comments in these ranges contain only
ASCII characters to match repository standards.
- Around line 369-375: The as_fixed_point() method currently performs an
unchecked cast from the JSON integer (i64) to the target fixed-point type's raw
value type without validating that the integer falls within the valid range for
that type. This allows out-of-range values to silently wrap or truncate into
invalid fixed-point representations. Validate that the integer value retrieved
from mValue->as_int() (stored in variable i) is within the acceptable range for
the target fixed-point type's raw type before casting it. If the value is out of
range, return fl::nullopt instead of proceeding with the conversion.
🪄 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: b67308e5-53a8-4e66-b4ea-7229c00e7935

📥 Commits

Reviewing files that changed from the base of the PR and between 2463111 and cfe8b91.

📒 Files selected for processing (4)
  • src/fl/stl/json.h
  • src/platforms/shared/ui/json/json_console.cpp.hpp
  • src/platforms/shared/ui/json/number_field.cpp.hpp
  • src/platforms/shared/ui/json/slider.cpp.hpp

Comment thread src/fl/stl/json.h
Comment on lines +133 to +140
// SFINAE trait — true for fl::fixed_point<>-shaped types (s16x16, s0x32,
// u24x8, ...). Used by fl::json setter / extractor templates so a
// fixed_point value flows through the integer storage path and never
// pulls IEEE-754 helpers into the link (FastLED #3022 / #3029). The
// detection probes the public members every fixed_point type exposes:
// - `INT_BITS` / `FRAC_BITS` — static layout constants
// - `raw()` — read the underlying integer repr
// - `from_raw(raw_type)` — rebuild the value from that repr

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

Replace non-ASCII punctuation in touched C++ comments.

New comments include non-ASCII characters (for example —, →, ‑). Please convert them to ASCII equivalents in this header (and the same newly added comment blocks in the touched UI .cpp.hpp files) to match repo standards.

As per coding guidelines, "ASCII-only in C++ source: ensure no non-ASCII characters in comments/strings in touched .h / .hpp / .cpp.hpp files."

Also applies to: 170-187

🤖 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.h` around lines 133 - 140, Replace all non-ASCII punctuation
characters in the newly added comments with ASCII equivalents throughout
src/fl/stl/json.h. Specifically, convert em-dashes (—) to hyphens (-) or
double-hyphens (--), and replace any other non-ASCII characters like right
arrows (→) and hyphens (‑) with their ASCII equivalents. Apply these
replacements at the anchor location (lines 133-140) where the SFINAE trait
comment block describes the detection probes, and also at the sibling location
(lines 170-187) that contains similar newly added comment blocks. Ensure all
comments in these ranges contain only ASCII characters to match repository
standards.

Source: Coding guidelines

Comment thread src/fl/stl/json.h
Comment on lines +369 to +375
typename fl::enable_if<detail::is_fl_fixed_point<FP>::value, fl::optional<FP>>::type
as_fixed_point() const FL_NOEXCEPT {
if (!mValue) return fl::nullopt;
auto i = mValue->as_int();
if (!i) return fl::nullopt;
return FP::from_raw(static_cast<decltype(FP().raw())>(*i));
}

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 | 🟠 Major | ⚡ Quick win

Validate raw-type range in as_fixed_point<FP>() before conversion.

as_fixed_point<FP>() currently reads i64 then does an unchecked cast to FP::raw()’s type. Out-of-range JSON integers can silently wrap/truncate into invalid fixed-point values.

Proposed fix
     template <typename FP>
     typename fl::enable_if<detail::is_fl_fixed_point<FP>::value, fl::optional<FP>>::type
     as_fixed_point() const FL_NOEXCEPT {
         if (!mValue) return fl::nullopt;
-        auto i = mValue->as_int();
-        if (!i) return fl::nullopt;
-        return FP::from_raw(static_cast<decltype(FP().raw())>(*i));
+        typedef decltype(fl::declval<const FP&>().raw()) raw_t;
+        auto raw = mValue->template as_int<raw_t>();
+        if (!raw) return fl::nullopt;
+        return FP::from_raw(*raw);
     }
🤖 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.h` around lines 369 - 375, The as_fixed_point() method
currently performs an unchecked cast from the JSON integer (i64) to the target
fixed-point type's raw value type without validating that the integer falls
within the valid range for that type. This allows out-of-range values to
silently wrap or truncate into invalid fixed-point representations. Validate
that the integer value retrieved from mValue->as_int() (stored in variable i) is
within the acceptable range for the target fixed-point type's raw type before
casting it. If the value is out of range, return fl::nullopt instead of
proceeding with the conversion.

@zackees

zackees commented Jun 14, 2026

Copy link
Copy Markdown
Member Author

Superseded by phase-2 work: integer-only IEEE 754 codec replacement.

The bit-twiddling codec (fl::ieee754_string — string ↔ IEEE 754 bits via integer math, plus integer-only int ↔ float_bits helpers in the JSON visitors) removes the libgcc soft-FP cascade structurally — without dropping the float or fl::vector<float> alternatives from json_value::variant_t. On a Low-memory target the LPC845 link still shows zero __aeabi_d* / __aeabi_f* symbols, just as this PR's gate achieved, but JSON I/O for fl::vector<float> keeps working (round-trips via the integer-only codec).

Closing in favor of the codec PR. The design conclusion from #3029 — that fl::vector<float> storage in the variant is structurally soft-FP-free; only the parser / serializer / scalar conversion routines pull libgcc — is what motivated the move from gating to codec replacement.

Related: #3022 (parent), #3029 (gap-tracking).

@zackees zackees closed this Jun 14, 2026
@fastled-project-sync fastled-project-sync Bot moved this from Triage to Done in FastLED Tracker Jun 14, 2026
zackees added a commit that referenced this pull request Jun 14, 2026
…#3022) (#3038)

* feat(json): integer-only string->IEEE 754 codec — parser (#3022 phase 2)

Adds `fl::ieee754_parse_decimal` (and stubs the serializer side) plus a
84-entry pow10 lookup table generated by `ci/tools/gen_pow10_table.py`.
The parser:

  * Reads decimal digits into a u64 mantissa with a decimal-exponent
    accumulator (handles fractional + scientific notation).
  * Normalizes the mantissa so its top bit is set.
  * Multiplies against a precomputed (mantissa, binary_exp) pair for
    10**k using a portable 4-way 32x32->64 widening multiply
    (`mul_hi_u64`) — no `__aeabi_d*` / `__aeabi_f*` helpers ever reached.
  * Packs into IEEE 754 single-precision bits with round-half-to-even.

Caller bit-casts the returned u32 to `float` via `fl::bit_cast<float>`
(which is `memcpy` — no FP arithmetic). Out-of-range exponents clamp to
±0 / ±inf bit patterns.

Embedded-grade precision target: ~6 significant decimal digits with at
most ±1 ULP drift from `strtof`. Sufficient for the JSON-RPC use case
that motivates the no-soft-FP mandate (FastLED #3022 / #3029).

`tests/fl/stl/ieee754_string.cpp` exercises well-known constants,
±1 ULP tolerance against the host strtof, scientific notation,
over/underflow clamping, and the `consumed` bookkeeping path. Passes
under both quick mode and debug mode (ASAN/LSAN/UBSAN).

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

* feat(json): integer-only IEEE 754 -> string serializer (#3022 phase 2)

Adds fl::ieee754_format_decimal. Reuses the same pow10 lookup table
already in the TU for the parser, plus a small kPow10IntExact[] table
(10^0..10^9 as exact u32 values) for the integer/fractional split.

  * Unpacks sign / biased exponent / mantissa from the IEEE 754 bit
    pattern via shifts and masks.
  * Lifts the 24-bit mantissa to u64 with the top bit set, multiplies by
    the normalized 10^precision via mul_hi_u64 (shared with the parser),
    and rounds-half-to-even at the bit-shift step.
  * Splits the resulting integer by 10^precision and formats via the
    existing fl::utoa64 helper — no FP arithmetic anywhere.
  * Inf / NaN / zero / underflow / overflow all return the appropriate
    literal (inf / -inf / nan / 0.000000 / clamp).

tests/fl/stl/ieee754_string.cpp extends to cover the serializer: known
constants (0, 1, 0.5, 10, 100), special values, parser round-trip on
exact powers of two and within 1 ULP on pi / e, and precision clamping.

Verified by building the test DLL directly and invoking the runner:
10/10 doctest cases pass. The bash test wrapper hits an unrelated
meson_native.txt lifecycle bug on this build dir, tracked separately.

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

* feat(json): route parser/serializer through bit-twiddling codec (#3022 phase 2)

Replaces the four direct callers of libgcc soft-FP-anchored helpers in
src/fl/stl/json.cpp.hpp with the integer-only fl::ieee754_string codec:

  * JsonTokenizer::scan_array_lookahead — fl::parseFloat + fl::abs check
    -> fl::ieee754_parse_decimal + biased-exp comparison.
  * JsonBuilder::parse_float_array (template) — same swap; the static_cast
    on the outbound value type is left to the caller, matching the
    "user opts into float math, library does not" mandate.
  * JsonBuilder::on_token NUMBER arm — fl::parseFloat -> bit-twiddling
    parse + fl::bit_cast<float> at the variant boundary (memcpy, free).
  * SerializerVisitor::accept(const float&) and accept(const fl::vector
    <float>&) — fl::string::append(f, prec) -> fl::ieee754_format_decimal
    (bit_cast<u32>(f), prec). Output precision contract preserved
    (3 digits scalar / 6 digits vector).
  * classify_array float branch — fl::abs(f) > 16777216.0f -> integer
    biased-exp comparison via the shared float_bits_magnitude_exceeds_2_24
    helper.
  * Removed the unused-since-#3027 canBeRepresentedAsFloat(double) dead
    helper (it pulled __aeabi_d* via fl::abs(double) for callers that no
    longer exist).

Verified:
  * tests/fl/stl/ieee754_string.cpp — 10/10 pass.
  * tests/fl/stl/json.cpp           — 27/27 pass (ScreenMap round-trip
    confirms the new fl::vector<float> serializer reproduces 0.000-style
    output the previous fl::string::append(f, 3) emitted).

Next phase will verify the LPC845 ELF link is free of __aeabi_d* /
__aeabi_f* symbols even with FL_JSON_HAS_FLOAT=1 (task #5).

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

* chore(lint): rename local + IWYU pragma + alphabetize drivers/_build

Three follow-up linter fixes spotted by `bash lint --cpp`:

  * `src/fl/stl/ieee754_string.cpp.hpp`: rename local `m_full` -> `mantissa_full`
    so MemberStyleChecker (which treats `m_*` as a member-variable prefix)
    stays quiet. The variable is a function-local in `ieee754_format_decimal`;
    the rename is purely cosmetic.
  * `src/fl/stl/json.cpp.hpp`: wrap the newly-added `#include "fl/stl/bit_cast.h"`
    in an `// IWYU pragma: begin_keep` / `end_keep` block so
    IwyuPragmaBlockChecker keeps it pinned (the include is reachable transitively
    but we want explicit intent for the `fl::bit_cast<float|u32>` calls).
  * `src/platforms/shared/mock/arm/teensy4/drivers/_build.cpp.hpp`: alphabetize
    the LPUART / ObjectFLED / FlexIO _build.cpp.hpp includes (UnityBuildChecker).
    Pre-existing master-side ordering bug from PR #3032 — fixing here per the
    project's "all encountered lint errors get addressed" policy.

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

* fix: address CodeRabbit review feedback on #3038

- Reject decimals with no digits (".", "-.") via explicit seen_digit guard;
  the existing i == mantissa_start check skipped past a consumed decimal point.
- Extend pow10 table down to K_MIN=-64 so the parser's raw 19-digit mantissa
  reaches IEEE 754 single-precision underflow without prematurely flushing to
  zero (e.g. 1234567890123456789e-46 ~= 1.23e-28 now decodes correctly).
- Fix float_bits_magnitude_exceeds_2_24 to include the (2**24, 2**25) decade
  (biased_exp == 151 with non-zero mantissa) and inf/NaN; the prior strict
  > 151 check leaked literals like 16777217.0 onto the optimized vector<float>
  path past the exact-integer boundary.
- Strip non-ASCII punctuation (em-dash, plus-minus, arrows) from generator
  output and from the new ieee754_string / json comments + test banners to
  satisfy the 7-bit-ASCII repo guideline.
- Drop F541 f-string prefix in gen_pow10_table.py print().

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[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.

fl::json: custom 64-bit packed tagged-number type (replaces variant<i64, float, double> in #3002)

1 participant