Commit 55e53fd1

55e53fd1ff7bMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · +1 added

Description

docs: plan for #646 (const self-ref runtime NameError)

Phase 1 covers the direct shape (<C>#initialize reads <X> where <X> = <C>.new) via a per-const sp_init_in_progress_<X> flag set/cleared around the const assignment, with the read site checking the flag and routing through sp_raise_cls("NameError", ...) when set.

Phase 1.5 extends to inheritance walks and attr_writer setter paths. Phase 2 (optional) uses a call-graph pass to skip the in-progress check at reads provably outside the init chain.

Transitive shape (APP = build_app() where build_app calls App. new internally) is documented as inherently harder — needs cross-method flow analysis to track which init chains end up running App.new.

Refs #646.

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

Details

Commit
55e53fd1ff7b
Parent
2cfa705c16c1

docs/issue-646-plan.mdaddedView file

1+# Issue #646 修正計画
2+
3+## 現象
4+
5+```ruby
6+class App
7+ def initialize
8+ APP.something # APP is being initialized RIGHT NOW
9+ end
10+end
11+APP = App.new
12+```
13+
14+MRI: `NameError: uninitialized constant App::APP` を init 中に raise。
15+spinel: `cst_APP` は `NULL`。read は NULL を返し、`.something` で segfault。
16+
17+reporter の実例 (tep#13) は transitive ケース:
18+```
19+APP = App.new
20+ → App#initialize
21+ → PG::Connection.new(...)
22+ → ... → Tep::Scheduler.scheduled_context?
23+ → Tep::APP.sched_current # APP is still NULL
24+```
25+
26+dispatch が compile-time に static resolve した結果、`cst_Tep_APP->iv_sched_current` が直接 emit され、NULL deref で SEGV。
27+
28+## 現在の対応 (765b984)
29+
30+直接 shape (`Class#initialize` が `CONST` を直接 read、ただし `CONST = Class.new` 形式) を compile-time に detect して clearer warning を emit。Runtime crash の plug は無し。
31+
32+## ゴール
33+
34+issue の expected behaviour:
35+1. **Best**: MRI 互換の `NameError` raise (option 1)
36+2. **Acceptable**: `nil` を返して method dispatch で NoMethodError (option 2)
37+3. **現状 / Worst**: silent partial-init pointer / SEGV (option 3)
38+
39+option 1 を目指す。
40+
41+## 修正案: per-const in-progress flag + read-side guard
42+
43+### Phase 1: 直接 shape (`<C>` init reads `<X>` where `<X> = <C>.new`)
44+
45+#### Analyzer 側 (spinel_analyze.rb)
46+
47+新しい table `@const_init_class`:
48+- 要素: `@const_expr_ids[i]` が `<Class>.new(...)` shape なら `<Class>` の名前。そうでなければ `""`。
49+- IR export: `SA @const_init_class N value;value;...`
50+
51+```ruby
52+def detect_const_init_classes
53+ @const_init_class = "".split(",")
54+ i = 0
55+ while i < @const_expr_ids.length
56+ init_cls = ""
57+ eid = @const_expr_ids[i]
58+ if eid >= 0 && @nd_type[eid] == "CallNode" && @nd_name[eid] == "new"
59+ recv = @nd_receiver[eid]
60+ if recv >= 0 && @nd_type[recv] == "ConstantReadNode"
61+ init_cls = @nd_name[recv]
62+ end
63+ end
64+ @const_init_class.push(init_cls)
65+ i = i + 1
66+ end
67+end
68+```
69+
70+`generate_code` 内の早めのタイミング (precompute_all_scope_decls 後) で 1 回呼び出し。
71+
72+#### Runtime 側 (lib/sp_runtime.h)
73+
74+`sp_raise_cls("NameError", msg)` は既存。再利用する。新しいヘルパは不要。
75+
76+#### Codegen 側 (spinel_codegen.rb)
77+
78+1. **Per-const in-progress flag emit** (`emit_const_init` 周辺):
79+ - `@const_init_class[i]` が空でない const に対し、`static int sp_init_in_progress_<X> = 0;` を const 宣言と一緒に emit。
80+
81+2. **Const init assignment を guard で包む** (`emit_const_init` 内):
82+ ```c
83+ sp_init_in_progress_X = 1;
84+ cst_X = sp_C_new();
85+ sp_init_in_progress_X = 0;
86+ ```
87+
88+3. **Const read site で in-progress check** (`compile_expr` ConstantReadNode arm):
89+ - resolve した const X の `@const_init_class[ci]` が空でない場合のみ、wrap で emit:
90+ ```c
91+ ((sp_init_in_progress_X) ? (sp_raise_cls("NameError", "uninitialized constant X"), (sp_C *)NULL) : cst_X)
92+ ```
93+ - sp_raise_cls 後の cast は dead code だが C compile を通すために必要。
94+
95+### Phase 2 (任意 - 最適化)
96+
97+- 完全に static に "init 経路外" と判明する read site (e.g., main の APP = App.new の後 emit される statements) では in-progress check を skip。
98+- これにより hot path の overhead をゼロにできる (call graph 解析が必要)。
99+- Phase 1 だけでも MRI 互換 + 性能影響は branch 1 つ per const read のみ。許容範囲。
100+
101+## 影響範囲
102+
103+| ファイル | 変更内容 | 行数概算 |
104+|---|---|---|
105+| spinel_analyze.rb | `detect_const_init_classes` 追加 + `generate_code` 呼び出し + IR export | ~30 |
106+| spinel_codegen.rb | `@const_init_class` ロード + const decl で flag emit + assign を guard + read 側 wrap | ~50 |
107+| lib/sp_runtime.h | 変更不要 (sp_raise_cls 再利用) | 0 |
108+| test/ | 新規 regression test (NameError raise + rescue) | ~20 |
109+
110+## 検証
111+
112+```ruby
113+# test/const_self_ref_raises_name_error.rb
114+class App
115+ def initialize
116+ APP # ← raises NameError
117+ rescue NameError => e
118+ puts "caught: " + e.message
119+ end
120+end
121+APP = App.new
122+puts "after"
123+```
124+
125+Expected:
126+```
127+caught: uninitialized constant APP
128+after
129+```
130+
131+## エッジケース
132+
133+1. **Transitive (`APP = build_app()` where build_app does `App.new`)**: Phase 1 では Catch しない。`@const_init_class[APP]` は `""` (build_app は CallNode `new` でも recv が ConstantReadNode でもない)。Phase 2 でも難しい (call graph + dispatch resolve が必要)。Reporter の workaround で対応可能。
134+
135+2. **Class hierarchy: `APP = SubApp.new` で SubApp < App**: `@const_init_class[APP] = "SubApp"`。SubApp#initialize 内 + 継承された App#initialize 内の APP read は guard 対象。inheritance walk を `@const_init_class` のチェックに加える必要あり。Phase 1 では SubApp の直接 init のみ catch、parent init は miss する可能性 — phase 1.5 で追加するか。
136+
137+3. **Module const (`APP = App.new` inside `module Tep`)**: const 名は `Tep_APP`。`@const_init_class` は qualified 名で record。標準パスで動く。
138+
139+4. **`||=` re-init**: `APP ||= App.new` (rare)。`@nd_type[eid]` が ConstantOrWriteNode と違う。最初の `=` パスでのみ guard、`||=` は skip。妥当。
140+
141+5. **Setter on partially-init recv (`APP.foo = bar`)**: const recv が NULL の attr_writer dispatch。setter は usually `cst_APP->iv_foo = ...` を emit → NULL deref で SEGV。Guard の wrap がここでも必要。compile_call_expr の `[]=` / attr_writer setter dispatch でも cst_X recv detect が要る。
142+
143+## 段階的な実装
144+
145+Phase 1 で issue #646 のメインケース (直接 shape) を MRI 互換に raise する。
146+Phase 1.5 で inheritance walk と setter path を追加。
147+Phase 2 (任意) で call graph による guard 削減。
148+Transitive case (build_app 経由) は inherently 難しく、document する方が pragmatic。
149+
150+## 実装順序
151+
152+1. `detect_const_init_classes` 追加、IR export 動作確認
153+2. Codegen で `@const_init_class` をロード、in-progress flag を decl
154+3. Const assignment を guard で包む emit
155+4. Const read site の wrap
156+5. Regression test 追加
157+6. setter path 追加 (Phase 1.5)
158+7. inheritance walk (Phase 1.5)
159+8. push + close #646