Commit fb028522

fb0285220b43Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 8 months ago · 3 files · +1 added · ~2 modified

Description

Add class inheritance and super

Design: cast-to-parent approach (no vtables):

  • Child structs embed parent fields at the same offsets
  • Inherited method calls cast child pointer to parent type
  • Method resolution walks superclass chain (find_method_inherited)
  • super(args) calls parent's method with cast

Implementation:

  • Superclass extraction from PM_CONSTANT_READ_NODE
  • Ivar inheritance: parent ivars prepended to child struct
  • Type propagation: parent ivar/param types flow to children
  • emit_initialize_func() for super() calls
  • Constructor generation for classes inheriting initialize

Test: examples/bm_inherit.rb — Animal/Dog/Cat hierarchy with inherited methods, overrides, super(), and polymorphic access.

All regressions pass.

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

Details

Commit
fb0285220b43
Parent
246c0e942b4b

examples/bm_inherit.rbaddedView file

1+# Test inheritance and super
2+
3+class Animal
4+ def initialize(name)
5+ @name = name
6+ end
7+
8+ def name
9+ @name
10+ end
11+
12+ def speak
13+ "..."
14+ end
15+
16+ def describe
17+ name
18+ end
19+end
20+
21+class Dog < Animal
22+ def initialize(name, breed)
23+ super(name)
24+ @breed = breed
25+ end
26+
27+ def breed
28+ @breed
29+ end
30+
31+ def speak
32+ "Woof!"
33+ end
34+end
35+
36+class Cat < Animal
37+ def speak
38+ "Meow!"
39+ end
40+end
41+
42+# Basic inheritance
43+dog = Dog.new("Rex", "Labrador")
44+puts dog.name # Rex (inherited)
45+puts dog.breed # Labrador
46+puts dog.speak # Woof! (overridden)
47+puts dog.describe # Rex (inherited, calls name)
48+
49+cat = Cat.new("Whiskers")
50+puts cat.name # Whiskers (inherited)
51+puts cat.speak # Meow! (overridden)
52+puts cat.describe # Whiskers (inherited)