54 lines
2.5 KiB
Plaintext
54 lines
2.5 KiB
Plaintext
---
|
|
title: Code Generation
|
|
description: How the Mist AST is translated into Rust source code, including class vtables and position mapping.
|
|
icon: Wrench
|
|
---
|
|
|
|
The code generator converts the Mist AST into Rust source code directly — no intermediate representation.
|
|
|
|
### Key files
|
|
|
|
- `src/lib.rs` — `RustCodegen` struct with output buffer, indentation tracking, `Mapping` for position translation
|
|
- `src/top_level.rs` — Generates Rust for top-level items (structs, enums, traits, functions, impls, imports, type aliases, const/static)
|
|
- `src/statement.rs` — Generates Rust for statements and blocks
|
|
- `src/expr.rs` — Generates Rust for expressions (literals, paths, binary ops, closures, arrays, prefix/postfix)
|
|
- `src/class_decl.rs` — Class-specific code generation (struct + vtable + impl blocks + Deref)
|
|
|
|
### Codegen Design
|
|
|
|
The `RustCodegen` maintains:
|
|
- A string `output` buffer
|
|
- An `indent` level (4 spaces per level)
|
|
- A `Mapping` that records `(RustMap, MistMap)` pairs for source position remapping
|
|
- A current `position` tracker (`RustMap(line, column)`)
|
|
|
|
Generation follows the `GenRust` trait:
|
|
|
|
```rust
|
|
pub trait GenRust {
|
|
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen);
|
|
}
|
|
```
|
|
|
|
And `GetRust` for simple string-returning types:
|
|
|
|
```rust
|
|
pub trait GetRust {
|
|
fn get_rust(&self) -> String;
|
|
}
|
|
```
|
|
|
|
The `Context` carries optional expression path information for class `super` / `Super` resolution.
|
|
|
|
### Class Codegen
|
|
|
|
Classes are the most complex codegen path. `ClassProcessedData` analyzes a class declaration and emits:
|
|
|
|
1. **Struct declaration** — `struct ClassName<G> { pub _super: Parent, pub field1: T1, ... }` (or `_vptr` for root classes)
|
|
2. **Vtable constants** — Index constants `__FN_METHOD` and a `__V_TABLE` static array of function pointers. For inherited classes, parent vtable entries are copied and overridden entries replaced.
|
|
3. **Constructor** — `pub fn new(...) -> Self` that creates an uninitialized instance via `MaybeUninit`, sets the vtable pointer, writes field defaults, calls `self.constructor(...)`, and returns `this`
|
|
4. **Method trampolines** — Public methods with `self` get wrapper functions `__m_method` stored in the vtable, plus virtual dispatch methods
|
|
5. **Override support** — Methods marked `override` are validated at compile time via generated test code
|
|
6. **Deref impls** — `impl Deref<Target = Parent> for Child` and `DerefMut` for inherited classes
|
|
7. **Impl declarations** — Inner `impl` blocks are rewritten to use the self type
|