Docs rewrite
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
---
|
||||
title: Classes
|
||||
description: Class declarations, constructors, inheritance, virtual dispatch, and the override keyword.
|
||||
icon: Shapes
|
||||
---
|
||||
|
||||
Mist introduces `class` as syntactic sugar for a Rust struct with a virtual method table (vtable).
|
||||
|
||||
```mist
|
||||
pub class Animal {
|
||||
str& name,
|
||||
|
||||
pub constructor(str& name)
|
||||
{
|
||||
self.name = name;
|
||||
}
|
||||
|
||||
pub void speak(&self)
|
||||
{
|
||||
println!("...");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Class fields can have default initializers:
|
||||
|
||||
```mist
|
||||
class Player {
|
||||
i32 health = 100,
|
||||
str& name,
|
||||
}
|
||||
```
|
||||
|
||||
### Inheritance
|
||||
|
||||
```mist
|
||||
class Dog : Animal {
|
||||
pub constructor(str& name)
|
||||
{
|
||||
super(name);
|
||||
}
|
||||
|
||||
override void speak(&self)
|
||||
{
|
||||
println!("Woof!");
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
The `override` keyword supports explicit base class targeting:
|
||||
|
||||
```mist
|
||||
override(Animal) void speak(&self)
|
||||
{
|
||||
println!("Woof!");
|
||||
}
|
||||
```
|
||||
|
||||
### Under the Hood
|
||||
|
||||
A class `Dog : Animal` generates:
|
||||
|
||||
1. A Rust struct with a `_super: Animal` field (or `_vptr: &'static [*const c_void]` for root classes)
|
||||
2. A vtable constant with function pointers for each public method
|
||||
3. An `impl` block with `Deref<Target = Animal>` and `DerefMut`
|
||||
4. Method trampolines (`__m_<name>`) that are dispatched through the vtable
|
||||
5. A `new()` constructor that initializes via `MaybeUninit` and calls the user's `constructor(&mut self)`
|
||||
|
||||
The vtable is unified: parent entries are copied, overridden entries replace parent slots, and new methods are appended.
|
||||
Reference in New Issue
Block a user