Commit e7af2c63

e7af2c6317b4Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 5 months ago · 4 files · -4 deleted

Description

docs: remove plan docs for features now implemented

These were "to-implement" planning notes whose feature has shipped and which nothing references; the design intent now lives in the code (and is recoverable from history if needed):

  • issue-646-plan.md (#646 fixed and closed)
  • setbyte-semantic-plan.md (String#setbyte implemented)
  • PROC-SUPPORT.md (first-class Proc/lambda implemented)
  • HASH-NULLABLE.md (typed-hash nil-on-miss implemented)

Kept: promote-mode-plan.md (--int-overflow=promote still partial) and CLASS-OBJECT.md (Phase 2+ pending, referenced by tests), plus the reference docs (AST / ANALYZE-IR / FFI / RBS-EXTRACT / limitations / INCOMPATIBILITIES / FLOAT-ROUNDING) that document the current system.

Co-Authored-By: Claude Opus 4.8 [email protected]

Details

Commit
e7af2c6317b4
Parent
2c17201e68e6

docs/HASH-NULLABLE.mddeleted

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-### Sym-valued hashes
55-
56-spinel currently has no dedicated `*SymHash` variant (no `sym_sym_hash`,
57-`str_sym_hash`, or `int_sym_hash`). Hash literals with symbol values
58-(e.g. `{a: :x}`) infer as `sym_poly_hash` / `str_poly_hash` etc. and
59-box symbols into `sp_RbVal` (SP_TAG_SYM) -- so missing-key already
60-returns `sp_box_nil()`, Ruby-compatible.
61-
62-If a future memory-optimization Phase introduces dedicated
63-`*SymHash` variants (sp_sym = mrb_int storage, 8 bytes/entry vs
64-sp_RbVal's 16 bytes), the natural nil sentinel is
65-`((sp_sym)-1)` -- which already serves as `c_default_val("symbol")`
66-in spinel_codegen.rb. The intern table's index 0 is reserved for
67-the first symbol, so -1 is unambiguously "no symbol". A
68-`sym?` scalar-nullable type would follow the same shape as
69-`int?` (sentinel-based, not pointer-based), gated on
70-`is_scalar_nullable_type`. Out of scope for the current rollout.
71-
72-## Call-site Audit
73-
74-### Internal-safe callers (no change needed)
75-
76-These iterate `h->order[i]` which holds **existing** keys, so they
77-never trigger the missing-key path:
78-
79-- `*Hash_values()` — values list from order
80-- `*Hash_dup()` — clone via order walk
81-- `*Hash_merge()` — combine two hashes, key from order
82-- `*Hash_eq()` — compare; checks `has_key?` first per-key
83-- `*Hash_update()` — copy values from order
84-- `*Hash_invert()` — swap k/v, key from order
85-- `*Hash_inspect()` — render via order
86-- `*Hash_to_<other_variant>()` — convert via order walk
87-- `*Hash_from_<other_variant>()` — likewise
88-
89-### `fetch(k, default)` callers (already correct)
90-
91-The `Hash#fetch(k, default)` codegen path already wraps with
92-`has_key?` and supplies the user's `default`:
93-
94-```c
95-sp_StrIntHash_has_key(h, k) ? sp_StrIntHash_get(h, k) : <user_default>
96-```
97-
98-When user passes `nil`, the codegen emits `SP_INT_NIL` for the int
99-variants or `NULL` for the str variants (issues #671 / #682 wired
100-these up). Phase A is orthogonal — `fetch` keeps working.
101-
102-### `h[k]` direct callers (THE TARGET)
103-
104-5 sites in `spinel_codegen.rb` emit raw `sp_<Hash>_get(...)`:
105-
106-| Line | Variant |
107-|---|---|
108-| 20579, 20628 | `SymIntHash` |
109-| 20758, 20794 | `SymStrHash` |
110-| 21131, 21190 | `StrIntHash` |
111-| 21302, 21336 | `IntStrHash` |
112-| 21379, 21436 | `StrStrHash` |
113-
114-Each currently lowers `h[k]` to:
115-
116-```c
117-sp_<Hash>_get(rc, key) // returns 0 / "" on miss — wrong
118-```
119-
120-The Phase A change makes these return the correct sentinel without
121-needing a wrapper `has_key? ? get : SENTINEL` (because `_get` itself
122-is the wrapper now).
123-
124-### iter-with-key callers (no change needed)
125-
126-These read `h->order[i]` (existing keys) inside `each` / `keys` etc.
127-walks — they don't hit miss:
128-
129-- 20650, 21241, 21253, 21292, 21350, 21416 — all `h->order[i]` reads
130-
131-### `_eq` callers (no change needed)
132-
133-`*Hash_eq` walks a's keys, checks `has_key?(b, k)` first, then
134-compares values. The `_get` calls inside `_eq` are guarded — never
135-miss.
136-
137-### `_inspect` callers (no change needed)
138-
139-Inspect walks `h->order[i]` — existing keys only.
140-
141-## Analyzer `[]` Return Type Table
142-
143-Located at `spinel_analyze.rb:5304-5328` (the `mname == "[]"` arm).
144-Current mapping:
145-
146-| Recv type | `[]` returns |
147-|---|---|
148-| `str_int_hash` | `int` |
149-| `str_str_hash` | `string` |
150-| `int_str_hash` | `string` |
151-| `sym_int_hash` | `int` |
152-| `sym_str_hash` | `string` |
153-| `sym_poly_hash` | `poly` |
154-| `str_poly_hash` | `poly` |
155-| `poly_poly_hash` | `poly` |
156-
157-Phase A change:
158-
159-| Recv type | New `[]` returns |
160-|---|---|
161-| `str_int_hash` | `int?` |
162-| `str_str_hash` | `string` (already nullable via NULL) |
163-| `int_str_hash` | `string` |
164-| `sym_int_hash` | `int?` |
165-| `sym_str_hash` | `string` |
166-| `sym_poly_hash` | `poly` (unchanged) |
167-| `str_poly_hash` | `poly` (unchanged) |
168-| `poly_poly_hash` | `poly` (unchanged) |
169-
170-The `int` → `int?` widening is the main analyzer change. Strings
171-keep their type label because the storage (`const char *`) is
172-already nullable; only the runtime miss return changes.
173-
174-## Downstream Codegen — NULL / SP_INT_NIL Propagation
175-
176-Once `_get` returns NULL / SP_INT_NIL on miss, every downstream
177-operation on the result needs nullable-aware handling.
178-
179-### String operations (mostly already NULL-safe)
180-
181-- `sp_str_length(NULL)` returns 0 (NULL-safe per lib/sp_runtime.h:475)
182-- `sp_str_eq(NULL, NULL)` returns 1; `sp_str_eq(NULL, "x")` returns 0
183- (NULL-safe per lib/sp_runtime.h:494)
184-- `sp_str_concat(NULL, "x")` falls back to `sp_str_empty` for NULL
185- (NULL-safe coalesce per lib/sp_runtime.h:1129)
186-
187-These produce silently-not-Ruby-but-safe behavior (Ruby's
188-`nil.length` raises NoMethodError; spinel returns 0). Phase A keeps
189-the silent-coalesce behavior — only the **truthy check** changes.
190-
191-`if h[:missing]; ... end`:
192-- Before: `if (sp_str_empty)` — non-NULL pointer is truthy in C —
193- WRONG (Ruby says nil is falsy)
194-- After: `if (NULL)` — falsy in C — CORRECT
195-
196-### Int operations on int?
197-
198-The codegen already has helpers for int? from prior work
199-(`compile_expr_int_opt_*`, sp_int_is_nil, etc.). Need to extend the
200-inference walk to mark `x = h[k]` as widening x's slot to `int?`
201-when h is a typed int-valued hash.
202-
203-Truthy check on int? sentinel (already implemented for
204-sp_str_index_opt etc., spinel_codegen.rb:12290+):
205-
206-```c
207-if (sp_int_is_nil(lv_x)) /* falsy */
208-```
209-
210-### Arithmetic on SP_INT_NIL
211-
212-Out of scope for Phase A — same constraint as the existing `int?`
213-work: arithmetic on SP_INT_NIL silently produces garbage (the
214-sentinel is a real `int64_t` value, so `SP_INT_NIL + 1` is just
215-`INT64_MIN + 1` — surprising but not a crash). Documented in
216-existing int? work (commit f6c3b6d era).
217-
218-## Phase 2 Scope — REVERTED (2026-05-25, #708)
219-
220-Phase 2 attempted to change `sp_StrStrHash_get` / `sp_IntStrHash_get` /
221-`sp_SymStrHash_get` to return `NULL` on missing keys. Committed as
222-0ec6b1d, then **reverted via 532ba3e** after #708 surfaced a
223-real-world breakage:
224-
225-- Tep apps segfault at boot.
226-- `lib/tep.rb`'s seeding chain (175-730) reads from hash slots
227- in patterns that the Phase 2 commit's "safe call paths" audit
228- missed -- the audit covered string-method dispatch
229- (`sp_str_length` / `sp_str_eq` / `sp_str_concat` are NULL-safe)
230- but didn't enumerate every downstream `const char *` use site
231- in user code or framework runtime.
232-- Restoring `sp_str_empty` semantics is the conservative call
233- until a wider audit + codemod recipe is ready.
234-
235-### Re-planned Phase 2 (deferred)
236-
237-The Ruby semantic violation is real (`if h[:missing]` evaluates as
238-truthy under the `""` fallback because `sp_str_empty` is a non-NULL
239-pointer). Bringing it inline with Ruby without breaking tep / real-
240-blog requires one of:
241-
242-1. **Opt-in via build flag** (`-DSP_STRHASH_MISS_NIL`). Apps that
243- audit their hash use can flip the flag; others stay on the
244- `""` fallback. Lowest-risk for downstream users.
245-2. **Lazy null-coalescing pass** in codegen: detect `h[k]` followed
246- by a method-call that requires non-NULL (`.length`, `.bytes`,
247- `.split`, ...) and insert a NULL → `sp_str_empty` coalesce.
248- The `if h[:k]` truthy site dispatches to a separate truthy
249- helper that treats `sp_str_empty` as falsy when the value came
250- from a hash miss (requires tagging the miss in the runtime).
251-3. **Surgical attack** on `compile_cond_expr` only: when the
252- condition is `h[k]` on a typed-string hash, emit
253- `sp_StrStrHash_has_key(h, k)` instead of the raw value-truthy
254- check. Doesn't change the runtime miss return at all; only
255- fixes the truthy check. Tep / real-blog can keep their
256- `s = h[k]; s.length` etc. patterns working.
257-
258-Option 3 is the smallest and most targeted; consider for a future
259-Phase 2 attempt.
260-
261-Until that lands, `*StrHash[missing] == sp_str_empty` (current
262-spinel behavior) -- documented Ruby-semantic violation, stable
263-runtime.
264-
265-## Phase 4 Scope — DEFERRED (2026-05-25)
266-
267-Implementing `*IntHash` → SP_INT_NIL is significantly more invasive
268-than initially scoped. First attempt (16:00-16:40 JST) hit three
269-cascading issues, all reverted before commit:
270-
271-### Cascade 1: Self-host bootstrap breaks via inferred-LV typing
272-
273-Changing `analyze`'s `[]` return for `str_int_hash` from `"int"` to
274-`"int?"` propagates "int?" through spinel_analyze.rb's OWN type
275-inference. Specifically `unify_return_type` and `unify_call_types`
276-treat `"int?"` as a distinct type from `"int"`, widening many
277-internal calls (like `not_in(name, arr)`) to poly. Mitigations
278-attempted:
279-
280-- `unify_hash_value_types`: treat `int?` as `int` (added)
281-- `unify_return_type`: treat `int?` as `int` for fallback (added)
282-
283-These alone aren't enough — `unify_call_types`'s
284-`base_type(old_pt) == base_type(at)` check at line 11568 still
285-diverges for `("string", "int?")` pairs, which then fall through
286-to the trailing "incompatible → poly" branch. The bootstrap fails
287-with `lv_kt = sp_box_nil()` typing (poly) on locals that should
288-be `const char *` (the result of `infer_type(...)`).
289-
290-### Cascade 2: `&&=` / `||=` codegen treats `SP_INT_NIL` as truthy
291-
292-The compound-assignment codegen lowers `counts[k] &&= v` to:
293-
294-```c
295-if (sp_StrIntHash_get(counts, k)) {
296- sp_StrIntHash_set(counts, k, v);
297-}
298-```
299-
300-The `if (...)` is C-truthy on the raw mrb_int. After Phase 4,
301-missing-key returns `SP_INT_NIL = INT64_MIN`, which is **non-zero**
302-and therefore C-truthy. Ruby says nil is falsy. The fix requires
303-the codegen to emit `if (!sp_int_is_nil(...))` for typed-int-hash
304-sources — a parallel arm in `compile_index_and_assign` /
305-`compile_index_or_assign`.
306-
307-### Cascade 3: Existing test assumptions
308-
309-`test/sym_int_hash_merge.rb` line 10 expects `puts h3[:q]` after
310-`h3.delete(:q)` to output `0`. Updating to empty line (Ruby's
311-`puts nil`) requires the int? puts arm AND propagation through
312-the analyze type so the call site dispatches to it. Without all
313-cascades fixed, the test produces the raw `-9223372036854775808`
314-output.
315-
316-### Re-planned Phase 4 (alternative: poly wrapper)
317-
318-The cleaner approach, mirroring `Array#index` (commit e46ec54):
319-
320-1. Add `sp_StrIntHash_get_poly(h, k)` runtime helper that returns
321- `sp_RbVal` (sp_box_nil() for missing, sp_box_int(v) for present).
322-2. Same for `sp_SymIntHash_get_poly`.
323-3. Codegen `h[k]` direct dispatch for `str_int_hash` / `sym_int_hash`
324- routes to `_get_poly` (returns sp_RbVal).
325-4. Analyze `[]` returns `"poly"` for these variants.
326-5. Compound writes (`&&=`/`||=`) read via `_get_poly`, write via
327- `_set` after unboxing.
328-
329-The poly route reuses existing infrastructure (sp_poly_truthy,
330-sp_poly_inspect, etc.) and avoids the int? cascade. Cost: boxing
331-on every `[]` lookup. For frameworks heavy in typed-int hash use,
332-profile before committing.
333-
334-### Status
335-
336-Phase 4 deferred until either:
337-- A focused session implements the poly-wrapper route end-to-end, or
338-- The int? cascade is fixed at all sites (3+ places in
339- spinel_analyze.rb plus the compound-assignment codegen)
340-
341-Until then, `*IntHash[missing]` returns the value-type zero (`0`)
342-— a known Ruby semantic violation, but stable.
343-
344-## Phase 5 Scope
345-
346-- Add regression tests:
347- - `test/str_str_hash_missing_returns_nil.rb` — `if h["missing"]; ...; end` falsy path
348- - `test/str_int_hash_missing_returns_nil.rb` — `if h["missing"]; ...; end` falsy
349- - `test/sym_int_hash_missing_arithmetic.rb` — document SP_INT_NIL arith caveat
350-- `make test` (all pass)
351-- `make bootstrap` (gen2 == gen3)
352-- `make optcarrot` (checksum 59662)
353-
354-## Risks
355-
356-1. **Bootstrap self-host**: spinel_analyze.rb + spinel_codegen.rb
357- use typed hashes extensively. Per-phase bootstrap convergence
358- required.
359-2. **optcarrot regression**: prior body-driven-widening cascade
360- (memory: body_usage_widening_optcarrot) warns that even
361- post-fixpoint widening can cascade-break optcarrot. Phase 4's
362- `int?` widening is the highest-risk step.
363-3. **Test-suite assumptions**: any existing test that asserts
364- `h[missing] == ""` or `h[missing] == 0` semantics needs update.
365- Survey via `grep -rE 'Hash.*\[".*"\].*== "?"' test/`.
366-
367-## Order of Operations
368-
369-```
370-Phase 1 — survey + this doc [current]
371-Phase 2 — *StrHash → NULL next
372-Phase 3 — *StrHash codegen tightening
373-Phase 4 — *IntHash → SP_INT_NIL bigger surgery
374-Phase 5 — regression tests + final verify
375-```
376-
377-Each phase ends with a green CI before the next begins. If Phase 4
378-regresses optcarrot, fall back to Phase 4a (per-variant rollout
379-with feature flag).