Commit cefccdef
cefccdef2a2aMerged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · +1 added
Description
docs: Hash nullable semantics design (Phase 1)
Phase 1 of the typed-hash nullable rollout. Documents the survey findings, sentinel convention (NULL for pointer-valued, SP_INT_NIL for int-valued), per-variant call-site audit, analyzer return-type table, and the phased migration plan.
Findings:
- 5 of 8 typed-hash variants violate Ruby semantics on missing-key lookup (StrInt/SymInt return 0, StrStr/SymStr/IntStr return "")
- The 3 *PolyHash variants are already correct (sp_box_nil())
- Internal callers (values, dup, merge, eq, etc.) iterate h->order[i] and never trigger the miss path -- unchanged by the rollout
- Hash#fetch(k, default) is already correct via has_key? guard
- 10 codegen sites emit raw
sp_<Hash>_get(...)for h[k] direct dispatch -- those are the targets - SP_INT_NIL infrastructure (lib/sp_runtime.h:74) is reusable from prior int? work (sp_str_index_opt etc.)
- String runtime is NULL-safe (sp_str_length / sp_str_eq / sp_str_concat)
Phases 2-5 outlined in the doc:
- Phase 2: *StrHash _get returns NULL (1 session)
- Phase 3: codegen NULL propagation tightening (1 session)
- Phase 4: *IntHash _get returns SP_INT_NIL, lhs widens to int? (1-2 sessions)
- Phase 5: regression tests + bootstrap + optcarrot (1 session)
Co-Authored-By: Claude Opus 4.7 [email protected]
Details
- Commit
- cefccdef2a2a
- Parent
- b2d6afa6251d
docs/HASH-NULLABLE.mdaddedView file
1+
# Hash Nullable Semantics2+
3+
Phase 1 design doc for aligning all typed-hash variants' `[]` lookup4+
with Ruby semantics (`h[missing_key] == nil`).5+
6+
## Problem7+
8+
Of 8 typed-hash variants, 5 violate Ruby semantics by returning a9+
non-nil sentinel on missing-key lookup:10+
11+
| Variant | Value type | Missing-key returns | Ruby semantics |12+
|---|---|---|---|13+
| `StrIntHash` | `mrb_int` | `0` | nil |14+
| `SymIntHash` | `mrb_int` | `0` | nil |15+
| `StrStrHash` | `const char *` | `sp_str_empty` ("") | nil (NULL) |16+
| `SymStrHash` | `const char *` | `sp_str_empty` ("") | nil (NULL) |17+
| `IntStrHash` | `const char *` | `sp_str_empty` ("") | nil (NULL) |18+
| `StrPolyHash` | `sp_RbVal` | `sp_box_nil()` | nil (correct) |19+
| `SymPolyHash` | `sp_RbVal` | `sp_box_nil()` | nil (correct) |20+
| `PolyPolyHash` | `sp_RbVal` | `sp_box_nil()` | nil (correct) |21+
22+
User-visible consequences:23+
24+
- `if h[:missing]; ... end` — current spinel sees "" / 0 as truthy25+
for the string/int variants, contrary to Ruby26+
- `cached = h[k]; if cached.length > 0` — works around the bug at27+
caller-side but pollutes call sites28+
- The codegen's own `has_key?+[]` fusion bug (uncovered during29+
measurement work) was triggered by `StrStrHash_get` returning ""30+
on miss instead of NULL31+
32+
## Sentinel Convention33+
34+
Reuse spinel's existing dual nullable encoding:35+
36+
- **Pointer-nullable** (`is_nullable_pointer_type`): `string`,37+
`<hash variants>`, `<array variants>`, `<obj_X>`, etc. — `NULL`38+
is the nil inhabitant39+
- **Scalar-nullable** (`is_scalar_nullable_type`): `int?` — uses40+
`SP_INT_NIL = INT64_MIN` sentinel via the existing41+
`sp_int_is_nil(v)` predicate42+
43+
Mapping per variant:44+
45+
| Variant | New `_get` returns on miss | LV slot when `x = h[k]` |46+
|---|---|---|47+
| `StrIntHash` | `SP_INT_NIL` | `int?` (mrb_int with sentinel) |48+
| `SymIntHash` | `SP_INT_NIL` | `int?` |49+
| `StrStrHash` | `NULL` | `string` (const char *, already nullable) |50+
| `SymStrHash` | `NULL` | `string` |51+
| `IntStrHash` | `NULL` | `string` |52+
| `*PolyHash` | (unchanged) | `poly` (already nullable via box_nil) |53+
54+
## Call-site Audit55+
56+
### Internal-safe callers (no change needed)57+
58+
These iterate `h->order[i]` which holds **existing** keys, so they59+
never trigger the missing-key path:60+
61+
- `*Hash_values()` — values list from order62+
- `*Hash_dup()` — clone via order walk63+
- `*Hash_merge()` — combine two hashes, key from order64+
- `*Hash_eq()` — compare; checks `has_key?` first per-key65+
- `*Hash_update()` — copy values from order66+
- `*Hash_invert()` — swap k/v, key from order67+
- `*Hash_inspect()` — render via order68+
- `*Hash_to_<other_variant>()` — convert via order walk69+
- `*Hash_from_<other_variant>()` — likewise70+
71+
### `fetch(k, default)` callers (already correct)72+
73+
The `Hash#fetch(k, default)` codegen path already wraps with74+
`has_key?` and supplies the user's `default`:75+
76+
```c77+
sp_StrIntHash_has_key(h, k) ? sp_StrIntHash_get(h, k) : <user_default>78+
```79+
80+
When user passes `nil`, the codegen emits `SP_INT_NIL` for the int81+
variants or `NULL` for the str variants (issues #671 / #682 wired82+
these up). Phase A is orthogonal — `fetch` keeps working.83+
84+
### `h[k]` direct callers (THE TARGET)85+
86+
5 sites in `spinel_codegen.rb` emit raw `sp_<Hash>_get(...)`:87+
88+
| Line | Variant |89+
|---|---|90+
| 20579, 20628 | `SymIntHash` |91+
| 20758, 20794 | `SymStrHash` |92+
| 21131, 21190 | `StrIntHash` |93+
| 21302, 21336 | `IntStrHash` |94+
| 21379, 21436 | `StrStrHash` |95+
96+
Each currently lowers `h[k]` to:97+
98+
```c99+
sp_<Hash>_get(rc, key) // returns 0 / "" on miss — wrong100+
```101+
102+
The Phase A change makes these return the correct sentinel without103+
needing a wrapper `has_key? ? get : SENTINEL` (because `_get` itself104+
is the wrapper now).105+
106+
### iter-with-key callers (no change needed)107+
108+
These read `h->order[i]` (existing keys) inside `each` / `keys` etc.109+
walks — they don't hit miss:110+
111+
- 20650, 21241, 21253, 21292, 21350, 21416 — all `h->order[i]` reads112+
113+
### `_eq` callers (no change needed)114+
115+
`*Hash_eq` walks a's keys, checks `has_key?(b, k)` first, then116+
compares values. The `_get` calls inside `_eq` are guarded — never117+
miss.118+
119+
### `_inspect` callers (no change needed)120+
121+
Inspect walks `h->order[i]` — existing keys only.122+
123+
## Analyzer `[]` Return Type Table124+
125+
Located at `spinel_analyze.rb:5304-5328` (the `mname == "[]"` arm).126+
Current mapping:127+
128+
| Recv type | `[]` returns |129+
|---|---|130+
| `str_int_hash` | `int` |131+
| `str_str_hash` | `string` |132+
| `int_str_hash` | `string` |133+
| `sym_int_hash` | `int` |134+
| `sym_str_hash` | `string` |135+
| `sym_poly_hash` | `poly` |136+
| `str_poly_hash` | `poly` |137+
| `poly_poly_hash` | `poly` |138+
139+
Phase A change:140+
141+
| Recv type | New `[]` returns |142+
|---|---|143+
| `str_int_hash` | `int?` |144+
| `str_str_hash` | `string` (already nullable via NULL) |145+
| `int_str_hash` | `string` |146+
| `sym_int_hash` | `int?` |147+
| `sym_str_hash` | `string` |148+
| `sym_poly_hash` | `poly` (unchanged) |149+
| `str_poly_hash` | `poly` (unchanged) |150+
| `poly_poly_hash` | `poly` (unchanged) |151+
152+
The `int` → `int?` widening is the main analyzer change. Strings153+
keep their type label because the storage (`const char *`) is154+
already nullable; only the runtime miss return changes.155+
156+
## Downstream Codegen — NULL / SP_INT_NIL Propagation157+
158+
Once `_get` returns NULL / SP_INT_NIL on miss, every downstream159+
operation on the result needs nullable-aware handling.160+
161+
### String operations (mostly already NULL-safe)162+
163+
- `sp_str_length(NULL)` returns 0 (NULL-safe per lib/sp_runtime.h:475)164+
- `sp_str_eq(NULL, NULL)` returns 1; `sp_str_eq(NULL, "x")` returns 0165+
(NULL-safe per lib/sp_runtime.h:494)166+
- `sp_str_concat(NULL, "x")` falls back to `sp_str_empty` for NULL167+
(NULL-safe coalesce per lib/sp_runtime.h:1129)168+
169+
These produce silently-not-Ruby-but-safe behavior (Ruby's170+
`nil.length` raises NoMethodError; spinel returns 0). Phase A keeps171+
the silent-coalesce behavior — only the **truthy check** changes.172+
173+
`if h[:missing]; ... end`:174+
- Before: `if (sp_str_empty)` — non-NULL pointer is truthy in C —175+
WRONG (Ruby says nil is falsy)176+
- After: `if (NULL)` — falsy in C — CORRECT177+
178+
### Int operations on int?179+
180+
The codegen already has helpers for int? from prior work181+
(`compile_expr_int_opt_*`, sp_int_is_nil, etc.). Need to extend the182+
inference walk to mark `x = h[k]` as widening x's slot to `int?`183+
when h is a typed int-valued hash.184+
185+
Truthy check on int? sentinel (already implemented for186+
sp_str_index_opt etc., spinel_codegen.rb:12290+):187+
188+
```c189+
if (sp_int_is_nil(lv_x)) /* falsy */190+
```191+
192+
### Arithmetic on SP_INT_NIL193+
194+
Out of scope for Phase A — same constraint as the existing `int?`195+
work: arithmetic on SP_INT_NIL silently produces garbage (the196+
sentinel is a real `int64_t` value, so `SP_INT_NIL + 1` is just197+
`INT64_MIN + 1` — surprising but not a crash). Documented in198+
existing int? work (commit f6c3b6d era).199+
200+
## Phase 2 Scope201+
202+
Implement only the `*StrHash` variants first:203+
204+
1. `lib/sp_runtime.h`:205+
- `sp_StrStrHash_get`: `return h->default_v ? h->default_v : sp_str_empty;`206+
→ `return h->default_v ? h->default_v : NULL;`207+
- `sp_IntStrHash_get`: same208+
2. `spinel_codegen.rb` `emit_*_runtime` for `SymStrHash`:209+
- `sp_SymStrHash_get`: same NULL change210+
3. Verify no internal caller depends on `_get` returning non-NULL211+
(the `_values`, `_dup`, etc. paths — they read `h->order[i]`212+
which are existing keys, so the return is always non-NULL from213+
`h->vals[idx]`, not the miss fallback)214+
4. `make test` + bootstrap + optcarrot regression checks215+
216+
Phase 3 widens analyze's `[]` return type for string-valued hashes217+
(no real change since `string` is already nullable at the C level —218+
mostly tightens up call-site emit where it assumed non-NULL).219+
220+
## Phase 4 Scope221+
222+
Implement `*IntHash` → SP_INT_NIL:223+
224+
1. `lib/sp_runtime.h` `sp_StrIntHash_get`: `return h->default_v;` →225+
`return SP_INT_NIL;` (drop `h->default_v` for the `[]` path —226+
`fetch(k, def)` already handles user default)227+
2. Similar for `SymIntHash`228+
3. Analyze: `str_int_hash[]` returns `int?` instead of `int`229+
4. Codegen: widen LV slot to `int?` when assigned from typed-int230+
hash `[]`231+
232+
Caveat: `default_v` is currently used by both `[]` AND `fetch(k)`233+
(no-arg `fetch`). Need to distinguish. Likely: keep `default_v`234+
field, but `_get` (which lowers `[]`) returns SP_INT_NIL always;235+
add `_fetch_default` or pass-through. Determined in Phase 4.236+
237+
## Phase 5 Scope238+
239+
- Add regression tests:240+
- `test/str_str_hash_missing_returns_nil.rb` — `if h["missing"]; ...; end` falsy path241+
- `test/str_int_hash_missing_returns_nil.rb` — `if h["missing"]; ...; end` falsy242+
- `test/sym_int_hash_missing_arithmetic.rb` — document SP_INT_NIL arith caveat243+
- `make test` (all pass)244+
- `make bootstrap` (gen2 == gen3)245+
- `make optcarrot` (checksum 59662)246+
247+
## Risks248+
249+
1. **Bootstrap self-host**: spinel_analyze.rb + spinel_codegen.rb250+
use typed hashes extensively. Per-phase bootstrap convergence251+
required.252+
2. **optcarrot regression**: prior body-driven-widening cascade253+
(memory: body_usage_widening_optcarrot) warns that even254+
post-fixpoint widening can cascade-break optcarrot. Phase 4's255+
`int?` widening is the highest-risk step.256+
3. **Test-suite assumptions**: any existing test that asserts257+
`h[missing] == ""` or `h[missing] == 0` semantics needs update.258+
Survey via `grep -rE 'Hash.*\[".*"\].*== "?"' test/`.259+
260+
## Order of Operations261+
262+
```263+
Phase 1 — survey + this doc [current]264+
Phase 2 — *StrHash → NULL next265+
Phase 3 — *StrHash codegen tightening 266+
Phase 4 — *IntHash → SP_INT_NIL bigger surgery267+
Phase 5 — regression tests + final verify 268+
```269+
270+
Each phase ends with a green CI before the next begins. If Phase 4271+
regresses optcarrot, fall back to Phase 4a (per-variant rollout272+
with feature flag).