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

1+# Exception handling design notes
2+
3+Spinel emits C and currently implements Ruby exceptions with `setjmp`/`longjmp`
4+(`sp_exc_stack[]` / `sp_exc_top` in `lib/sp_runtime.h`; `begin/rescue/ensure/
5+retry` lowered in codegen). This document records the design goals, the
6+alternatives considered, and the measurements that settled the question, so the
7+analysis is not re-derived each time.
8+
9+## Goals (matz)
10+
11+- Cost when **no** exception is thrown must be **zero or very low**.
12+- Cost **when** an exception is thrown does not matter.
13+- `setjmp`/`longjmp` should be avoided if practical.
14+- Generated C verbosity does not matter (it is machine-generated).
15+- Returning a struct (value + error channel) is acceptable.
16+- Sequential per-call checking is a cost concern.
17+- **Microcontroller (low-memory) execution is a core motivation and cannot be dropped.**
18+
19+## The fundamental C constraint
20+
21+A cross-frame non-local jump in portable C requires **either** `setjmp`/`longjmp`
22+**or** the platform unwinder (`_Unwind_*`). Avoiding both forces unwinding the
23+stack one frame at a time via **return-value propagation** — i.e. a check after
24+every call that may raise. So "zero happy-path instructions" is only reachable
25+with table-based unwinding (C++/Itanium EH).
26+
27+## Mechanisms by happy-path cost
28+
29+| Mechanism | Examples | Happy path | Unwind | Fits a C emitter |
30+|---|---|---|---|---|
31+| setjmp/longjmp | Lua, mruby, CRuby, current Spinel | volatile residual | med | yes (current) |
32+| Table-based EH | C++, Rust panic, Swift, Crystal | "zero" instructions, but see measurement | heavy | only via C++ output |
33+| error-in-register / error union | Swift `throws`, Zig `!T`, Herbceptions | one predictable branch per throwing call | light | codegen change, per-call cost |
34+| Return-value flag | Go err, CPython, Nim `--exceptions:goto` | per-call check | light | codegen change |
35+| C++ try/catch (looks-C via macros) | Nim C++ backend, Haxe | see measurement | heavy | C++ toolchain |
36+
37+## Microcontroller reality
38+
39+C++ **exceptions** are almost always disabled on MCUs (`-fno-exceptions`):
40+unwind tables consume flash, the unwinder adds footprint, `throw` allocates and
41+has non-deterministic timing. arm-none-eabi / avr-gcc / ESP-IDF / Zephyr all
42+default exceptions off; MISRA/AUTOSAR restrict them. So **C++ EH is unavailable
43+on the MCU target**, and `setjmp` (no unwind tables, tiny `jmp_buf`) is the
44+right low-memory mechanism there — return-value would add code at every call
45+site, which is *worse* for flash. This is why mruby/Lua use setjmp on embedded.
46+
47+A macro abstraction (`SP_TRY` / `SP_RESCUE` / `SP_RAISE`) can switch cleanly
48+between **two boundary-only mechanisms** (C++ EH on host, setjmp on MCU) because
49+neither needs per-intermediate-call code. It **cannot** abstract return-value
50+(that needs codegen to emit per-call propagation, not just macro expansion).
51+
52+## Measurements
53+
54+### Prior (2026-06-07): return-value rejected
55+
56+A global `sp_err` flag + `if (sp_err) goto` after every statement was
57+prototyped and measured: optcarrot **753 -> 527 fps (~-30%)**. optcarrot is
58+method-call-dense = worst case for per-call checks. Rejected.
59+
60+### 2026-06-18: C++ EH measured (this session)
61+
62+optcarrot's generated C was compiled and run as C++ (checksum 59662 preserved).
63+
64+Feasibility — C++ compatibility is **not** a real barrier:
65+- 33 g++ errors total; **~73% are `volatile sp_RbVal`** copy errors, i.e. caused
66+ by the setjmp `volatile` machinery that a C++-EH (no-setjmp) design removes.
67+- The rest: an anonymous `enum` inside `struct sp_Val` needs hoisting to file
68+ scope (C injects its enumerators into the enclosing scope, C++ does not;
69+ 1 line), 2 implicit `void*` conversions (explicit cast / `-fpermissive`), and
70+ archive symbols need `extern "C"` (C++ would mangle the calls otherwise).
71+- No designated initializers in `sp_runtime.h` (the worst C/C++ landmine is absent).
72+- 1 C++-keyword identifier collision (`this`) in optcarrot — mangle to fix.
73+
74+Runtime cost (10 runs, max fps; same source, only the EH flag differs):
75+
76+| build | fps | vs no-EH ceiling |
77+|---|---|---|
78+| g++ `-fno-exceptions` (volatile stripped) | **736** | — (ceiling) |
79+| current setjmp (gcc, volatile present) | **716** | -2.7% (volatile/setjmp residual) |
80+| g++ C++ EH enabled, no `noexcept` | **689** | **-6.4%** |
81+
82+Key finding: **C++ EH is not zero-cost here.** With *zero* actual `throw`s,
83+enabling `-fexceptions` costs ~6.4% purely from optimization inhibition (g++
84+treats every non-`noexcept` call as may-throw and maintains unwind state).
85+optcarrot is call-dense and GC'd (no destructors), yet the tax is large. As a
86+result **C++ EH (689) is slower than the current setjmp build (716)**: the
87+EH-enable tax (6.4%) exceeds the volatile tax (2.7%) it would remove.
88+
89+Caveat — `noexcept` ceiling: 689 is the no-annotation worst case. `-fno-exceptions`
90+(= effectively all-`noexcept`) is 736, so annotating provably-non-raising
91+functions `noexcept` could approach 736 and beat setjmp by ~3%. But that needs
92+the same can-raise analysis as the return-value approach, the genuinely-raising
93+functions still pay, and the realistic landing is between 689 and 736.
94+
95+## Conclusion (2026-06-18)
96+
97+- **Keep `setjmp`/`longjmp`.** Re-confirmed by the new C++ EH data: EH's ceiling
98+ is only ~setjmp+3% (needs full `noexcept` analysis) and its floor is below
99+ setjmp; return-value was -30%. No mechanism beats setjmp clearly on the
100+ happy path for this call-dense workload, and setjmp is also the correct
101+ low-memory choice for the MCU target.
102+- **The real, bounded win is the volatile residual (~2.7%)**, taken without
103+ replacing the mechanism — narrow `volatile` to values that actually live
104+ across a `begin/rescue/retry` boundary (see SETJMP.md), not whole functions.
105+- C++ EH (looks-C via macros) stays feasible and is the only route to true
106+ zero-instruction happy path, but only if a future `noexcept`-via-can-raise
107+ experiment shows it reaching ~736; out of the box it regresses. Parked.
108+- Related latent correctness items on the setjmp path: #773 (volatile pointer
109+ locals), #1474 (fiber x exception cross-stack longjmp).
110+
111+## Reproduce
112+
113+```sh
114+make optcarrot # regenerates build/optcarrot-single.c (WRAP)
115+sed 's/\bvolatile //g' build/optcarrot-single.c > /tmp/oc.cpp
116+# patch a copy of lib/sp_runtime.h: hoist `enum {SP_PROC2,...}` out of struct sp_Val;
117+# wrap the header body in extern "C" { ... }
118+g++ -std=c++17 -O2 -fpermissive -I/tmp/cpplib -Ilib/regexp -DSP_INT_OVERFLOW_MODE_WRAP \
119+ -c /tmp/oc.cpp -o /tmp/oc.o # EH on
120+g++ ... -fno-exceptions ... # EH off (ceiling)
121+g++ -O2 /tmp/oc.o lib/libspinel_rt.a -lm -Wl,--gc-sections -o /tmp/oc_cpp_eh
122+```