Skip to main content

wcmu_basic/
wcmu_basic.rs

1//! Demonstrate the full Keleusma WCMU pipeline.
2//!
3//! Compile a script. Compute its worst-case memory usage budget.
4//! Construct a Vm with auto-sized arena. Run it.
5//!
6//! Run with: `cargo run --example wcmu_basic`
7
8use keleusma::Value;
9use keleusma::compiler::compile;
10use keleusma::lexer::tokenize;
11use keleusma::parser::parse;
12use keleusma::verify;
13use keleusma::vm::{Vm, VmState};
14
15const SCRIPT: &str = "
16loop main(input: i64) -> i64 {
17    let doubled = input * 2;
18    let _ignored = yield doubled;
19    doubled
20}
21";
22
23fn main() {
24    // Compile.
25    let tokens = tokenize(SCRIPT).expect("lex error");
26    let program = parse(&tokens).expect("parse error");
27    let module = compile(&program).expect("compile error");
28
29    // Inspect the WCMU budget for each Stream chunk in the module.
30    let chunk_wcmu = verify::module_wcmu(&module, &[]).expect("module wcmu");
31    for (idx, chunk) in module.chunks.iter().enumerate() {
32        if matches!(chunk.block_type, keleusma::bytecode::BlockType::Stream) {
33            let (stack_bytes, heap_bytes) = chunk_wcmu[idx];
34            println!("chunk `{}`:", chunk.name);
35            println!("  stack WCMU: {} bytes", stack_bytes);
36            println!("  heap  WCMU: {} bytes", heap_bytes);
37            println!("  total:      {} bytes", stack_bytes + heap_bytes);
38        }
39    }
40
41    // Construct an auto-sized arena and a Vm that borrows it.
42    let cap = keleusma::vm::auto_arena_capacity_for(&module, &[]).expect("auto capacity");
43    let arena = keleusma::Arena::with_capacity(cap);
44    let mut vm = Vm::new(module, &arena).expect("vm construction");
45    println!();
46    println!("auto-sized arena capacity: {} bytes", vm.arena().capacity());
47
48    // Drive the coroutine through one yield.
49    match vm.call(&[Value::Int(21)]).expect("vm call") {
50        VmState::Yielded(v) => println!("yielded: {:?}", v),
51        other => panic!("expected yield, got {:?}", other),
52    }
53}