tishlang_cranelift_runtime/lib.rs
1//! Runtime linked into the `tish build --native-backend cranelift` executable.
2//!
3//! **`tish_run_chunk`** deserializes embedded bytecode and runs **`tishlang_vm`** — the same
4//! execution engine as `tish run --backend vm`. The crate name is historical; this is not
5//! running CLIF-emitted machine code for each Tish opcode.
6
7use tishlang_bytecode::deserialize;
8use tishlang_vm::Vm;
9
10/// Serialization format:
11/// - u64: code len
12/// - bytes: code
13/// - u64: constants count
14/// - for each constant: u8 tag + payload
15/// - u64: names count
16/// - for each name: u64 len + bytes
17///
18/// Rust-callable wrapper. Run serialized chunk data. Returns exit code (0 on success).
19pub fn tish_run_chunk(ptr: *const u8, len: usize) -> i32 {
20 tish_run_chunk_impl(ptr, len)
21}
22
23#[no_mangle]
24extern "C" fn tish_run_chunk_impl(ptr: *const u8, len: usize) -> i32 {
25 if ptr.is_null() || len < 8 {
26 return 1;
27 }
28 let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
29 match deserialize(slice) {
30 Ok(chunk) => {
31 let mut vm = Vm::new();
32 match vm.run(&chunk) {
33 Ok(_) => 0,
34 Err(e) => {
35 eprintln!("Runtime error: {}", e);
36 1
37 }
38 }
39 }
40 Err(e) => {
41 eprintln!("Deserialization error: {}", e);
42 1
43 }
44 }
45}