Support class inheritance and method resolution order (MRO)

Closed
GA
4d ago
+11393-787

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-argument super().
  • 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-argument super(Cls, self) and zero-argument super() 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 with raise and try ... except handlers.
    • Implement class introspection: cls.__bases__, cls.__mro__, and cls.mro().
    • Implement object.__new__ and custom __new__ allocation control.
  • Validation:
    • Validate duplicate base classes (TypeError: duplicate base class <name>).
    • Enforce consistent MRO ordering and format base class names in MRO conflicts.
    • Validate object placement 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.
  • Memory & Cycle Collection:
    • Retain base classes with reference counting.
    • Update for_each_child_id to trace base classes so the cycle collector matches Class::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.rs covering cooperative super, REPL snapshots/dumps, suspension/resumption in inherited initializers, and recursion limits.

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: object only as last base, duplicate bases raise TypeError, built-in types other than exception classes cannot be bases, and metaclass keywords remain a parse-time NotImplementedError. Dataclass subclassing remains unsupported and is documented as such.
  • super() does cooperative MRO dispatch, including zero-argument super() 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__, and object.__init__/__new__ are supported; object is 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, naive date/datetime.strftime formats, and timedelta.days.
  • Dump fingerprints, serialization fixtures, and memory baselines were updated; the new Type::Super payload and custom_type_name wire field are serialized through the WIT boundary.