Commit 4a8ca9de

4a8ca9dea493Merged

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

Description

docs: stage 2 design — poly-as-set type representation

Save the design notes for the deferred stage 2 of body-side type inference (the "poly type carries a set of candidate classes" extension). Stage 1 (commit 0d10645, narrow_param_types_from_body_method_calls) handles the single-class case; stage 2 generalizes to set intersection across observations and unlocks else-arm negative narrowing.

Documented for future reference. Implementation deferred until a concrete bug case justifies the 1-2 week refactor cost — current known-issue list is dominated by caller-side widening misses, not type-precision misses, so stage 2's expected ROI is uncertain. The doc enumerates impacted functions, encoding choice (poly{A;B} semicolon-separated, mirroring module_acc_resolved's existing convention), staged migration plan (2a no-op representation extension → 2b intersection → 2c type-minus → 2d emit-side enumeration), and the trigger conditions for actually picking it up.

Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]

Details

Commit
4a8ca9dea493
Parent
59f48e594a9d

POLY-AS-SET.mdaddedView file

1+# Stage 2 設計案: poly-as-set 型表現
2+
3+Stage 1 (`narrow_param_types_from_body_method_calls`、commit `0d10645`) の制約「呼ばれる全メソッドが**ただ1つ**のクラスにしかない」を外すための、内部型表現の拡張案。記録目的。実装は未着手。
4+
5+## 動機
6+
7+現状の "poly" は不透明な単一トークン。次の精度向上が手に入っていない:
8+
9+1. **set-intersection narrowing** — 候補集合を観測ごとに intersect して絞る
10+ ```ruby
11+ def render(model)
12+ model.title # Article のみ → {Article}
13+ model.body # Article + Comment → {Article, Comment}
14+ # 交差 = {Article} → narrow できるはず
15+ end
16+ ```
17+ Stage 1 では `model.body` の信号がぼやけて捨てられる。
18+
19+2. **else-arm 負の絞り込み** — `if x.is_a?(A); ... ; else; # x:NOT(A) ; end`
20+ 現在 scan_new_calls の comment にも明示:
21+ > The else-arm walks unchanged (we don't currently model "type minus C")
22+
23+3. **emit サイズ削減** — `compile_poly_method_call` の per-class arm が `@cls_names` を全列挙。候補集合に絞れば未到達 arm を消せる。
24+
25+## 内部表現
26+
27+### 文字列エンコード案
28+
29+`"poly"` → `"poly{<sorted-class-name-list>}"` (集合を文字列でエンコード):
30+
31+```
32+"poly" → 既存の "全クラス" 意味、互換維持のため keep
33+"poly{Article}" → 単一クラス、`obj_Article` と等価扱いで折り畳み可能
34+"poly{Article;Comment}" → 二項
35+"poly{Article;Comment;HWIA}" → 三項
36+"poly{Article;Comment;HWIA}?" → nullable版 (既存の `?` サフィックス慣習継承)
37+```
38+
39+セパレータは `;` (既存の `@cls_meth_params` のクラス区切り `|` や param 区切り `,` と衝突しない、`@cls_meth_names` の method 区切りと一致)。
40+
41+### 正規化ルール
42+
43+- ソートして決定的なエンコードに (`{B;A}` ではなく `{A;B}`)
44+- 重複除去
45+- サイズ 1 → `obj_<C>` に折り畳み (representation lift; 集合表現を消す)
46+- 全クラスを含む → `"poly"` に折り畳み (degenerate case)
47+
48+### 影響を受ける関数 (主要)
49+
50+| 関数 | 既存ロジック | 必要な拡張 |
51+|------|-------------|------------|
52+| `base_type` | `"obj_C?"` → `"obj_C"` | `"poly{A;B}?"` → `"poly{A;B}"` |
53+| `is_obj_type` | `"obj_"` プレフィックス判定 | (poly-set は obj_ ではない、独立) |
54+| `is_value_type_obj` | obj_C の class lookup | poly-set は value-type 不可 (各候補は struct 化 NG) |
55+| `c_type` | `"poly"` → `"sp_RbVal"` | `"poly{...}"` も同じく `"sp_RbVal"` |
56+| `c_default_val` | `"poly"` → `"sp_box_nil()"` | 同 |
57+| `unify_call_types` | 二項 unify | set union (詳細下記) |
58+| `box_value_to_poly` | obj_C / 各種 → sp_box_* | set 経由は対象外、各 candidate ごとに caller 側で box済を期待 |
59+
60+### unify_call_types の拡張
61+
62+```
63+unify("poly{A;B}", "obj_A") = "poly{A;B}" (subset → 包含)
64+unify("poly{A;B}", "obj_C") = "poly{A;B;C}" (union)
65+unify("poly{A;B}", "poly{B;C}") = "poly{A;B;C}" (union)
66+unify("poly{A;B}", "poly{A;B}") = "poly{A;B}" (idempotent)
67+unify("poly{A;B}", "int") = "poly" (混合型は既存 poly に degrade)
68+unify("obj_A", "obj_B") = "poly{A;B}" (新ロジック; 現状は "poly")
69+unify("poly", any) = "poly" (degenerate keep)
70+```
71+
72+ポイント: **混合型 (obj+primitive) は既存の不透明 `"poly"` に落とす**。これにより既存コードの `"poly"` 判定 (受け取り側のすべての場所) と互換が取れる。`"poly{...}"` は **すべて user obj** な集合に限定。
73+
74+### intersection 演算 (Stage 1 を一般化)
75+
76+```
77+intersect("poly{A;B;C}", "poly{B;C;D}") = "poly{B;C}"
78+intersect("poly{A;B}", "poly{C;D}") = "" (空 → 信号矛盾)
79+intersect("poly{A}", "obj_A") = "obj_A"
80+intersect("poly{A;B}", "obj_C") = "" (空)
81+```
82+
83+Stage 1 の `unify_param_class_from_observations` を集合演算で書き直す:
84+- 各観測 `param.<m>` で「`<m>` を定義する user class 集合 S(m)」を計算
85+- 各観測の S(m) で intersection を取る
86+- `is_primitive_shared_method(m)` は S に「全クラス + builtins」を意味するので intersection 中立 (skip)
87+- 最終 intersection が空でなければ narrow
88+
89+### type minus 演算 (else-arm)
90+
91+```
92+type_minus("poly{A;B;C}", "obj_A") = "poly{B;C}"
93+type_minus("poly{A;B}", "obj_A") = "obj_B" (size 1 折り畳み)
94+type_minus("poly{A}", "obj_A") = "" (空; unreachable)
95+type_minus("poly", "obj_A") = "poly" (不透明は触らない)
96+```
97+
98+scan_new_calls の IfNode 処理に else-arm narrow を追加:
99+```ruby
100+# then-arm
101+if narrow_var != ""
102+ push_type_narrow(narrow_var, narrow_t) # 既存
103+end
104+walk(then_body)
105+pop
106+
107+# else-arm (新規)
108+else_narrow_t = type_minus(原型, narrow_t)
109+if else_narrow_t != ""
110+ push_type_narrow(narrow_var, else_narrow_t)
111+end
112+walk(else_body)
113+pop
114+```
115+
116+## emit-side 変更
117+
118+### compile_poly_method_call
119+
120+```ruby
121+# 現状:
122+i = 0
123+while i < @cls_names.length
124+ midx = cls_find_method_direct(i, mname)
125+ if midx >= 0
126+ # arm 出力
127+ end
128+ i += 1
129+end
130+
131+# Stage 2:
132+candidates = poly_candidates(recv_type) # "poly{A;B}" → ["A", "B"]
133+# 候補が空 (= 不透明 "poly") なら現状通り全列挙
134+# 候補があれば限定列挙
135+candidates.each { |cn|
136+ ci = find_class_idx(cn)
137+ midx = cls_find_method_direct(ci, mname)
138+ if midx >= 0
139+ # arm 出力
140+ end
141+}
142+```
143+
144+emit 量削減: Roundhouse 規模 (~20 user class、平均候補3クラス) で arm 17 個 ÷ poly call sites 50-100 個 ≈ 1000-2000 行の C 削減 (runtime 動作に影響なし、cc 時間 + emit サイズのみ)。
145+
146+### sp_RbVal タグの動作変化なし
147+
148+ランタイムの sp_RbVal/cls_id 機構は変更不要。集合は **静的判定** だけの情報。runtime は cls_id で正しく分岐。
149+
150+## 不動点の収束
151+
152+Stage 2 では union (拡大) と intersection (縮小) の両方を扱う:
153+
154+- caller→callee widening (scan_new_calls): union で拡大
155+- callee→caller (戻り値伝播): union で拡大
156+- body-side narrow (Stage 1 拡張): intersection で縮小
157+
158+各 round 内の順序を:
159+1. union 系 (call-site 観測) を全部走らせて param ptype を膨らませる
160+2. その後で intersection 系 (body 観測) を走らせて絞る
161+
162+→ "拡大→縮小" の順序が各 round で一定なら、実質単調に近づく。`inference_signature` で前回と等しくなったら stop。最大 round 数を上げる必要があるかもしれない (現状 4 → 6〜8 程度に)。
163+
164+## 互換性 / 移行ステップ
165+
166+Stage 2 を 1 PR で全部入れるのは bootstrap risk が高い。段階移行:
167+
168+### 2a. 表現拡張 (no-op)
169+- `"poly{A;B}"` 文字列を内部で生成する経路を入れるが、すべて `"poly"` に折り畳んで返す
170+- `unify_call_types` などはまだ既存挙動
171+- すべての判定箇所が新表現を view できることを bootstrap で確認
172+
173+### 2b. set-intersection narrow
174+- Stage 1 の単一クラス制約を外す
175+- `unify_param_class_from_observations` を set intersection で書き直す
176+- 既存の `"poly"` への混合型 degrade はそのまま
177+
178+### 2c. else-arm 負の絞り込み
179+- IfNode の else-arm に type_minus 適用
180+- recursive scan のスコープ管理を慎重に (then と else で違う narrow)
181+
182+### 2d. emit-side 列挙の限定
183+- `compile_poly_method_call` で候補集合があればそれを使う
184+- emit 出力差を 1 PR で分離 (review しやすさのため)
185+
186+## リスクと観察ポイント
187+
188+1. **bootstrap stability**: 型文字列処理の 1 箇所のミスで gen2 != gen3 → CI 全敗
189+ - 各サブステップ後 `make bootstrap` 必須
190+ - 表現変更前に既存 split/join ロジックの全数 grep し、新セパレータ衝突の有無を確認
191+
192+2. **テスト盲点**:
193+ - 集合サイズ 0 (空 = unreachable) のハンドリング
194+ - サイズ 1 → obj_<C> 折り畳みの一貫性
195+ - 全クラス集合と "poly" の等価扱い
196+
197+3. **ROI 計測**:
198+ - Stage 2a 完了時点で既存テスト + Roundhouse archive で no-op 確認
199+ - Stage 2b 後、stage 1 で narrow できなかった param が集合 narrow できる事例を 1 つ以上見つける (見つからないなら投資中止判断材料)
200+ - Stage 2c, 2d は 2b の効果を見て継続判断
201+
202+## 着手判断条件
203+
204+Stage 2 に踏み込むべきタイミング:
205+
206+- `caller-side widening が届かない経路` 起源でない、**型精度**起源のバグが具体例で現れた時
207+- Roundhouse 移行が runtime 段階に入って "static dispatch ミス" が顕在化した時
208+- emit サイズ・cc 時間のボトルネックが計測で示された時 (現状は CI 11分問題は sccache miss 由来で、emit サイズではない)
209+
210+それまでは Stage 1 で観察を継続。
211+
212+---
213+
214+参考:
215+- Stage 1: `narrow_param_types_from_body_method_calls` (`0d10645`)
216+- 関連コメント: `spinel_codegen.rb` の `scan_new_calls` IfNode 処理 ("we don't currently model 'type minus C'")
217+- 既存集合的ロジックの先例: `module_acc_resolved` のセミコロン区切りクラス候補リスト (#126)