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 Semantics
2+
3+Phase 1 design doc for aligning all typed-hash variants' `[]` lookup
4+with Ruby semantics (`h[missing_key] == nil`).
5+
6+## Problem
7+
8+Of 8 typed-hash variants, 5 violate Ruby semantics by returning a
9+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 truthy
25+ for the string/int variants, contrary to Ruby
26+- `cached = h[k]; if cached.length > 0` — works around the bug at
27+ caller-side but pollutes call sites
28+- The codegen's own `has_key?+[]` fusion bug (uncovered during
29+ measurement work) was triggered by `StrStrHash_get` returning ""
30+ on miss instead of NULL
31+
32+## Sentinel Convention
33+
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 inhabitant
39+- **Scalar-nullable** (`is_scalar_nullable_type`): `int?` — uses
40+ `SP_INT_NIL = INT64_MIN` sentinel via the existing
41+ `sp_int_is_nil(v)` predicate
42+
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 Audit
55+
56+### Internal-safe callers (no change needed)
57+
58+These iterate `h->order[i]` which holds **existing** keys, so they
59+never trigger the missing-key path:
60+
61+- `*Hash_values()` — values list from order
62+- `*Hash_dup()` — clone via order walk
63+- `*Hash_merge()` — combine two hashes, key from order
64+- `*Hash_eq()` — compare; checks `has_key?` first per-key
65+- `*Hash_update()` — copy values from order
66+- `*Hash_invert()` — swap k/v, key from order
67+- `*Hash_inspect()` — render via order
68+- `*Hash_to_<other_variant>()` — convert via order walk
69+- `*Hash_from_<other_variant>()` — likewise
70+
71+### `fetch(k, default)` callers (already correct)
72+
73+The `Hash#fetch(k, default)` codegen path already wraps with
74+`has_key?` and supplies the user's `default`:
75+
76+```c
77+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 int
81+variants or `NULL` for the str variants (issues #671 / #682 wired
82+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+```c
99+sp_<Hash>_get(rc, key) // returns 0 / "" on miss — wrong
100+```
101+
102+The Phase A change makes these return the correct sentinel without
103+needing a wrapper `has_key? ? get : SENTINEL` (because `_get` itself
104+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]` reads
112+
113+### `_eq` callers (no change needed)
114+
115+`*Hash_eq` walks a's keys, checks `has_key?(b, k)` first, then
116+compares values. The `_get` calls inside `_eq` are guarded — never
117+miss.
118+
119+### `_inspect` callers (no change needed)
120+
121+Inspect walks `h->order[i]` — existing keys only.
122+
123+## Analyzer `[]` Return Type Table
124+
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. Strings
153+keep their type label because the storage (`const char *`) is
154+already nullable; only the runtime miss return changes.
155+
156+## Downstream Codegen — NULL / SP_INT_NIL Propagation
157+
158+Once `_get` returns NULL / SP_INT_NIL on miss, every downstream
159+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 0
165+ (NULL-safe per lib/sp_runtime.h:494)
166+- `sp_str_concat(NULL, "x")` falls back to `sp_str_empty` for NULL
167+ (NULL-safe coalesce per lib/sp_runtime.h:1129)
168+
169+These produce silently-not-Ruby-but-safe behavior (Ruby's
170+`nil.length` raises NoMethodError; spinel returns 0). Phase A keeps
171+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 — CORRECT
177+
178+### Int operations on int?
179+
180+The codegen already has helpers for int? from prior work
181+(`compile_expr_int_opt_*`, sp_int_is_nil, etc.). Need to extend the
182+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 for
186+sp_str_index_opt etc., spinel_codegen.rb:12290+):
187+
188+```c
189+if (sp_int_is_nil(lv_x)) /* falsy */
190+```
191+
192+### Arithmetic on SP_INT_NIL
193+
194+Out of scope for Phase A — same constraint as the existing `int?`
195+work: arithmetic on SP_INT_NIL silently produces garbage (the
196+sentinel is a real `int64_t` value, so `SP_INT_NIL + 1` is just
197+`INT64_MIN + 1` — surprising but not a crash). Documented in
198+existing int? work (commit f6c3b6d era).
199+
200+## Phase 2 Scope
201+
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`: same
208+2. `spinel_codegen.rb` `emit_*_runtime` for `SymStrHash`:
209+ - `sp_SymStrHash_get`: same NULL change
210+3. Verify no internal caller depends on `_get` returning non-NULL
211+ (the `_values`, `_dup`, etc. paths — they read `h->order[i]`
212+ which are existing keys, so the return is always non-NULL from
213+ `h->vals[idx]`, not the miss fallback)
214+4. `make test` + bootstrap + optcarrot regression checks
215+
216+Phase 3 widens analyze's `[]` return type for string-valued hashes
217+(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 Scope
221+
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-int
230+ 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 Scope
238+
239+- Add regression tests:
240+ - `test/str_str_hash_missing_returns_nil.rb` — `if h["missing"]; ...; end` falsy path
241+ - `test/str_int_hash_missing_returns_nil.rb` — `if h["missing"]; ...; end` falsy
242+ - `test/sym_int_hash_missing_arithmetic.rb` — document SP_INT_NIL arith caveat
243+- `make test` (all pass)
244+- `make bootstrap` (gen2 == gen3)
245+- `make optcarrot` (checksum 59662)
246+
247+## Risks
248+
249+1. **Bootstrap self-host**: spinel_analyze.rb + spinel_codegen.rb
250+ use typed hashes extensively. Per-phase bootstrap convergence
251+ required.
252+2. **optcarrot regression**: prior body-driven-widening cascade
253+ (memory: body_usage_widening_optcarrot) warns that even
254+ post-fixpoint widening can cascade-break optcarrot. Phase 4's
255+ `int?` widening is the highest-risk step.
256+3. **Test-suite assumptions**: any existing test that asserts
257+ `h[missing] == ""` or `h[missing] == 0` semantics needs update.
258+ Survey via `grep -rE 'Hash.*\[".*"\].*== "?"' test/`.
259+
260+## Order of Operations
261+
262+```
263+Phase 1 — survey + this doc [current]
264+Phase 2 — *StrHash → NULL next
265+Phase 3 — *StrHash codegen tightening
266+Phase 4 — *IntHash → SP_INT_NIL bigger surgery
267+Phase 5 — regression tests + final verify
268+```
269+
270+Each phase ends with a green CI before the next begins. If Phase 4
271+regresses optcarrot, fall back to Phase 4a (per-variant rollout
272+with feature flag).