Skip to main content

generic_struct/
generic_struct.rs

1//! Demonstration that generic structs compile and execute end to end.
2//!
3//! Generic structs declare type parameters in `<T, U>` form between
4//! the struct name and the field block. Field type expressions may
5//! reference these parameters. Construction at use sites instantiates
6//! the parameters, and field access on a generic struct returns the
7//! per-instance instantiated field type.
8//!
9//! Run with: `cargo run --example generic_struct`
10
11use keleusma::compiler::compile;
12use keleusma::lexer::tokenize;
13use keleusma::parser::parse;
14use keleusma::vm::{DEFAULT_ARENA_CAPACITY, Vm, VmState};
15use keleusma::{Arena, Value};
16
17fn main() {
18    let src = r#"
19        struct Cell<T> { value: T }
20        fn main() -> i64 {
21            let c = Cell { value: 42 };
22            c.value
23        }
24    "#;
25    let tokens = tokenize(src).expect("lex");
26    let program = parse(&tokens).expect("parse");
27    let module = compile(&program).expect("compile");
28    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
29    let mut vm = Vm::new(module, &arena).expect("verify");
30    match vm.call(&[]) {
31        Ok(VmState::Finished(Value::Int(n))) => {
32            println!("Cell {{ value: 42 }}.value = {}", n);
33            assert_eq!(n, 42);
34            println!("generic struct executed end to end");
35        }
36        other => panic!("unexpected: {:?}", other),
37    }
38}