Commit 621627db

621627dbb4d5Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 7 files · +3 added · ~4 modified

Description

feat(runtime): adopt frozen_string_literal: true semantics for setbyte

Spinel keeps string literals in rodata and dedups them across the program — they are physically immutable. The setbyte path previously masked this with a silent no-op (commit bbfc3b3), which broke Ruby semantics: a mutation that visibly didn't happen is worse than a clear error.

Adopt # frozen_string_literal: true semantics globally instead: setbyte on a literal (or any non-whitelisted buffer) raises FrozenError. Heap-allocated buffers (sp_str_alloc 0xfe/0xfc, sp_String 0xfd) still mutate.

Per spinel-as-Ruby-subset design: explicit FrozenError is the principled escalation when the user reaches for mutation on a frozen literal. The dup-then-mutate idiom (bm_ruby_xor, etc.) keeps working.

Aliasing semantics now match CRuby with the pragma enabled:

a = "ab"; a.setbyte(...) -> FrozenError (matches) a = "ab".dup; a.setbyte(...) -> mutate (matches) a = "ab".dup; b = a; a.setbyte -> shared heap, both see (matches)

The COW route considered in the planning notes had an unavoidable aliasing divergence (a = "ab"; b = a; ... shared the rodata pointer and only a's slot got COW'd). Frozen-literal semantics sidesteps that entirely: the mutation never happens, the user gets a clear error.

Follow-up (separate effort): apply the same frozen-on-literal gate to String#<<, #concat, #replace, the !-suffix mutators, and any other mutating methods that currently silent-fall through on literal recv.

  • lib/sp_runtime.h: sp_str_setbyte raises FrozenError on non-heap markers (0xff literal, unknown FFI, NULL).
  • test/str_method_nil_arg_no_segv: rescue the literal setbyte and pin the FrozenError message; add a parallel dup-mutate line so the "mutation works on heap" half is also pinned.
  • test/str_setbyte_frozen_literal: new regression covering literal-raise, lv-pointing-at-literal-raise, dup-mutate, concat-mutate, shared-heap-aliasing, ivar dispatch.
  • test/str_setbyte_dup_mutates: comment updated to reference the frozen-literal companion test.
  • docs/setbyte-semantic-plan.md: design rationale.

Default raise: 629 / 0 / 0 (one new regression test). Bench: 57 / 0 / 0 / 0 (bm_ruby_xor still PASS via dup). Optcarrot checksum 59662 unchanged.

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

Details

Commit
621627dbb4d5
Parent
93638f216ef6

docs/setbyte-semantic-plan.mdaddedView file

1+# String#setbyte semantic-preserving plan (改訂版: frozen literal 採用)
2+
3+## 方針
4+
5+**spinel は `# frozen_string_literal: true` がグローバルに有効な Ruby として振る舞う。**
6+
7+- string literal は frozen (rodata に置く既存設計と整合)
8+- 変更操作 (setbyte, <<, concat, replace, !-suffix mutators, …) を frozen literal に対して行うと `FrozenError` を raise
9+- mutable string が必要なら `.dup` で heap allocate
10+
11+## 何故これが正しいか
12+
13+1. **spinel の既存設計と一致**: literal は既に rodata に dedup されている。 frozen として扱うのが本質的に正しい
14+2. **Ruby の方向性**: 3.0+ で frozen-string-literal を推奨、 将来的にデフォルト化の議論あり
15+3. **subset の identity と一致**: spinel は Ruby のサブセット → サブセット内では一貫した強い保証を提供する設計
16+4. **silent failure を排除**: no-op は最悪。 raise なら user は問題を即座に発見し `.dup` で fix できる
17+5. **aliasing 曖昧さの解消**: COW にあった `a = "ab"; b = a; a.setbyte(...)` の divergence 問題が起きない (mutation 試行で必ず raise)
18+
19+## 現在の問題
20+
21+`commit bbfc3b3` (sp_str_setbyte) の挙動:
22+- heap (0xfe/0xfc/0xfd) → mutate ✓
23+- literal (0xff) → **silent no-op** ✗
24+- FFI / unknown → silent no-op ✗
25+
26+silent no-op は受け入れられない。 frozen literal semantics で raise に切り替える。
27+
28+## Phase 1: setbyte の frozen literal raise
29+
30+### Runtime 変更
31+
32+`lib/sp_runtime.h` の `sp_str_setbyte`:
33+
34+```c
35+static inline mrb_int sp_str_setbyte(const char *s, mrb_int i, mrb_int v) {
36+ if (!s) return v;
37+ unsigned char m = ((const unsigned char *)s)[-1];
38+ if (m == 0xfe || m == 0xfc || m == 0xfd) {
39+ ((char *)s)[i] = (char)v;
40+ return v;
41+ }
42+ /* literal (0xff) or FFI / unknown -> frozen, raise. spinel
43+ treats all string literals as frozen-string-literal: true. */
44+ sp_raise_cls("FrozenError", "can't modify frozen String");
45+ return v; /* unreachable; longjmp via sp_raise_cls */
46+}
47+```
48+
49+### Codegen 変更
50+
51+なし。 既存の `sp_str_setbyte(rc, idx, val)` emit がそのまま runtime check を経由する。
52+
53+### Test 更新
54+
55+`test/str_method_nil_arg_no_segv.rb` の setbyte 部分が FrozenError raise するように:
56+
57+```ruby
58+# 旧:
59+(str = "a")
60+str.setbyte(0, 98)
61+puts str # spinel: "a" (mutation dropped)
62+
63+# 新:
64+(str = "a")
65+begin
66+ str.setbyte(0, 98)
67+ puts "no raise: " + str
68+rescue FrozenError => e
69+ puts "frozen: " + e.message
70+end
71+```
72+
73+期待値 `"frozen: can't modify frozen String"`。
74+
75+### 新 regression test (`test/str_setbyte_frozen_literal.rb`)
76+
77+```ruby
78+# Spinel adopts `# frozen_string_literal: true` semantics globally:
79+# string literals are immutable; setbyte on a literal raises
80+# FrozenError. To mutate, use .dup or a fresh heap-allocated
81+# string from .+/.concat etc.
82+
83+# Literal: raises
84+begin
85+ s = "abc"
86+ s.setbyte(0, 67)
87+ puts "no raise"
88+rescue FrozenError => e
89+ puts "literal: " + e.message
90+end
91+
92+# Dup'd: mutates
93+s2 = "abc".dup
94+s2.setbyte(0, 67)
95+puts s2 # Cbc
96+
97+# String#+: mutates (returns fresh heap)
98+s3 = "x" + "y"
99+s3.setbyte(0, 90)
100+puts s3 # Zy
101+
102+# ivar on heap string: mutates
103+class C
104+ attr_reader :buf
105+ def initialize; @buf = "abc".dup; end
106+ def hit; @buf.setbyte(0, 67); end
107+end
108+c = C.new
109+c.hit
110+puts c.buf # Cbc
111+```
112+
113+期待値:
114+```
115+literal: can't modify frozen String
116+Cbc
117+Zy
118+Cbc
119+```
120+
121+## Phase 2: 他の mutator にも適用 (follow-up)
122+
123+Phase 1 が安定したら、 同じ frozen-check を以下にも適用:
124+
125+| Method | 現状 | 目標 |
126+|---|---|---|
127+| String#<< | (調査要) | literal recv で FrozenError |
128+| String#concat | (調査要) | 同上 |
129+| String#replace | (調査要) | 同上 |
130+| String#chomp! | (調査要) | 同上 |
131+| String#strip! | (調査要) | 同上 |
132+| String#squeeze! | (調査要) | 同上 |
133+| String#gsub!, sub! | (調査要) | 同上 |
134+| String#upcase!, downcase! 等 | (調査要) | 同上 |
135+
136+各 method の codegen で marker check を runtime emit するか、 共通 helper を経由させる。 Phase 2 は別 issue で個別に対応。
137+
138+## Phase 3: ユーザー視点の error message 改善
139+
140+`FrozenError` の message を spinel-aware に:
141+- `can't modify frozen String (literal "<content>")` のように literal 文字列の先頭 32 文字を含めると debug 容易
142+- ただし stack trace が無いので line 情報は出ない (既存の sp_raise_cls 仕様)
143+
144+Phase 3 はオプション。
145+
146+## Aliasing semantics — frozen literal 採用で完全互換
147+
148+| Pattern | spinel (frozen literal) | MRI (frozen literal pragma) | 一致? |
149+|---|---|---|---|
150+| `a = "ab"; a.setbyte(0, 67)` | FrozenError raise | FrozenError raise | ✅ |
151+| `a = "ab"; b = "ab"; a.setbyte(0, 67)` | FrozenError raise | FrozenError raise | ✅ |
152+| `a = "ab".dup; b = a; a.setbyte(0, 67)` | mutate, b="Cb" (shared) | mutate, b="Cb" (shared) | ✅ |
153+| `a = "ab".dup; a.setbyte(0, 67)` | mutate | mutate | ✅ |
154+
155+frozen literal pragma 有効な Ruby と完全一致。
156+
157+## bm_ruby_xor の挙動
158+
159+```ruby
160+def xor_strings(a, b)
161+ result = a.dup # heap (0xfe)
162+ result.setbyte(i, ...) # heap path で mutate
163+ result
164+end
165+```
166+
167+dup で heap 化されるので問題なし。 Phase 1 で PASS。
168+
169+## 影響範囲
170+
171+| File | 変更 | 行数 |
172+|---|---|---|
173+| lib/sp_runtime.h | `sp_str_setbyte` を frozen-raise 化 | ~5 |
174+| test/str_method_nil_arg_no_segv.rb | literal setbyte を rescue で wrap | ~8 |
175+| test/str_method_nil_arg_no_segv.rb.expected | "a" → "frozen: ..." | ~1 |
176+| test/str_setbyte_frozen_literal.rb | 新 regression test | ~25 |
177+| test/str_setbyte_frozen_literal.rb.expected | | ~4 |
178+| docs/SPINEL-SEMANTICS.md (任意) | frozen-literal-default の document | ~30 |
179+
180+## 検証
181+
182+- `make test`: 628/0/0 → 629/0/0 (新 regression test 追加、 既存 test の expected 更新)
183+- `make bench`: 57/0/0/0 維持 (bm_ruby_xor は dup → heap path)
184+- `make optcarrot`: checksum 59662 維持
185+
186+## Risks
187+
188+1. **既存 user code の breakage**: spinel で動いていた `s = "abc"; s.setbyte(...)` が raise に変わる
189+ - 緩和: error message が明確、 `.dup` で簡単に修正可能
190+ - spinel は Ruby subset、 frozen literal pragma に依存することは subset 内では妥当
191+2. **他の mutator が consistent でない**: Phase 1 では setbyte のみ。 String#<< 等は別挙動のまま
192+ - 緩和: Phase 2 で順次対応、 個別 issue で track
193+3. **FFI / unknown marker への扱い**: 現在は literal 同様 raise (defensive)
194+ - FFI で返った文字列は通常 spinel-side で `sp_str_dup_external` 経由して heap 化されているので実害は少ない
195+
196+## 実装順
197+
198+1. `sp_str_setbyte` を frozen-raise 化
199+2. `test/str_method_nil_arg_no_segv` 更新
200+3. 新 regression test `str_setbyte_frozen_literal` 追加
201+4. `make test` / `make bench` / `make optcarrot` 全通し
202+5. commit + push
203+6. Phase 2 (他の mutator) を別 issue として open