Commit 957f9a75

957f9a759f45Merged

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

Description

docs: remove completed CLASS-OBJECT design memo

The Class-object feature it planned (obj.class, to_s/name/inspect, ==/!=, </> <=, superclass, ancestors/include?, dynamic is_a?, case/when Class, constant-as-value, Module/Class distinction, and the 0-byte-when-unused conditional emission) is implemented in the C backend and verified to match CRuby across the doc's full initial scope. The memo also describes the retired Ruby self-host backend (spinel_codegen.rb), so it no longer matches the codebase. The deferred items it lists (dynamic Klass.new, instance_methods, allocate, prepend, singleton_class) are tracked elsewhere, not by this plan.

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

Details

Commit
957f9a759f45
Parent
8b1d6cc1af09

docs/CLASS-OBJECT.mddeleted

1-# Class オブジェクト 設計メモ
2-
3-`obj.class` を Ruby 互換の Class 値として扱うための設計。Module も含めた
4-継承ツリー対応、機能未使用時は 1 byte も emit しない条件付き出力。
5-
6-## 動機
7-
8-現状の Spinel は `obj.class` を未対応とし、warning + 0 を吐いていた。
9-optcarrot は文字列補間 (`"#<#{ self.class }>"`) で `<0>` のような壊れた
10-出力になる。互換性のため、Class を本物の値型として実装する。
11-
12-## スコープ
13-
14-### サポート対象 (初期実装)
15-
16-- `obj.class` → Class 値 (組み込み型と user class 両方)
17-- `Klass.to_s` / `.name` / `.inspect` → 名前文字列 (`Optcarrot::NES` 形式)
18-- `Klass == Other` / `!=` → cls_id 比較
19-- `Klass < Other` / `<=` → subclass 比較
20-- `Klass.superclass` → 親 class
21-- `Klass.ancestors` → 含む module 込みの祖先 list
22-- `Klass.ancestors.include?(C)`
23-- `obj.is_a?(C)` で C が動的 (poly) のとき
24-- `case obj when Klass1, Klass2` (`Class#===`)
25-- ConstantReadNode (`Foo` を value として使う)
26-- Module も Class と同じ cls_id 空間に統合
27-
28-### 後回し
29-
30-- `Klass.instance_methods` / `.method_defined?`
31-- `Klass.new(*args)` (動的 instantiation)
32-- `Klass.allocate`
33-- `prepend` (現状は include のみ)
34-- Singleton class (`obj.singleton_class`)
35-
36-## 表現
37-
38-### C 側
39-
40-```c
41-typedef struct { mrb_int cls_id; } sp_Class;
42-```
43-
44-8 byte の値型、レジスタ渡し。`cls_id = -1` は sentinel ("class でない")。
45-Class と Module は同じ表現。区別は `sp_class_kinds[cls_id]`。
46-
47-新 poly tag `SP_TAG_CLASS` を追加 (ancestors を PolyArray に格納するため)。
48-
49-### Codegen 側
50-
51-新型タグ `"class"`:
52-
53-- `c_type("class") → "sp_Class"`
54-- 既定値: `((sp_Class){-1})`
55-- 値型 (`is_value_type` true)
56-
57-## Global class table
58-
59-統一した cls_id 空間に Class と Module が共存する。
60-
61-### Built-in registration (固定 index)
62-
63-| cls_id | name | kind | parent | includes |
64-|---|---|---|---|---|
65-| 0 | BasicObject | CLASS | -1 | [] |
66-| 1 | Object | CLASS | 0 | [Kernel] |
67-| 2 | Kernel | MODULE | -1 | [] |
68-| 3 | Comparable | MODULE | -1 | [] |
69-| 4 | Enumerable | MODULE | -1 | [] |
70-| 5 | NilClass | CLASS | 1 | [] |
71-| 6 | TrueClass | CLASS | 1 | [] |
72-| 7 | FalseClass | CLASS | 1 | [] |
73-| 8 | Numeric | CLASS | 1 | [Comparable] |
74-| 9 | Integer | CLASS | 8 | [] |
75-| 10 | Float | CLASS | 8 | [] |
76-| 11 | String | CLASS | 1 | [Comparable] |
77-| 12 | Symbol | CLASS | 1 | [Comparable] |
78-| 13 | Array | CLASS | 1 | [Enumerable] |
79-| 14 | Hash | CLASS | 1 | [Enumerable] |
80-| 15 | Range | CLASS | 1 | [Enumerable] |
81-| 16 | Time | CLASS | 1 | [Comparable] |
82-| 17 | Module | CLASS | 1 | [] |
83-| 18 | Class | CLASS | 17 | [] |
84-| 19 | Method | CLASS | 1 | [] |
85-| 20 | Complex | CLASS | 8 | [] |
86-| 21 | Proc | CLASS | 1 | [] |
87-
88-User-defined class / module はこの後ろに採番される。
89-
90-### `obj.class` の cls_id 解決
91-
92-| 静的型 | 返す cls_id |
93-|---|---|
94-| `obj_<C>` (user class) | builtin_count + ci of C |
95-| `obj_<M>` (user module instance) — そもそもインスタンスが作られない | n/a |
96-| `int` | 9 (Integer) |
97-| `float` | 10 (Float) |
98-| `string` / `mutable_str` | 11 (String) |
99-| `symbol` | 12 (Symbol) |
100-| `int_array`/`str_array`/`float_array`/`poly_array`/`ptr_array<…>` | 13 (Array) |
101-| `*_hash` 各種 | 14 (Hash) |
102-| `range` | 15 (Range) |
103-| `time` | 16 (Time) |
104-| `complex` | 20 (Complex) |
105-| `bool` (TrueClass / FalseClass) | 6 / 7 (literal の場合) |
106-| `nil` | 5 (NilClass) |
107-| `class` (sp_Class on sp_Class) | 17 or 18 (kind による) |
108-| `poly` | runtime 判定: `sp_class_for_poly(<rval>)` |
109-
110-## Precomputed ancestors
111-
112-ancestors の MRO 計算は **codegen 時** に Ruby 側で展開し、flat 配列に焼く。
113-runtime は単純 lookup のみ。
114-
115-### Codegen のアルゴリズム
116-
117-```ruby
118-def compute_ancestors(i, acc = [])
119- return acc if acc.include?(i)
120- if @kind[i] == :module
121- acc.push(i)
122- @includes[i].each { |j| compute_ancestors(j, acc) }
123- else
124- # class
125- acc.push(i)
126- @includes[i].reverse_each { |j| compute_ancestors(j, acc) }
127- if @parents[i] >= 0
128- compute_ancestors(@parents[i], acc)
129- end
130- end
131- acc
132-end
133-```
134-
135-include 順序 (逆順) と dedup を含めて、CRuby の MRO と同じ並びを生成する。
136-
137-### 出力テーブル
138-
139-```c
140-static const mrb_int sp_class_ancestors_off[N+1] = { 0, 1, 4, 5, ... };
141-static const mrb_int sp_class_ancestors_flat[] = {
142- /* 0 BasicObject */ 0,
143- /* 1 Object */ 1, 2, 0, /* Object, Kernel, BasicObject */
144- /* 2 Kernel */ 2,
145- /* 3 Comparable */ 3,
146- /* 4 Enumerable */ 4,
147- /* 5 NilClass */ 5, 1, 2, 0,
148- ...
149- /* 9 Integer */ 9, 8, 3, 1, 2, 0, /* Integer, Numeric, Comparable, Object, Kernel, BasicObject */
150- /* 13 Array */ 13, 4, 1, 2, 0, /* Array, Enumerable, Object, Kernel, BasicObject */
151- ...
152-};
153-```
154-
155-### Ruby 仕様との照合
156-
157-```
158-Array.ancestors => [Array, Enumerable, Object, Kernel, BasicObject]
159-Enumerable.ancestors => [Enumerable]
160-Comparable.ancestors => [Comparable]
161-Integer.ancestors => [Integer, Numeric, Comparable, Object, Kernel, BasicObject]
162-String.ancestors => [String, Comparable, Object, Kernel, BasicObject]
163-NilClass.ancestors => [NilClass, Object, Kernel, BasicObject]
164-Class.ancestors => [Class, Module, Object, Kernel, BasicObject]
165-```
166-
167-precomputed table はちょうどこの通り展開される。
168-
169-## Runtime helpers (lib/sp_runtime.h)
170-
171-```c
172-typedef struct { mrb_int cls_id; } sp_Class;
173-
174-#define SP_KIND_CLASS 1
175-#define SP_KIND_MODULE 2
176-
177-/* Built-in cls_id 定数 */
178-#define SP_CLASS_BASICOBJECT 0
179-#define SP_CLASS_OBJECT 1
180-#define SP_CLASS_KERNEL 2
181-#define SP_CLASS_COMPARABLE 3
182-#define SP_CLASS_ENUMERABLE 4
183-#define SP_CLASS_NIL 5
184-#define SP_CLASS_TRUE 6
185-#define SP_CLASS_FALSE 7
186-#define SP_CLASS_NUMERIC 8
187-#define SP_CLASS_INTEGER 9
188-#define SP_CLASS_FLOAT 10
189-#define SP_CLASS_STRING 11
190-#define SP_CLASS_SYMBOL 12
191-#define SP_CLASS_ARRAY 13
192-#define SP_CLASS_HASH 14
193-#define SP_CLASS_RANGE 15
194-#define SP_CLASS_TIME 16
195-#define SP_CLASS_MODULE 17
196-#define SP_CLASS_CLASS 18
197-#define SP_CLASS_METHOD 19
198-#define SP_CLASS_COMPLEX 20
199-#define SP_CLASS_PROC 21
200-
201-static inline const char *sp_class_to_s(sp_Class c) {
202- if (c.cls_id < 0 || c.cls_id >= SP_CLASS_COUNT) return "";
203- return sp_class_names[c.cls_id];
204-}
205-
206-static inline mrb_bool sp_class_eq(sp_Class a, sp_Class b) {
207- return a.cls_id == b.cls_id;
208-}
209-
210-/* sp_Class 値の `.class` を返す: kind に応じて Class または Module を返す */
211-static inline sp_Class sp_class_meta(sp_Class c) {
212- if (c.cls_id < 0 || c.cls_id >= SP_CLASS_COUNT) return (sp_Class){-1};
213- return (sp_Class){sp_class_kinds[c.cls_id] == SP_KIND_MODULE ? SP_CLASS_MODULE : SP_CLASS_CLASS};
214-}
215-
216-static inline sp_Class sp_class_superclass(sp_Class c) {
217- if (c.cls_id < 0 || c.cls_id >= SP_CLASS_COUNT) return (sp_Class){-1};
218- /* module には superclass が無い */
219- if (sp_class_kinds[c.cls_id] == SP_KIND_MODULE) return (sp_Class){-1};
220- return (sp_Class){sp_class_parents[c.cls_id]};
221-}
222-
223-/* `child <= ancestor` — ancestors に ancestor が含まれるか */
224-static inline mrb_bool sp_class_le(sp_Class child, sp_Class ancestor) {
225- if (child.cls_id < 0) return FALSE;
226- mrb_int s = sp_class_ancestors_off[child.cls_id];
227- mrb_int e = sp_class_ancestors_off[child.cls_id + 1];
228- for (mrb_int k = s; k < e; k++) {
229- if (sp_class_ancestors_flat[k] == ancestor.cls_id) return TRUE;
230- }
231- return FALSE;
232-}
233-
234-/* `child < ancestor` — proper subclass (== は false) */
235-static inline mrb_bool sp_class_lt(sp_Class child, sp_Class ancestor) {
236- if (child.cls_id == ancestor.cls_id) return FALSE;
237- return sp_class_le(child, ancestor);
238-}
239-
240-static sp_PolyArray *sp_class_ancestors_arr(sp_Class c) {
241- sp_PolyArray *r = sp_PolyArray_new();
242- if (c.cls_id < 0) return r;
243- mrb_int s = sp_class_ancestors_off[c.cls_id];
244- mrb_int e = sp_class_ancestors_off[c.cls_id + 1];
245- for (mrb_int k = s; k < e; k++) {
246- sp_PolyArray_push(r, sp_box_class((sp_Class){sp_class_ancestors_flat[k]}));
247- }
248- return r;
249-}
250-
251-/* `Klass === obj` — obj.class が Klass の subclass-or-equal か */
252-static inline mrb_bool sp_class_case_match(sp_Class klass, sp_Class obj_class) {
253- return sp_class_le(obj_class, klass);
254-}
255-
256-/* poly 値の cls_id を取って sp_Class を返す runtime 関数 */
257-static sp_Class sp_class_for_poly(sp_RbVal v) {
258- switch (v.tag) {
259- case SP_TAG_NIL: return (sp_Class){SP_CLASS_NIL};
260- case SP_TAG_BOOL: return (sp_Class){v.v.b ? SP_CLASS_TRUE : SP_CLASS_FALSE};
261- case SP_TAG_INT: return (sp_Class){SP_CLASS_INTEGER};
262- case SP_TAG_FLT: return (sp_Class){SP_CLASS_FLOAT};
263- case SP_TAG_STR: return (sp_Class){SP_CLASS_STRING};
264- case SP_TAG_SYM: return (sp_Class){SP_CLASS_SYMBOL};
265- case SP_TAG_CLASS: /* Class/Module 自身 — kind を見る */
266- return sp_class_meta((sp_Class){v.v.i});
267- case SP_TAG_OBJ:
268- /* user class instance: cls_id (poly) を builtin offset 込みで返す */
269- return (sp_Class){v.cls_id};
270- default:
271- return (sp_Class){-1};
272- }
273-}
274-```
275-
276-## 条件付き emission
277-
278-無関係な program で 1 byte も emit しないように、`@needs_*` フラグで制御する。
279-
280-| フラグ | 立つ条件 | emit する table |
281-|---|---|---|
282-| `@needs_class_table` | `obj.class` / class 値の登場 / `.to_s` / `.name` / ConstantReadNode を value で利用 | `sp_class_names`, `sp_class_kinds` |
283-| `@needs_class_parents` | `.superclass` | `sp_class_parents` |
284-| `@needs_class_ancestors` | `.ancestors` / 動的 `is_a?` / `case-when` Class / `<` / `<=` | `sp_class_ancestors_off`, `sp_class_ancestors_flat` |
285-
286-`scan_features` (既存) を拡張して上記を AST walk で検出する。
287-
288-### Reachability-based subset emission
289-
290-更に細かく: 「user code から到達可能な class/module」だけを emit する
291-(`Object`, `BasicObject`, `Kernel` は parent として transitively 必要)。
292-
293-実装は scan phase で reachable set を求め、emit 時にそのインデックスだけを
294-出力する。cls_id は連続な numbering である必要があるので、
295-re-numbering テーブルを持つ。
296-
297-ただし初期実装ではフルテーブル emit で OK
298-(builtin 22 + user ~30 = 52 entry × 平均 6 ancestors ≒ 2.5KB)。
299-最適化は後回し。
300-
301-## Codegen 変更点
302-
303-### 1. Class index 管理
304-
305-```ruby
306-# 初期化時に builtin を登録
307-@builtin_class_names = ["BasicObject", "Object", "Kernel", ..., "Proc"]
308-@builtin_class_kinds = [:class, :class, :module, ..., :class]
309-@builtin_class_parents = [-1, 0, -1, ..., 1]
310-@builtin_class_includes = [[], [2], [], ..., []]
311-@builtin_class_count = @builtin_class_names.length
312-
313-# user class の cls_id は @builtin_class_count + ci
314-def cls_id_for_user_ci(ci)
315- @builtin_class_count + ci
316-end
317-
318-# 静的型から cls_id を解決
319-def cls_id_for_static_type(t)
320- case t
321- when "int" then SP_CLASS_INTEGER
322- when "float" then SP_CLASS_FLOAT
323- when "string", "mutable_str" then SP_CLASS_STRING
324- when "symbol" then SP_CLASS_SYMBOL
325- ...
326- when /^obj_(.+)$/ then cls_id_for_user_ci(find_class_idx($1))
327- ...
328- end
329-end
330-```
331-
332-### 2. `@cls_human_names`
333-
334-class collection 時に `Optcarrot::NES` 形式 (`::` 区切り) を別途記録する。
335-
336-```ruby
337-def collect_class_with_prefix(nid, module_prefix)
338- ...
339- cname = ... # "Optcarrot_NES"
340- human = (module_prefix == "" ? local : human_join(module_prefix, local))
341- @cls_names.push(cname)
342- @cls_human_names.push(human)
343- ...
344-end
345-
346-def human_join(prefix, local)
347- # prefix は "Optcarrot" 形式 (まだ underscore されていない場合)、
348- # または "Optcarrot_Inner" 形式 (nest している場合) を想定。
349- prefix.split("_").join("::") + "::" + local
350-end
351-```
352-
353-### 3. `obj.class` の lowering
354-
355-```ruby
356-# compile_object_method_expr 内
357-if mname == "class"
358- cid = cls_id_for_static_type(recv_type)
359- if cid >= 0
360- @needs_class_table = 1
361- return "((sp_Class){#{cid}})"
362- end
363- if recv_type == "poly"
364- @needs_class_table = 1
365- return "sp_class_for_poly(#{rc})"
366- end
367-end
368-```
369-
370-`infer_call_type` で `<recv>.class → "class"`。
371-
372-### 4. `class` 受信のメソッド
373-
374-```ruby
375-# compile_object_method_expr 内、recv_type == "class"
376-case mname
377-when "to_s", "name", "inspect"
378- @needs_class_table = 1
379- "sp_class_to_s(#{rc})"
380-when "==", "eql?"
381- "sp_class_eq(#{rc}, #{compile_arg0(nid)})"
382-when "!="
383- "(!sp_class_eq(#{rc}, #{compile_arg0(nid)}))"
384-when "superclass"
385- @needs_class_table = 1
386- @needs_class_parents = 1
387- "sp_class_superclass(#{rc})"
388-when "ancestors"
389- @needs_class_table = 1
390- @needs_class_ancestors = 1
391- "sp_class_ancestors_arr(#{rc})"
392-when "<"
393- @needs_class_ancestors = 1
394- "sp_class_lt(#{rc}, #{compile_arg0(nid)})"
395-when "<="
396- @needs_class_ancestors = 1
397- "sp_class_le(#{rc}, #{compile_arg0(nid)})"
398-when "class"
399- @needs_class_table = 1
400- "sp_class_meta(#{rc})"
401-end
402-```
403-
404-### 5. ConstantReadNode (Class/Module 名) を value で使う
405-
406-`compile_expr` で ConstantReadNode を扱う path を拡張:
407-
408-```ruby
409-# 既存: receiver context (Foo.new など) は別 path で処理されるので、
410-# ここに来るのは「value 用法」のみ
411-if @nd_type[nid] == "ConstantReadNode"
412- name = @nd_name[nid]
413- cid = lookup_class_id_for_const_name(name)
414- if cid >= 0
415- @needs_class_table = 1
416- return "((sp_Class){#{cid}})"
417- end
418- ...
419-end
420-```
421-
422-`infer_type` も同様に: ConstantReadNode が class/module 名 → "class" 型。
423-
424-### 6. `is_a?` の拡張
425-
426-既存の static cls_id check はそのまま。動的 (poly) recv に対しては:
427-
428-```ruby
429-if mname == "is_a?" && recv_type == "poly"
430- @needs_class_ancestors = 1
431- "sp_class_le(sp_class_for_poly(#{rc}), #{compile_arg0(nid)})"
432-end
433-```
434-
435-ここで arg0 が ConstantReadNode (例: `Foo`) なら、上記の Class const-as-value
436-ルールで `((sp_Class){cid})` に lower される。
437-
438-### 7. `case obj when Klass1, Klass2`
439-
440-既存の case-when は WhenNode の condition を `===` で評価する。Spinel の現状
441-実装は obj_<C> に対して cls_id 比較を直接出していると思われる
442-(要確認)。Class const と sp_Class 値を `===` で比較する path に対応。
443-
444-```ruby
445-# WhenNode condition compile
446-when_cond_type = infer_type(cond)
447-if when_cond_type == "class"
448- # sp_class_case_match で評価
449- @needs_class_ancestors = 1
450- emit_when "sp_class_case_match(#{compile_expr(cond)}, sp_class_for_poly(#{subject}))"
451-end
452-```
453-
454-## Phase 計画
455-
456-### Phase 1 — sp_Class コア + Class entries
457-1 commit。Module は暫定で全部 CLASS として登録 (`is_a?(Module)` は次 phase)。
458-
459-- `sp_Class` struct + `SP_TAG_CLASS` poly tag
460-- `@builtin_class_*` 配列を Compiler init で登録
461-- `@cls_human_names` tracking
462-- `sp_class_names` 配列 emission (条件付き)
463-- `obj.class` の static lowering
464-- `class.to_s` / `.name` / `.inspect` / `==` / `!=` / `class` (meta)
465-- `@needs_class_table` フラグ
466-- test/builtin_class_basic.rb
467-
468-### Phase 2 — Constant as value + Module 区別
469-1 commit。
470-
471-- `kind` フィールド追加 (CLASS / MODULE)
472-- Module を MODULE として登録
473-- `sp_class_kinds` 配列 emission
474-- ConstantReadNode (class/module 名) → `((sp_Class){cid})` lowering
475-- `Klass.class == Class`, `Mod.class == Module` 動作確認
476-- test/class_constant_as_value.rb
477-
478-### Phase 3 — Precomputed ancestors + subclass / superclass
479-1 commit。
480-
481-- `@cls_includes` を class collection 時に populate
482-- `compute_ancestors` Ruby 側で実装
483-- `sp_class_ancestors_flat` / `_off` 配列 emission (条件付き)
484-- `sp_class_parents` 配列 emission (条件付き)
485-- `class.superclass`, `class.ancestors`, `class.ancestors.include?(C)`
486-- `class < other` / `<=`
487-- 動的 `is_a?` / `case-when Klass`
488-- `@needs_class_parents`, `@needs_class_ancestors` フラグ
489-- test/class_hierarchy.rb (modules を含む)
490-
491-### 各 phase の検証
492-
493-- `make test` (regressions が無いこと)
494-- `make bootstrap` (gen2.c == gen3.c)
495-- `make optcarrot` (checksum 59662)
496-
497-## Bootstrap risk
498-
499-spinel_codegen.rb 自体が `obj.class`、`.ancestors`、`.is_a?`、`.superclass`
500-を使っていれば、変更で self-host が壊れる可能性がある。実装前に grep:
501-
502-```bash
503-grep -nE "\.class\b|\.ancestors\b|\.is_a\?|\.superclass\b|\.kind_of\?" spinel_codegen.rb
504-```
505-
506-使っていれば、その箇所も新 path を通る。bootstrap で gen2 == gen3 を逐次検証
507-しながら進める。
508-
509-## メモリ・Binary size 見込み
510-
511-機能未使用 → 0 byte。
512-
513-機能フル使用 (組み込み 22 + user 30 = 52 entries の場合):
514-
515-- `sp_class_names`: 52 × 8B (ptr) + ~600B (文字列実体) ≒ 1KB
516-- `sp_class_kinds`: 52 × 1B = 52B
517-- `sp_class_parents`: 52 × 8B = 416B
518-- `sp_class_ancestors_off`: 53 × 8B = 424B
519-- `sp_class_ancestors_flat`: 平均 6 entry × 52 = 312 × 8B ≒ 2.5KB
520-
521-合計 ~4.5KB。LTO + dead code elimination でさらに削れる余地あり。