Skip to main content

generic_identity/
generic_identity.rs

1//! Demonstration that a generic identity function compiles and runs
2//! end to end against the existing bytecode runtime.
3//!
4//! Keleusma's `Value` enum is runtime-tagged. Bytecode operations
5//! dispatch on the tag, so a generic chunk that flows a value through
6//! unchanged works for any type without compile-time monomorphization.
7//! More complex generics that constrain `T` to a specific shape
8//! (arithmetic, fields) require monomorphization to enforce the
9//! constraint at compile time.
10//!
11//! Run with: `cargo run --example generic_identity`
12
13use keleusma::compiler::compile;
14use keleusma::lexer::tokenize;
15use keleusma::parser::parse;
16use keleusma::vm::{DEFAULT_ARENA_CAPACITY, Vm, VmState};
17use keleusma::{Arena, Value};
18
19fn main() {
20    let src = r#"
21        fn id<T>(x: T) -> T { x }
22        fn main() -> i64 { id(42) }
23    "#;
24    let tokens = tokenize(src).expect("lex");
25    let program = parse(&tokens).expect("parse");
26    let module = compile(&program).expect("compile");
27    let arena = Arena::with_capacity(DEFAULT_ARENA_CAPACITY);
28    let mut vm = Vm::new(module, &arena).expect("verify");
29    match vm.call(&[]) {
30        Ok(VmState::Finished(Value::Int(n))) => {
31            println!("id(42) = {}", n);
32            assert_eq!(n, 42);
33            println!("generic identity executed end to end");
34        }
35        other => panic!("unexpected: {:?}", other),
36    }
37}