Support class inheritance and method resolution order (MRO)
Closed
GA
4d ago+11393+11393+01234567890123456789012345678901234567890123456789-787-787-012345678901234567890123456789
Partially resolves #965
Overview
Implements comprehensive support for single and multiple class inheritance in Monty with CPython-compatible C3 method resolution order (MRO), cooperative super() dispatch, issubclass(), __init_subclass__, custom exception subclasses, and class introspection.
Changes
- Syntax & Compiler:
- Support base class expressions and starred base unpacking in class definitions (
class Foo(*bases, Bar):). - Allow keyword arguments in class definitions (
class Foo(Bar, key=value):) forwarded to__init_subclass__. - Class-body compilation returns only the namespace dict; the compiler emits the 3-argument
type()call in the enclosing scope so base expressions evaluate at runtime in source order. - Automatically bind implicit
__class__cell closures inside methods for zero-argumentsuper().
- Support base class expressions and starred base unpacking in class definitions (
- Runtime & Class Model:
- Dynamically compute C3 linearization MRO during
type.__new__/ class creation, protected by an amortized time-limit check. - Traverse MRO during instance and class attribute lookup (
mro_getattr/mro_getattr_ref). - Support
super()proxy dispatch with both two-argumentsuper(Cls, self)and zero-argumentsuper()in methods for cooperative multiple inheritance. - Support
__init_subclass__callback invoked during class definition with custom keyword arguments. - Implement
issubclass(sub, super)supporting single classes, recursive hierarchies, and nested tuples of classes. - Support
isinstance(obj, Cls)across class inheritance hierarchies. - Support special dunder method inheritance (
__init__,__str__,__eq__,__contains__,__iter__, etc.). - Support user-defined custom exception classes subclassing
BaseException,Exception, and standard built-in exceptions, fully integrated withraiseandtry ... excepthandlers. - Implement class introspection:
cls.__bases__,cls.__mro__, andcls.mro(). - Implement
object.__new__and custom__new__allocation control.
- Dynamically compute C3 linearization MRO during
- Validation:
- Validate duplicate base classes (
TypeError: duplicate base class <name>). - Enforce consistent MRO ordering and format base class names in MRO conflicts.
- Validate
objectplacement in base class lists (e.g. rejecting(object, Bar)and(A, object, B)). - Reject built-in types other than exception types as base classes (
TypeError: type '<name>' is not an acceptable base type). - Reject metaclass keyword arguments with
NotImplementedError.
- Validate duplicate base classes (
- Memory & Cycle Collection:
- Retain base classes with reference counting.
- Update
for_each_child_idto trace base classes so the cycle collector matchesClass::py_dec_ref_ids.
- Documentation & Tests:
- Update limitations documentation (
docs/limitations/classes.md,docs/limitations/exceptions.md,docs/limitations/index.md,docs/limitations/dataclasses.md,docs/alternatives.md). - Add Python and TypeScript usage examples in
examples/classes/. - Add extensive test cases covering basic inheritance, lookup order, dunders, mutations, super dispatch,
__init_subclass__, introspection,issubclass, redefinitions, dynamic classes, and custom exceptions. - Add 31 end-to-end integration tests in
crates/monty/tests/class_inheritance.rscovering cooperative super, REPL snapshots/dumps, suspension/resumption in inherited initializers, and recursion limits.
- Update limitations documentation (
Summary by cubic
Implements single and multiple class inheritance with CPython-compatible C3 method resolution order (MRO). Previously class Foo(Bar) was rejected as not-implemented and the 3-arg type() form required empty bases; now isinstance/issubclass, super(), __init_subclass__, custom exceptions, and class introspection all resolve through MRO, and class Foo(Bar, *bases, key=...) evaluates bases and keywords at runtime in source order.
- C3 MRO validation matches CPython:
objectonly as last base, duplicate bases raiseTypeError, built-in types other than exception classes cannot be bases, and metaclass keywords remain a parse-timeNotImplementedError. Dataclass subclassing remains unsupported and is documented as such. super()does cooperative MRO dispatch, including zero-argumentsuper()in method bodies via the implicit__class__cell and method aliasing across built-in exceptions.- Custom exceptions subclass
BaseException/Exception, raise and catch correctly, and keep their type names through the wire protocol and across WASM/Python/JS host boundaries, with chaining via__context__/__cause__. issubclass(),__bases__,__mro__,mro(),__init_subclass__, andobject.__init__/__new__are supported;objectis now constructible.- Class creation, MRO scans, and exception matching honor amortized execution deadlines; base buffers are preflighted and inherited method IDs deduplicated.
- Performance fast paths were added for immediate value export, integer arithmetic, string concatenation, scalar equality,
sorted(),str.replace/str.encode, naivedate/datetime.strftimeformats, andtimedelta.days. - Dump fingerprints, serialization fixtures, and memory baselines were updated; the new
Type::Superpayload andcustom_type_namewire field are serialized through the WIT boundary.