Code Generation
How the Mist AST is translated into Rust source code, including class vtables and position mapping.
The code generator converts the Mist AST into Rust source code directly — no intermediate representation.
Key files
src/lib.rs—RustCodegenstruct with output buffer, indentation tracking,Mappingfor position translationsrc/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 blockssrc/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
outputbuffer - An
indentlevel (4 spaces per level) - A
Mappingthat records(RustMap, MistMap)pairs for source position remapping - A current
positiontracker (RustMap(line, column))
Generation follows the GenRust trait:
pub trait GenRust {
fn gen_rust(&self, ctx: &mut Context, cg: &mut RustCodegen);
}And GetRust for simple string-returning types:
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:
- Struct declaration —
struct ClassName<G> { pub _super: Parent, pub field1: T1, ... }(or_vptrfor root classes) - Vtable constants — Index constants
__FN_METHODand a__V_TABLEstatic array of function pointers. For inherited classes, parent vtable entries are copied and overridden entries replaced. - Constructor —
pub fn new(...) -> Selfthat creates an uninitialized instance viaMaybeUninit, sets the vtable pointer, writes field defaults, callsself.constructor(...), and returnsthis - Method trampolines — Public methods with
selfget wrapper functions__m_methodstored in the vtable, plus virtual dispatch methods - Override support — Methods marked
overrideare validated at compile time via generated test code - Deref impls —
impl Deref<Target = Parent> for ChildandDerefMutfor inherited classes - Impl declarations — Inner
implblocks are rewritten to use the self type