Commit 75c55c6c
75c55c6cee80Merged
Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 2 files · +1 added · ~1 modified
Description
docs: add Class object design memo + fix Windows test path
Two unrelated changes bundled because the second is a CI hotfix:
-
docs/CLASS-OBJECT.md — Class object 実装の設計メモ (sp_Class value type, precomputed ancestors, Module 統合, 条件付き table emission など)。次セッションで実装着手予定。
-
test/file_class_methods_int_recv:
/tmp/...を cwd-relative path に変更。Windows MinGW64 build の native binary は/tmp/...を MSYS2 と同じディレクトリに解決しないため、 binwrite が黙って失敗していた (sp_file_write は fopen 失敗を 検知しない)。bundle_io_sys.rb / fileio.rb と同じ workaround。
Co-Authored-By: Claude Opus 4.7 (1M context) [email protected]
Details
- Commit
- 75c55c6cee80
- Parent
- 7463eaf29072
docs/CLASS-OBJECT.mdaddedView file
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` → 親 class21+
- `Klass.ancestors` → 含む module 込みの祖先 list22+
- `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+
```c41+
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 table58+
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 ancestors111+
112+
ancestors の MRO 計算は **codegen 時** に Ruby 側で展開し、flat 配列に焼く。113+
runtime は単純 lookup のみ。114+
115+
### Codegen のアルゴリズム116+
117+
```ruby118+
def compute_ancestors(i, acc = [])119+
return acc if acc.include?(i)120+
if @kind[i] == :module121+
acc.push(i)122+
@includes[i].each { |j| compute_ancestors(j, acc) }123+
else124+
# class125+
acc.push(i)126+
@includes[i].reverse_each { |j| compute_ancestors(j, acc) }127+
if @parents[i] >= 0128+
compute_ancestors(@parents[i], acc)129+
end130+
end131+
acc132+
end133+
```134+
135+
include 順序 (逆順) と dedup を含めて、CRuby の MRO と同じ並びを生成する。136+
137+
### 出力テーブル138+
139+
```c140+
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+
```c172+
typedef struct { mrb_int cls_id; } sp_Class;173+
174+
#define SP_KIND_CLASS 1175+
#define SP_KIND_MODULE 2176+
177+
/* Built-in cls_id 定数 */178+
#define SP_CLASS_BASICOBJECT 0179+
#define SP_CLASS_OBJECT 1180+
#define SP_CLASS_KERNEL 2181+
#define SP_CLASS_COMPARABLE 3182+
#define SP_CLASS_ENUMERABLE 4183+
#define SP_CLASS_NIL 5184+
#define SP_CLASS_TRUE 6185+
#define SP_CLASS_FALSE 7186+
#define SP_CLASS_NUMERIC 8187+
#define SP_CLASS_INTEGER 9188+
#define SP_CLASS_FLOAT 10189+
#define SP_CLASS_STRING 11190+
#define SP_CLASS_SYMBOL 12191+
#define SP_CLASS_ARRAY 13192+
#define SP_CLASS_HASH 14193+
#define SP_CLASS_RANGE 15194+
#define SP_CLASS_TIME 16195+
#define SP_CLASS_MODULE 17196+
#define SP_CLASS_CLASS 18197+
#define SP_CLASS_METHOD 19198+
#define SP_CLASS_COMPLEX 20199+
#define SP_CLASS_PROC 21200+
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+
## 条件付き emission277+
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 emission289+
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 で OK298+
(builtin 22 + user ~30 = 52 entry × 平均 6 ancestors ≒ 2.5KB)。299+
最適化は後回し。300+
301+
## Codegen 変更点302+
303+
### 1. Class index 管理304+
305+
```ruby306+
# 初期化時に 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.length312+
313+
# user class の cls_id は @builtin_class_count + ci314+
def cls_id_for_user_ci(ci)315+
@builtin_class_count + ci316+
end317+
318+
# 静的型から cls_id を解決319+
def cls_id_for_static_type(t)320+
case t321+
when "int" then SP_CLASS_INTEGER322+
when "float" then SP_CLASS_FLOAT323+
when "string", "mutable_str" then SP_CLASS_STRING324+
when "symbol" then SP_CLASS_SYMBOL325+
...326+
when /^obj_(.+)$/ then cls_id_for_user_ci(find_class_idx($1))327+
...328+
end329+
end330+
```331+
332+
### 2. `@cls_human_names`333+
334+
class collection 時に `Optcarrot::NES` 形式 (`::` 区切り) を別途記録する。335+
336+
```ruby337+
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+
end345+
346+
def human_join(prefix, local)347+
# prefix は "Optcarrot" 形式 (まだ underscore されていない場合)、348+
# または "Optcarrot_Inner" 形式 (nest している場合) を想定。349+
prefix.split("_").join("::") + "::" + local350+
end351+
```352+
353+
### 3. `obj.class` の lowering354+
355+
```ruby356+
# compile_object_method_expr 内357+
if mname == "class"358+
cid = cls_id_for_static_type(recv_type)359+
if cid >= 0360+
@needs_class_table = 1361+
return "((sp_Class){#{cid}})"362+
end363+
if recv_type == "poly"364+
@needs_class_table = 1365+
return "sp_class_for_poly(#{rc})"366+
end367+
end368+
```369+
370+
`infer_call_type` で `<recv>.class → "class"`。371+
372+
### 4. `class` 受信のメソッド373+
374+
```ruby375+
# compile_object_method_expr 内、recv_type == "class"376+
case mname377+
when "to_s", "name", "inspect"378+
@needs_class_table = 1379+
"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 = 1386+
@needs_class_parents = 1387+
"sp_class_superclass(#{rc})"388+
when "ancestors"389+
@needs_class_table = 1390+
@needs_class_ancestors = 1391+
"sp_class_ancestors_arr(#{rc})"392+
when "<"393+
@needs_class_ancestors = 1394+
"sp_class_lt(#{rc}, #{compile_arg0(nid)})"395+
when "<="396+
@needs_class_ancestors = 1397+
"sp_class_le(#{rc}, #{compile_arg0(nid)})"398+
when "class"399+
@needs_class_table = 1400+
"sp_class_meta(#{rc})"401+
end402+
```403+
404+
### 5. ConstantReadNode (Class/Module 名) を value で使う405+
406+
`compile_expr` で ConstantReadNode を扱う path を拡張:407+
408+
```ruby409+
# 既存: 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 >= 0415+
@needs_class_table = 1416+
return "((sp_Class){#{cid}})"417+
end418+
...419+
end420+
```421+
422+
`infer_type` も同様に: ConstantReadNode が class/module 名 → "class" 型。423+
424+
### 6. `is_a?` の拡張425+
426+
既存の static cls_id check はそのまま。動的 (poly) recv に対しては:427+
428+
```ruby429+
if mname == "is_a?" && recv_type == "poly"430+
@needs_class_ancestors = 1431+
"sp_class_le(sp_class_for_poly(#{rc}), #{compile_arg0(nid)})"432+
end433+
```434+
435+
ここで arg0 が ConstantReadNode (例: `Foo`) なら、上記の Class const-as-value436+
ルールで `((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+
```ruby445+
# WhenNode condition compile446+
when_cond_type = infer_type(cond)447+
if when_cond_type == "class"448+
# sp_class_case_match で評価449+
@needs_class_ancestors = 1450+
emit_when "sp_class_case_match(#{compile_expr(cond)}, sp_class_for_poly(#{subject}))"451+
end452+
```453+
454+
## Phase 計画455+
456+
### Phase 1 — sp_Class コア + Class entries457+
1 commit。Module は暫定で全部 CLASS として登録 (`is_a?(Module)` は次 phase)。458+
459+
- `sp_Class` struct + `SP_TAG_CLASS` poly tag460+
- `@builtin_class_*` 配列を Compiler init で登録461+
- `@cls_human_names` tracking462+
- `sp_class_names` 配列 emission (条件付き)463+
- `obj.class` の static lowering464+
- `class.to_s` / `.name` / `.inspect` / `==` / `!=` / `class` (meta)465+
- `@needs_class_table` フラグ466+
- test/builtin_class_basic.rb467+
468+
### Phase 2 — Constant as value + Module 区別469+
1 commit。470+
471+
- `kind` フィールド追加 (CLASS / MODULE)472+
- Module を MODULE として登録473+
- `sp_class_kinds` 配列 emission474+
- ConstantReadNode (class/module 名) → `((sp_Class){cid})` lowering475+
- `Klass.class == Class`, `Mod.class == Module` 動作確認476+
- test/class_constant_as_value.rb477+
478+
### Phase 3 — Precomputed ancestors + subclass / superclass479+
1 commit。480+
481+
- `@cls_includes` を class collection 時に populate482+
- `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 risk498+
499+
spinel_codegen.rb 自体が `obj.class`、`.ancestors`、`.is_a?`、`.superclass`500+
を使っていれば、変更で self-host が壊れる可能性がある。実装前に grep:501+
502+
```bash503+
grep -nE "\.class\b|\.ancestors\b|\.is_a\?|\.superclass\b|\.kind_of\?" spinel_codegen.rb504+
```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 (文字列実体) ≒ 1KB516+
- `sp_class_kinds`: 52 × 1B = 52B517+
- `sp_class_parents`: 52 × 8B = 416B518+
- `sp_class_ancestors_off`: 53 × 8B = 424B519+
- `sp_class_ancestors_flat`: 平均 6 entry × 52 = 312 × 8B ≒ 2.5KB520+
521+
合計 ~4.5KB。LTO + dead code elimination でさらに削れる余地あり。test/file_class_methods_int_recv.rbmodifiedView file
Loading diff…