Commit 7db5be94
7db5be948f7bMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 13 files · +8 added · ~5 modified
Description
Support inject/reduce over an each.with_index enumerator
arr.each.with_index.inject(init) { |acc, (val, idx)| ... } (and the
each_with_index.inject and reduce spellings) was rejected as an
unsupported call, even though each.with_index is a common indexed-fold
idiom (running totals, base-N decoding, weighted sums).
each.with_index / each_with_index is a blockless enumerator yielding
[element, index] pairs. A new codegen path (emit_each_with_index_chain)
recognises the exact chain shape and lowers the fold as an indexed loop,
binding the pair as a destructured |acc, (v, i)| or a single |acc, pair|
(a 2-element array). analyze types the fold params (acc from the seed,
v = element, i = int) and infers the chain's result type so consumers
(puts, assignment) dispatch correctly. The match is gated tightly on the
chain shape, so no other call path is affected.
Verified vs MRI incl. base26 decode, string accumulator, offset, and the each_with_index spelling. 956 test (gcc + clang) / 57 bench / optcarrot 59662 (734 fps); clean under clang -fsanitize=address,undefined.
Closes #1481
Co-Authored-By: Claude Opus 4.8 [email protected]
Details
- Commit
- 7db5be948f7b
- Parent
- 913a83318df6
EXCEPTIONS.mdaddedView file
# Exception handling design notesSpinel emits C and currently implements Ruby exceptions with `setjmp`/`longjmp`(`sp_exc_stack[]` / `sp_exc_top` in `lib/sp_runtime.h`; `begin/rescue/ensure/retry` lowered in codegen). This document records the design goals, thealternatives considered, and the measurements that settled the question, so theanalysis is not re-derived each time.## Goals (matz)- Cost when **no** exception is thrown must be **zero or very low**.- Cost **when** an exception is thrown does not matter.- `setjmp`/`longjmp` should be avoided if practical.- Generated C verbosity does not matter (it is machine-generated).- Returning a struct (value + error channel) is acceptable.- Sequential per-call checking is a cost concern.- **Microcontroller (low-memory) execution is a core motivation and cannot be dropped.**## The fundamental C constraintA cross-frame non-local jump in portable C requires **either** `setjmp`/`longjmp`**or** the platform unwinder (`_Unwind_*`). Avoiding both forces unwinding thestack one frame at a time via **return-value propagation** — i.e. a check afterevery call that may raise. So "zero happy-path instructions" is only reachablewith table-based unwinding (C++/Itanium EH).## Mechanisms by happy-path cost| Mechanism | Examples | Happy path | Unwind | Fits a C emitter ||---|---|---|---|---|| setjmp/longjmp | Lua, mruby, CRuby, current Spinel | volatile residual | med | yes (current) || Table-based EH | C++, Rust panic, Swift, Crystal | "zero" instructions, but see measurement | heavy | only via C++ output || error-in-register / error union | Swift `throws`, Zig `!T`, Herbceptions | one predictable branch per throwing call | light | codegen change, per-call cost || Return-value flag | Go err, CPython, Nim `--exceptions:goto` | per-call check | light | codegen change || C++ try/catch (looks-C via macros) | Nim C++ backend, Haxe | see measurement | heavy | C++ toolchain |## Microcontroller realityC++ **exceptions** are almost always disabled on MCUs (`-fno-exceptions`):unwind tables consume flash, the unwinder adds footprint, `throw` allocates andhas non-deterministic timing. arm-none-eabi / avr-gcc / ESP-IDF / Zephyr alldefault exceptions off; MISRA/AUTOSAR restrict them. So **C++ EH is unavailableon the MCU target**, and `setjmp` (no unwind tables, tiny `jmp_buf`) is theright low-memory mechanism there — return-value would add code at every callsite, which is *worse* for flash. This is why mruby/Lua use setjmp on embedded.A macro abstraction (`SP_TRY` / `SP_RESCUE` / `SP_RAISE`) can switch cleanlybetween **two boundary-only mechanisms** (C++ EH on host, setjmp on MCU) becauseneither needs per-intermediate-call code. It **cannot** abstract return-value(that needs codegen to emit per-call propagation, not just macro expansion).## Measurements### Prior (2026-06-07): return-value rejectedA global `sp_err` flag + `if (sp_err) goto` after every statement wasprototyped and measured: optcarrot **753 -> 527 fps (~-30%)**. optcarrot ismethod-call-dense = worst case for per-call checks. Rejected.### 2026-06-18: C++ EH measured (this session)optcarrot's generated C was compiled and run as C++ (checksum 59662 preserved).Feasibility — C++ compatibility is **not** a real barrier:- 33 g++ errors total; **~73% are `volatile sp_RbVal`** copy errors, i.e. caused by the setjmp `volatile` machinery that a C++-EH (no-setjmp) design removes.- The rest: an anonymous `enum` inside `struct sp_Val` needs hoisting to file scope (C injects its enumerators into the enclosing scope, C++ does not; 1 line), 2 implicit `void*` conversions (explicit cast / `-fpermissive`), and archive symbols need `extern "C"` (C++ would mangle the calls otherwise).- No designated initializers in `sp_runtime.h` (the worst C/C++ landmine is absent).- 1 C++-keyword identifier collision (`this`) in optcarrot — mangle to fix.Runtime cost (10 runs, max fps; same source, only the EH flag differs):| build | fps | vs no-EH ceiling ||---|---|---|| g++ `-fno-exceptions` (volatile stripped) | **736** | — (ceiling) || current setjmp (gcc, volatile present) | **716** | -2.7% (volatile/setjmp residual) || g++ C++ EH enabled, no `noexcept` | **689** | **-6.4%** |Key finding: **C++ EH is not zero-cost here.** With *zero* actual `throw`s,enabling `-fexceptions` costs ~6.4% purely from optimization inhibition (g++treats every non-`noexcept` call as may-throw and maintains unwind state).optcarrot is call-dense and GC'd (no destructors), yet the tax is large. As aresult **C++ EH (689) is slower than the current setjmp build (716)**: theEH-enable tax (6.4%) exceeds the volatile tax (2.7%) it would remove.Caveat — `noexcept` ceiling: 689 is the no-annotation worst case. `-fno-exceptions`(= effectively all-`noexcept`) is 736, so annotating provably-non-raisingfunctions `noexcept` could approach 736 and beat setjmp by ~3%. But that needsthe same can-raise analysis as the return-value approach, the genuinely-raisingfunctions still pay, and the realistic landing is between 689 and 736.## Conclusion (2026-06-18)- **Keep `setjmp`/`longjmp`.** Re-confirmed by the new C++ EH data: EH's ceiling is only ~setjmp+3% (needs full `noexcept` analysis) and its floor is below setjmp; return-value was -30%. No mechanism beats setjmp clearly on the happy path for this call-dense workload, and setjmp is also the correct low-memory choice for the MCU target.- **The real, bounded win is the volatile residual (~2.7%)**, taken without replacing the mechanism — narrow `volatile` to values that actually live across a `begin/rescue/retry` boundary (see SETJMP.md), not whole functions.- C++ EH (looks-C via macros) stays feasible and is the only route to true zero-instruction happy path, but only if a future `noexcept`-via-can-raise experiment shows it reaching ~736; out of the box it regresses. Parked.- Related latent correctness items on the setjmp path: #773 (volatile pointer locals), #1474 (fiber x exception cross-stack longjmp).## Reproduce```shmake optcarrot # regenerates build/optcarrot-single.c (WRAP)sed 's/\bvolatile //g' build/optcarrot-single.c > /tmp/oc.cpp# patch a copy of lib/sp_runtime.h: hoist `enum {SP_PROC2,...}` out of struct sp_Val;# wrap the header body in extern "C" { ... }g++ -std=c++17 -O2 -fpermissive -I/tmp/cpplib -Ilib/regexp -DSP_INT_OVERFLOW_MODE_WRAP \ -c /tmp/oc.cpp -o /tmp/oc.o # EH ong++ ... -fno-exceptions ... # EH off (ceiling)g++ -O2 /tmp/oc.o lib/libspinel_rt.a -lm -Wl,--gc-sections -o /tmp/oc_cpp_eh```ISSUE_TRIAGE.mdaddedView file
Loading diff…
OPTIMIZATION.mdaddedView file
Loading diff…
PR908.mdaddedView file
Loading diff…
SETJMP.mdaddedView file
Loading diff…
src/analyze_infer.cmodifiedView file
Loading diff…
src/analyze_pass.cmodifiedView file
Loading diff…
src/codegen_call.cmodifiedView file
Loading diff…
src/codegen_fold.cmodifiedView file
Loading diff…
src/codegen_internal.hmodifiedView file
Loading diff…
t3b.types.jsonaddedView file
Loading diff…
test/each_with_index_inject.rbaddedView file
Loading diff…
test/each_with_index_inject.rb.expectedaddedView file
Loading diff…