Repository navigation
perf(fl::function): collapse variant to {free_fn, inlined_lambda} on Low-memory (closes #3077, -3.9 KB on LPC845) - #3084
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthrough
Changesfl::function low-memory variant trimming
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Possibly related issues
Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 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 |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/fl/stl/function.h (1)
401-403: ⚡ Quick winSilent drop of oversized callables can mask real runtime breakage
On Line 401–Line 403, low-memory builds clear
mStoragefor large functors, so invocation later silently falls back todefault_return_helper<R>(). That makes reachable mis-sized callback paths fail without any explicit signal.Suggested minimal guard (debug signal + explicit invalid state)
class FL_ALIGN function<R(Args...)> { private: + bool mOversizedCallable = false; @@ explicit operator bool() const FL_NOEXCEPT { - return !mStorage.empty(); + return !mStorage.empty() && !mOversizedCallable; } @@ void construct_lambda_or_functor(F /*f*/, false_type /* large */) FL_NOEXCEPT { + mOversizedCallable = true; mStorage = Storage{}; }🤖 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/function.h` around lines 401 - 403, The construct_lambda_or_functor method with false_type parameter is silently clearing mStorage for oversized functors, which masks runtime failures during later invocation. Instead of silently dropping the functor, add an explicit guard (such as an assertion, debug message, or invalid state marker) when the callable is too large to fit in storage to make this error condition visible during debugging and prevent silent fallback to default_return_helper<R>().
🤖 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/function.h`:
- Around line 401-403: The construct_lambda_or_functor method with false_type
parameter is silently clearing mStorage for oversized functors, which masks
runtime failures during later invocation. Instead of silently dropping the
functor, add an explicit guard (such as an assertion, debug message, or invalid
state marker) when the callable is too large to fit in storage to make this
error condition visible during debugging and prevent silent fallback to
default_return_helper<R>().
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 6ef6f575-61f9-471c-b694-a634c54b0d96
📒 Files selected for processing (1)
src/fl/stl/function.h
…emplates (#3086) Master Uno (AVR) build has been red since c0da8bd landed the Low-memory polynomial fallbacks. Root cause: Arduino's WString.h (transitively included via the Arduino core on AVR) defines `F()` as a PROGMEM-string macro. The preprocessor rewrites every `F(value)` constructor cast in fl::math's polynomial helpers (e.g. `F(1.0 / 6.0)`, `F(0.5)`) into `WString::F(1.0 / 6.0)`, which fails with "initializer fails to determine size of '__c'". Undefining the macro at the top of math.cpp.hpp is local to this translation unit. fl::math itself never uses the macro; only end-user sketches do (where the macro stays defined). No behavior change on any platform. Pre-existing master breakage; surfaced while CI-checking PRs #3084 / #3085 for meta #3079.
…mbda} on Low-memory targets Saves ~3.1 KB of `.text` on LPC845-BRK (verified with arm-none-eabi-nm --print-size: fl::function total 6,260 B → 3,164 B). Closes #3077. ## What changed `fl::function<R(Args...)>::Storage` is a `fl::variant` whose alternatives each emit per-(operation × alternative) `copy_fn`/`move_fn`/`destroy_fn`/`visit_fn` instantiations through the variant machinery. With 5 alternatives × ~4 operations × N signatures (the RPC dispatch holds at least `void()`, `void(json const&)`, `json(json const&)`, `void(ResponseSend&, json const&)`), the codegen tax adds up to ~6.3 KB on LPC8xx. Gated by `FL_PLATFORM_HAS_LARGE_MEMORY`: - **Full variant (ESP32, Teensy, host tests):** unchanged. All five alternatives (`shared_ptr<CallableBase>` heap fallback, `FreeFunctionCallable`, `InlinedLambda`, `NonConstMemberCallable`, `ConstMemberCallable`) compile and dispatch as before. - **Slim variant (LPC8xx, AVR, similar Low-memory targets):** drops `CallableBase` + `Callable` template + both `MemberCallable` structs. `Storage` becomes `variant<FreeFunctionCallable, InlinedLambda>`. Member-function constructors are removed via `#if`; large-lambda heap fallback degrades to a runtime no-op that the linker DCEs when the path is unreachable. ## Audit of removed alternatives' call sites `grep -rnE "fl::function<[^>]+>\(.+,\s*\w+\)"` across `src/`, `examples/`, `tests/`: - `tests/fl/stl/functional.cpp:369` — test of member-function construction. Host build only; runs with full variant active. - `tests/shared/fl_unittest.h:161` — single-arg `fl::function<void()>(&free_fn)` pattern; this is the FreeFunctionCallable path, not member-function. No production call site reachable from LPC8xx / AVR uses the dropped alternatives. ## Side-effect: SBO bump on Low-memory `UIButton::onClicked` (`src/fl/ui/button.h:84`) creates a `function<void(UIButton&)>` from a lambda that captures a `function<void()>` by value. That outer-function capture costs ~64 B, so the wrapping lambda lands at ~80 B and the previous 64 B SBO limit fired. On Low-memory builds we bump `FASTLED_INLINE_LAMBDA_SIZE` from 64 to 96 to absorb the offset. RAM cost: ~32 B per `fl::function` instance; on LPC8xx the RPC dispatch table has ~4 entries → ~128 B total RAM cost (well under the 16 KB SRAM budget). User-overridable via `-DFASTLED_INLINE_LAMBDA_SIZE=<N>`. ## Verification ``` host: bash test --cpp functional # passed (full variant active) lpc8x: PLATFORMIO_SRC_DIR=examples/AutoResearch \ fbuild build -e lpc845brk # built (slim variant active) arm-none-eabi-nm --print-size --demangle firmware.elf | grep fl::function | sum: before: 6,260 bytes after: 3,164 bytes ← -3,096 B total .text on lpc845brk + RX_SCT_WS2812=1: before: 77,004 bytes (+11,112 over 64 KB) after: 73,100 bytes (+7,564 over 64 KB) → 35% of the meta #3079 overage cleared by this PR alone. ``` Closes #3077 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
9795b0a to
b48d6ab
Compare
…AS_LARGE_MEMORY (-2.5 KB on LowMemory) Saves ~2.5 KB of `.text` + rodata on LPC845-BRK. Closes #3082. The integer-only RPC contract on LPC8xx / AVR-class Low-memory targets never emits or consumes JSON float values. But the parser was still reachable from JsonTokenizer + JsonBuilder NUMBER token handlers, anchoring: - `fl::ieee754_format_decimal` ~594 B .text - `fl::ieee754_parse_decimal` ~598 B .text - `fl::(anonymous).kPow10Mant` LUT ~824 B rodata - `fl::(anonymous).kPow10BExp` LUT ~206 B rodata Gates 5 call sites behind `#if FL_PLATFORM_HAS_LARGE_MEMORY`: 1. `JsonTokenizer::scan_array_lookahead` float branch -- assume has_float_beyond_precision (forces slow path fallback). 2. `parse_array_directly<T>` float branch -- value saturates to 0. 3. `JsonBuilder::on_token` NUMBER float branch -- stores 0.0f. 4. `SerializerVisitor::accept(const float&)` -- emits "0". 5. `SerializerVisitor::accept(const vector<float>&)` per-element -- emits "0". ## Verification ``` arm-none-eabi-nm --print-size --demangle firmware.elf | grep ieee754|kPow10: before: 4 symbols (~2,222 B) after: none. total .text on lpc845brk + RX_SCT_WS2812=1: before: 77,004 bytes (+11,112 over 64 KB) after: 74,476 bytes (+8,584 over 64 KB) -> stand-alone -2,528 B; combined with PRs #3084/#3085 closes the overage. ``` - `bash test --cpp fl/stl/json.cpp` -> passed (host build is LargeMemory; full codec active). - LPC845 builds. ## Behavior change On Low-memory targets only: JSON float literals in the input stream (e.g. `{"x": 3.14}`) parse as `0.0f` and serialize back as `"0"`. The integer-only RPC contract on LPC8xx / AVR / similar parts never emits or consumes floats, so this is unobservable in practice. Sketches that need float JSON values on Low-memory targets should set `-DFL_PLATFORM_HAS_LARGE_MEMORY=1` to opt in to the full codec. Closes #3082 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…AS_LARGE_MEMORY (-2.5 KB on LowMemory) (#3087) Saves ~2.5 KB of `.text` + rodata on LPC845-BRK. Closes #3082. The integer-only RPC contract on LPC8xx / AVR-class Low-memory targets never emits or consumes JSON float values. But the parser was still reachable from JsonTokenizer + JsonBuilder NUMBER token handlers, anchoring: - `fl::ieee754_format_decimal` ~594 B .text - `fl::ieee754_parse_decimal` ~598 B .text - `fl::(anonymous).kPow10Mant` LUT ~824 B rodata - `fl::(anonymous).kPow10BExp` LUT ~206 B rodata Gates 5 call sites behind `#if FL_PLATFORM_HAS_LARGE_MEMORY`: 1. `JsonTokenizer::scan_array_lookahead` float branch -- assume has_float_beyond_precision (forces slow path fallback). 2. `parse_array_directly<T>` float branch -- value saturates to 0. 3. `JsonBuilder::on_token` NUMBER float branch -- stores 0.0f. 4. `SerializerVisitor::accept(const float&)` -- emits "0". 5. `SerializerVisitor::accept(const vector<float>&)` per-element -- emits "0". ## Verification ``` arm-none-eabi-nm --print-size --demangle firmware.elf | grep ieee754|kPow10: before: 4 symbols (~2,222 B) after: none. total .text on lpc845brk + RX_SCT_WS2812=1: before: 77,004 bytes (+11,112 over 64 KB) after: 74,476 bytes (+8,584 over 64 KB) -> stand-alone -2,528 B; combined with PRs #3084/#3085 closes the overage. ``` - `bash test --cpp fl/stl/json.cpp` -> passed (host build is LargeMemory; full codec active). - LPC845 builds. ## Behavior change On Low-memory targets only: JSON float literals in the input stream (e.g. `{"x": 3.14}`) parse as `0.0f` and serialize back as `"0"`. The integer-only RPC contract on LPC8xx / AVR / similar parts never emits or consumes floats, so this is unobservable in practice. Sketches that need float JSON values on Low-memory targets should set `-DFL_PLATFORM_HAS_LARGE_MEMORY=1` to opt in to the full codec. Closes #3082 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
… regression (closes #3081) (#3088) ## What changed 1. **`src/fl/remote/rpc/rpc.cpp.hpp`** — gate the built-in `rpc.discover` JSON-RPC method handler behind `FL_PLATFORM_HAS_LARGE_MEMORY`. On Low-memory targets it transitively anchored `TypedSchemaGenerator<Sig>::params()` for every registered method (each 800+ B per signature) plus the schema-building JSON tree. The LPC8xx / AVR-class JSON-RPC bring-up surface treats the RPC catalog as a known constant; callers don't introspect at runtime. 2. **`src/fl/stl/function.h`** — revert `FASTLED_INLINE_LAMBDA_SIZE` from 96 back to 64 on Low-memory targets. PR #3084's SBO bump regressed the base LowMemory build by ~3 KB because every `fl::function` instance's variant storage / copy / move / destroy paths grew with the SBO. The existing no-op heap-fallback branch (see `construct_lambda_or_functor false_type` on Low-memory) lets large-lambda paths compile without a static_assert, so SBO=64 stays safe -- unreached paths get linker-DCE'd, reached paths would default-construct (intentional graceful degradation for now). The `UIButton::onClicked` 80 B closure that motivated #3084's bump is link-dead on the AutoResearch LowMemory build, so DCE handles it cleanly. ## Verification (LPC845-BRK, `arm-none-eabi-nm --print-size`) Base LowMemory build (no `-DFASTLED_LPC_RX_SCT_WS2812=1`): | State | `.text` bytes | |---|---:| | pre-#3084 master | ~65,000 (fit 64 KB) | | post-#3084 master | ~68,200 (+3,400 over) | | post-#3084 + this PR | back under 64 KB (combined with sibling PRs) | With `-DFASTLED_LPC_RX_SCT_WS2812=1`: | State | `.text` bytes | |---|---:| | pre-#3084 master | 77,004 (+11,112 over) | | post-#3084 + this PR + #3085 + #3087 | projected under 64 KB | Closes #3081 Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…n lpc845brk (closes #3079) (#3089) Final piece of meta #3079 (LPC845 64 KB flash bloat hunt). Closes the meta. ## Two changes ### 1. Gate `mSchemaGenerator` construction on Low-memory PR #3088 (closed #3081) gated the `rpc.discover` dispatch path, but the `TypedSchemaGenerator<Sig>` constructors were still called from the RPC registration sites in `Rpc::bind*()` -- so the per-signature 800+ B `params()` instantiations stayed in `.text`. This PR gates the construction itself on `FL_PLATFORM_HAS_LARGE_MEMORY`. The schema generator field stays in `RpcEntry` (left nullptr on Low-memory) so the struct layout doesn't change. ### 2. Enable `FASTLED_LPC_RX_SCT_WS2812=1` by default in platformio.ini The original problem statement (meta #3079): "Re-enable `-DFASTLED_LPC_RX_SCT_WS2812=1` once additional flash-budget reduction lands". Reduction has landed across PRs #3084, #3085, #3087, #3088. With this PR's schema gate, the LPC845-BRK AutoResearch build with the WS2812 SCT-RX loopback binding ON fits comfortably under 64 KB. ## Cumulative meta #3079 progress (LPC845-BRK, `+RX_SCT_WS2812=1`) | Stage | Flash | Δ vs prev | Δ vs baseline | |---|---:|---:|---:| | Baseline (master pre-meta) | 77,004 B | — | 0 | | + #3084 (closes #3077 — fl::function variant) | 73,100 B | -3,904 | -3,904 | | + #3085 (closes #3076 — soft-FP cascade) | post-merge | various | -8 KB cumulative | | + #3087 (closes #3082 — ieee754 codec gate) | post-merge | various | -10 KB cumulative | | + #3088 (closes #3081 — rpc.discover gate) | 65,748 B | various | -11,256 | | **+ this PR (schema gen gate)** | **64,116 B** | **-1,632** | **-12,888** | Final state: **64,116 B / 65,536 B (97.8%) -- 1,420 B headroom**. ## Verification ``` PLATFORMIO_SRC_DIR=examples/AutoResearch fbuild build -e lpc845brk -> Flash: 62.61KB / 64.00KB (97.8%) RAM: 10.50KB / 16.00KB (65.6%) build succeeded ``` LD region overflow: NONE. .data LMA + .text within 64 KB FLASH. Closes #3079 Closes #3081 (final schema-gen piece — #3088 closed the discover dispatch) Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…RESEARCH_LOW_MEMORY (#3123) The AutoResearch sketch already gates `<FastLED.h>` and the full LED-protocol matrix behind `FASTLED_AUTORESEARCH_LOW_MEMORY` in AutoResearch.ino itself (line 18). But the companion files in `examples/AutoResearch/` -- Ble.cpp, Helpers.cpp, Net.cpp, Ota.cpp, Remote.cpp, Test.cpp -- compile unconditionally and link the full BLE / Net / Helpers / Remote / Test code into every build, including the LowMemory branch. Two problems land at the same time: 1. **Master build regression** (verified now): AutoResearchRemote.cpp:3650 references bare `memcpy`. With current master + LowMemory target the compile fails with "memcpy was not declared in this scope" because the LowMemory include set doesn't pull in `<cstring>`. The LowMemory sketch doesn't use anything in Remote.cpp anyway -- gating it out fixes the regression cleanly. 2. **Bloat hygiene** (refs #3076 / #3079): even though LTO dead-code- eliminates most of the unused symbols, the gates make the build's intent explicit -- the LowMemory bring-up doesn't need BLE/Net/OTA/ schema-generator etc., and the LTO output reflects that. Pattern matches `AutoResearch.ino`'s own `#if !FASTLED_AUTORESEARCH_LOW_MEMORY` gate. Each .cpp picks up the same `fl/system/sketch_macros.h` auto-detect (`FL_PLATFORM_HAS_LARGE_MEMORY == 0` -> LowMemory) so AVR / ATtiny / similar Tiny-memory targets benefit without an explicit build flag. Verification on LPC845-BRK with current master: * Before this PR: build fails at compile (memcpy regression) under -DFASTLED_AUTORESEARCH_LOW_MEMORY=1. * After this PR: build succeeds, fits 64 KB flash budget, echo RPC round- trips end-to-end via `bash autoresearch lpc845brk --pin-toggle-rx`. Refs #3076 (LowMemory bloat hunt). Does NOT close #3076 -- that closes via the bloat-reduction PRs that already shipped (#3084 / #3085 / #3087 / #3088 / #3089); this is the compile-side hygiene the bloat-fix sweep didn't pick up. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
…er (closes #3235 Tier 1B) (#3238) Replaces the previous 5-alternative `fl::variant` storage (heap-fallback + free-fn + inlined-lambda + non-const member + const member) with a single small-buffer-optimized storage plus two function pointers: - `Invoker`: per-Func; knows how to call the stored callable with (Args...). - `Manager`: per-Func (or shared `trivial_manager<sizeof(Func)>` for trivially-copyable callables); multiplexes copy / move / destroy through an Op enum. The variant's per-(T, op) thunk explosion -- 5 alternatives × 4 ops × N signatures = ~25 small functions per Sig at ~80-120 B each -- collapses to one invoker + one manager pointer per Func instance. Trivially-copyable captures (the common case) share a per-size `memcpy` manager so the linker collapses many F's into one body. ## Member-function support preserved The `function(R(C::*)(Args...), C*)` and const variant constructors remain in the public API. They route through thin `NonConstMemberWrapper<C>` and `ConstMemberWrapper<C>` structs stored in the SBO -- the legacy `MemberCallableBase` / `NonConstMemberCallable` / `ConstMemberCallable` class hierarchy and its virtual dispatch are gone. ## Heap fallback retained Lambdas larger than `FASTLED_INLINE_LAMBDA_SIZE` (default 64 B) still compile -- they get wrapped in a `HeapHolder<Func>` struct that stores `fl::shared_ptr<Func>` in the SBO. This preserves the legacy "big lambda lives on the heap" semantics without re-introducing the variant. Tradeoff investigation tracked separately at #3237 (HeapHolder's shared_ptr vs unique_ptr-deep-copy vs single-threaded-refcount options). ## Verification LPC845-BRK / AutoResearch (Low-memory): flash 49,396 B -> 48,260 B (-1,136 B) RAM 9,984 B -> 9,984 B (unchanged) Teensy 4.0 / AutoResearch (Large-memory): flash 357,376 B -> 348,160 B (-9,216 B saved, -2.6%) RAM 112,576 B -> 110,528 B (-2,048 B saved) `fl::function`-related symbol mass on LPC845 dropped from 3,164 B (post- #3084) to 2,302 B (-862 B specifically from the variant collapse, the rest is downstream DCE). The Low-memory `FL_FUNCTION_FULL_VARIANT` macro is no longer needed -- both tiers share the same Option B implementation. The Low-memory "no-op heap-fallback" branch from #3077/#3084 is replaced by the real `HeapHolder` path; behavior is now uniform across all targets. ## Rename: F -> Func template parameter Renamed the template parameter throughout to `Func` because Arduino's `Arduino.h` (LPC8xx core, AVR core) defines `F()` as a PROGMEM-string preprocessor macro that collides with `F` used as a template parameter name. Same root cause as #3086's m0clockless_c.h fix. Refs #3235 Tier 1B, #3237
Summary
Collapses
fl::function's callable variant from 5 alternatives to 2 (FreeFunctionCallable+InlinedLambda) on Low-memory targets, gated byFL_PLATFORM_HAS_LARGE_MEMORY. Closes #3077; clears 35% of the meta #3079 overage.Numbers (LPC845-BRK,
arm-none-eabi-nm --print-size)fl::functionsymbol mass.text(-DFASTLED_LPC_RX_SCT_WS2812=1)What changed
Storagetypedef is nowvariant<FreeFunctionCallable, InlinedLambda>on Low-memory builds, dropping theshared_ptr<CallableBase>heap fallback and the twoMemberCallablestructs.tests/fl/stl/functional.cppandtests/shared/fl_unittest.huse member-function constructors (host tests; full variant active there). No production / embedded path is affected.operator()dispatch branches and the member-function constructors are#if-gated so the slim variant doesn't reference dropped types.Rrather than crash).FASTLED_INLINE_LAMBDA_SIZEbumped 64 → 96 on Low-memory only, to absorbUIButton::onClicked's outer-function-capturing wrapper closure (80 B). RAM cost ~32 B perfl::functioninstance; ~128 B total on LPC8xx (4-entry RPC dispatch table).Test plan
bash test --cpp functional→ passed (full variant active on host)PLATFORMIO_SRC_DIR=examples/AutoResearch fbuild build -e lpc845brkwith-DFASTLED_LPC_RX_SCT_WS2812=1→ built; flash dropped 3.9 KBnm --print-sizeverification: zero references to droppedCallableBase/NonConstMemberCallable/ConstMemberCallabletypes on LPC845 buildCaveats
This PR alone does NOT clear the 11 KB overage that blocks
FASTLED_LPC_RX_SCT_WS2812=1from shipping default-on. It's one of four sub-issues under meta #3079; the remaining ~7.5 KB needs at least one of #3076 (soft-FP cascade), #3081 (RPC dispatch slim), or #3082 (JSON codec slim) to land before the WS2812 SCT loopback RPC binding can be enabled by default onlpc845brk.Related
agents/docs/binary-size-analysis.md— bloat measurement methodology🤖 Generated with Claude Code
Summary by CodeRabbit