Skip to main content

vm/
lib.rs

1//使用 cranelift 作为后端 直接 jit 解释脚本
2mod binary;
3mod memory;
4mod native;
5pub use native::{ANY, STD, ZustCallback};
6
7mod fns;
8use anyhow::{Result, anyhow};
9pub use fns::{FnInfo, FnVariant};
10mod context;
11pub use context::BuildContext;
12
13mod rt;
14use cranelift::prelude::types;
15use dynamic::{Dynamic, Type};
16pub use rt::{BuiltinFn, BuiltinFnRegistry, JITRunTime};
17#[cfg(feature = "candle")]
18mod candle_module;
19#[cfg(feature = "db")]
20mod db_module;
21mod gpu_layout;
22#[cfg(feature = "gpu")]
23mod gpu_module;
24#[cfg(feature = "http")]
25mod http_module;
26#[cfg(feature = "llm")]
27mod llm_module;
28#[cfg(feature = "llm")]
29mod oss_module;
30mod root_module;
31mod time_module;
32mod math_module;
33pub use gpu_layout::{GpuFieldLayout, GpuStructLayout};
34pub use parking_lot::RwLock;
35
36use std::sync::{OnceLock, Weak};
37static PTR_TYPE: OnceLock<types::Type> = OnceLock::new();
38pub fn ptr_type() -> types::Type {
39    PTR_TYPE.get().cloned().unwrap()
40}
41
42pub fn get_type(ty: &Type) -> Result<types::Type> {
43    if ty.is_f64() {
44        Ok(types::F64)
45    } else if ty.is_f32() {
46        Ok(types::F32)
47    } else if ty.is_int() | ty.is_uint() {
48        match ty.width() {
49            1 => Ok(types::I8),
50            2 => Ok(types::I16),
51            4 => Ok(types::I32),
52            8 => Ok(types::I64),
53            _ => Err(anyhow!("非法类型 {:?}", ty)),
54        }
55    } else if let Type::Bool = ty {
56        Ok(types::I8)
57    } else {
58        Ok(ptr_type())
59    }
60}
61
62use compiler::Symbol;
63use cranelift::prelude::*;
64use cranelift_module::Module;
65
66pub fn init_jit(mut jit: JITRunTime) -> Result<JITRunTime> {
67    jit.add_all()?;
68    Ok(jit)
69}
70
71use std::sync::Arc;
72unsafe impl Send for JITRunTime {}
73unsafe impl Sync for JITRunTime {}
74
75pub type NativeContext = *const Weak<RwLock<JITRunTime>>;
76
77pub fn with_native_context<T>(context: NativeContext, f: impl FnOnce(&Vm) -> Result<T>) -> Result<T> {
78    if context.is_null() {
79        return Err(anyhow!("VM context is null"));
80    }
81    let jit = unsafe { &*context }.upgrade().ok_or_else(|| anyhow!("VM context has expired"))?;
82    let vm = Vm { jit };
83    f(&vm)
84}
85
86fn add_method_field(jit: &mut JITRunTime, def: &str, method: &str, id: u32) -> Result<()> {
87    let def_id = jit.get_id(def)?;
88    if let Some((_, define)) = jit.compiler.sym_tab.symbols.get_symbol_mut(def_id) {
89        if let Symbol::Struct(Type::Struct { params, fields }, _) = define {
90            fields.push((method.into(), Type::Symbol { id, params: params.clone() }));
91        }
92    }
93    Ok(())
94}
95
96fn add_native_module_fns(jit: &mut JITRunTime, module: &str, fns: &[(&str, &[Type], Type, *const u8)]) -> Result<()> {
97    jit.add_module(module);
98    for (name, arg_tys, ret_ty, fn_ptr) in fns {
99        let full_name = format!("{}::{}", module, name);
100        jit.add_native_ptr(&full_name, name, arg_tys, ret_ty.clone(), *fn_ptr)?;
101    }
102    jit.pop_module();
103    Ok(())
104}
105
106impl JITRunTime {
107    fn add_memory_runtime(&mut self) -> Result<()> {
108        self.native_symbols.write().insert("__vm_scope_enter".to_string(), memory::scope_enter as *const () as usize);
109        self.native_symbols.write().insert("__vm_scope_exit_void".to_string(), memory::scope_exit_void as *const () as usize);
110        self.native_symbols.write().insert("__vm_scope_exit_dynamic".to_string(), memory::scope_exit_dynamic as *const () as usize);
111        self.native_symbols.write().insert("__vm_scope_exit_bytes".to_string(), memory::scope_exit_bytes as *const () as usize);
112        self.native_symbols.write().insert("__vm_struct_alloc".to_string(), native::struct_alloc as *const () as usize);
113        self.native_symbols.write().insert("__vm_repeat_fill".to_string(), native::repeat_fill as *const () as usize);
114        self.native_symbols.write().insert("__vm_strcat".to_string(), native::strcat as *const () as usize);
115        self.native_symbols.write().insert("__vm_strcat_i64".to_string(), native::strcat_i64 as *const () as usize);
116        self.native_symbols.write().insert("__vm_strcat_assign".to_string(), native::strcat_assign as *const () as usize);
117        self.native_symbols.write().insert("__vm_callback_new".to_string(), native::callback_new as *const () as usize);
118        self.native_symbols.write().insert("__vm_callback_call".to_string(), native::callback_call as *const () as usize);
119        self.native_symbols.write().insert("__vm_spawn_ptr".to_string(), native::spawn_ptr as *const () as usize);
120        self.native_symbols.write().insert("__vm_struct_from_ptr".to_string(), native::struct_from_ptr as *const () as usize);
121        self.native_symbols.write().insert("__vm_array_from_ptr".to_string(), native::array_from_ptr as *const () as usize);
122        self.native_symbols.write().insert("__vm_array_to_ptr".to_string(), native::array_to_ptr as *const () as usize);
123        self.native_symbols.write().insert("__vm_arith_fault".to_string(), memory::arith_fault as *const () as usize);
124
125        let void_sig = self.get_sig(&[], Type::Void)?;
126        self.builtin_fns.register(BuiltinFn::ScopeEnter, self.module.declare_function("__vm_scope_enter", cranelift_module::Linkage::Import, &void_sig)?);
127        self.builtin_fns.register(BuiltinFn::ScopeExitVoid, self.module.declare_function("__vm_scope_exit_void", cranelift_module::Linkage::Import, &void_sig)?);
128
129        let dynamic_sig = self.get_sig(&[Type::Any], Type::Any)?;
130        self.builtin_fns.register(BuiltinFn::ScopeExitDynamic, self.module.declare_function("__vm_scope_exit_dynamic", cranelift_module::Linkage::Import, &dynamic_sig)?);
131
132        let bytes_sig = self.get_sig(&[Type::Any, Type::I64, Type::I64], Type::Any)?;
133        self.builtin_fns.register(BuiltinFn::ScopeExitBytes, self.module.declare_function("__vm_scope_exit_bytes", cranelift_module::Linkage::Import, &bytes_sig)?);
134
135        let struct_alloc_sig = self.get_sig(&[Type::I64], Type::Any)?;
136        self.builtin_fns.register(BuiltinFn::StructAlloc, self.module.declare_function("__vm_struct_alloc", cranelift_module::Linkage::Import, &struct_alloc_sig)?);
137
138        let repeat_fill_sig = self.get_sig(&[Type::Any, Type::I64, Type::I64, Type::I64], Type::Void)?;
139        self.builtin_fns.register(BuiltinFn::RepeatFill, self.module.declare_function("__vm_repeat_fill", cranelift_module::Linkage::Import, &repeat_fill_sig)?);
140
141        let strcat_sig = self.get_sig(&[Type::Str, Type::Str], Type::Str)?;
142        self.builtin_fns.register(BuiltinFn::Strcat, self.module.declare_function("__vm_strcat", cranelift_module::Linkage::Import, &strcat_sig)?);
143
144        let strcat_i64_sig = self.get_sig(&[Type::Str, Type::I64], Type::Str)?;
145        self.builtin_fns.register(BuiltinFn::StrcatI64, self.module.declare_function("__vm_strcat_i64", cranelift_module::Linkage::Import, &strcat_i64_sig)?);
146
147        let strcat_assign_sig = self.get_sig(&[Type::Any, Type::Any], Type::Any)?;
148        self.builtin_fns.register(BuiltinFn::StrcatAssign, self.module.declare_function("__vm_strcat_assign", cranelift_module::Linkage::Import, &strcat_assign_sig)?);
149
150        let callback_new_sig = self.get_sig(&[Type::I64, Type::I64, Type::I64, Type::Any], Type::Any)?;
151        self.builtin_fns.register(BuiltinFn::CallbackNew, self.module.declare_function("__vm_callback_new", cranelift_module::Linkage::Import, &callback_new_sig)?);
152
153        let callback_call_sig = self.get_sig(&[Type::Any, Type::Any], Type::Any)?;
154        self.builtin_fns.register(BuiltinFn::CallbackCall, self.module.declare_function("__vm_callback_call", cranelift_module::Linkage::Import, &callback_call_sig)?);
155
156        let spawn_ptr_sig = self.get_sig(&[Type::I64, Type::I64, Type::Any], Type::Bool)?;
157        self.builtin_fns.register(BuiltinFn::SpawnPtr, self.module.declare_function("__vm_spawn_ptr", cranelift_module::Linkage::Import, &spawn_ptr_sig)?);
158
159        let struct_from_ptr_sig = self.get_sig(&[Type::I64, Type::I64], Type::Any)?;
160        self.builtin_fns.register(BuiltinFn::StructFromPtr, self.module.declare_function("__vm_struct_from_ptr", cranelift_module::Linkage::Import, &struct_from_ptr_sig)?);
161        self.builtin_fns.register(BuiltinFn::ArrayFromPtr, self.module.declare_function("__vm_array_from_ptr", cranelift_module::Linkage::Import, &struct_from_ptr_sig)?);
162        let array_to_ptr_sig = self.get_sig(&[Type::Any, Type::Any, Type::I64], Type::Void)?;
163        self.builtin_fns.register(BuiltinFn::ArrayToPtr, self.module.declare_function("__vm_array_to_ptr", cranelift_module::Linkage::Import, &array_to_ptr_sig)?);
164
165        self.builtin_fns.register(BuiltinFn::ArithFault, self.module.declare_function("__vm_arith_fault", cranelift_module::Linkage::Import, &void_sig)?);
166        Ok(())
167    }
168
169    pub fn add_module(&mut self, name: &str) {
170        self.compiler.sym_tab.symbols.add_module(name.into());
171    }
172
173    pub fn pop_module(&mut self) {
174        self.compiler.sym_tab.symbols.pop_module();
175    }
176
177    pub fn add_native_const(&mut self, name: &str, value: impl Into<Dynamic>, ty: Type) -> u32 {
178        self.compiler.add_symbol(name, Symbol::Const { value: value.into(), ty, is_pub: true })
179    }
180
181    pub fn add_type(&mut self, name: &str, ty: Type, is_pub: bool) -> u32 {
182        self.compiler.add_symbol(name, Symbol::Struct(ty, is_pub))
183    }
184
185    pub fn add_empty_type(&mut self, name: &str) -> Result<u32> {
186        match self.get_id(name) {
187            Ok(id) => Ok(id),
188            Err(_) => Ok(self.add_type(name, Type::Struct { params: Vec::new(), fields: Vec::new() }, true)),
189        }
190    }
191
192    pub fn add_native_module_ptr(&mut self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
193        self.add_module(module);
194        let full_name = format!("{}::{}", module, name);
195        let result = self.add_native_ptr(&full_name, name, arg_tys, ret_ty, fn_ptr);
196        self.pop_module();
197        result
198    }
199
200    pub fn add_native_module_context_ptr(&mut self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
201        self.add_module(module);
202        let full_name = format!("{}::{}", module, name);
203        let result = self.add_context_native_ptr(&full_name, name, arg_tys, ret_ty, fn_ptr);
204        self.pop_module();
205        result
206    }
207
208    pub fn add_native_method_ptr(&mut self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
209        self.add_empty_type(def)?;
210        let full_name = format!("{}::{}", def, method);
211        let id = self.add_native_ptr(&full_name, &full_name, arg_tys, ret_ty, fn_ptr)?;
212        add_method_field(self, def, method, id)?;
213        Ok(id)
214    }
215
216    pub fn add_std(&mut self) -> Result<()> {
217        if self.compiler.sym_tab.symbols.get_id("std::print").is_ok() {
218            return Ok(());
219        }
220        self.add_module("std");
221        for (name, arg_tys, ret_ty, fn_ptr) in STD {
222            self.add_native_ptr(name, name, arg_tys, ret_ty, fn_ptr)?;
223        }
224        self.add_context_native_ptr("import", "import", &[Type::Any, Type::Any], Type::Bool, native::import_with_vm as *const u8)?;
225        self.add_context_native_ptr("spawn", "spawn", &[Type::Any, Type::Any], Type::Bool, native::spawn_with_vm as *const u8)?;
226        Ok(())
227    }
228
229    pub fn add_any(&mut self) -> Result<()> {
230        if self.compiler.sym_tab.symbols.get_id("Any").is_ok() && self.compiler.sym_tab.symbols.get_id("Any::is_map").is_ok() {
231            return Ok(());
232        }
233        for (name, arg_tys, ret_ty, fn_ptr) in ANY {
234            let (_, method) = name.split_once("::").ok_or_else(|| anyhow!("非法 Any 方法名 {}", name))?;
235            self.add_native_method_ptr("Any", method, arg_tys, ret_ty, fn_ptr)?;
236        }
237        Ok(())
238    }
239
240    pub fn add_vec(&mut self) -> Result<()> {
241        if self.compiler.sym_tab.symbols.get_id("Vec::get_idx").is_ok() {
242            return Ok(());
243        }
244        self.add_empty_type("Vec")?;
245        let vec_def = Type::Symbol { id: self.get_id("Vec")?, params: Vec::new() };
246        self.add_inline("Vec::swap", vec![vec_def.clone(), Type::I64, Type::I64], Type::Void, |ctx: Option<&mut BuildContext>, args: Vec<Value>| {
247            if let Some(ctx) = ctx {
248                let width = ctx.builder.ins().iconst(types::I64, 4);
249                let offset_val = ctx.builder.ins().imul(args[1], width); // i * 4 i32大小四字节
250                let final_addr = ctx.builder.ins().iadd(args[0], offset_val); // base + (i*4)
251                let dest = ctx.builder.ins().imul(args[2], width);
252                let dest_addr = ctx.builder.ins().iadd(args[0], dest); // base + (i*4)
253                let dest_val = ctx.builder.ins().load(types::I32, MemFlags::trusted(), dest_addr, 0);
254                let v = ctx.builder.ins().load(types::I32, MemFlags::trusted(), final_addr, 0);
255                ctx.builder.ins().store(MemFlags::trusted(), v, dest_addr, 0);
256                ctx.builder.ins().store(MemFlags::trusted(), dest_val, final_addr, 0);
257            }
258            Err(anyhow!("无返回值"))
259        })?;
260
261        self.add_inline("Vec::get_idx", vec![vec_def.clone(), Type::I64], Type::I32, |ctx: Option<&mut BuildContext>, args: Vec<Value>| {
262            if let Some(ctx) = ctx {
263                let width = ctx.builder.ins().iconst(types::I64, 4);
264                let offset_val = ctx.builder.ins().imul(args[1], width); // i * 4 i32大小四字节
265                let final_addr = ctx.builder.ins().iadd(args[0], offset_val);
266                Ok((Some(ctx.builder.ins().load(types::I32, MemFlags::trusted(), final_addr, 0)), Type::I32))
267            } else {
268                Ok((None, Type::I32))
269            }
270        })?;
271        Ok(())
272    }
273
274    #[cfg(feature = "llm")]
275    pub fn add_llm(&mut self) -> Result<()> {
276        if self.compiler.sym_tab.symbols.get_id("llm::complete").is_ok() {
277            return Ok(());
278        }
279        add_native_module_fns(self, "llm", &llm_module::LLM_NATIVE)?;
280        add_native_module_fns(self, "oss", &oss_module::OSS_NATIVE)
281    }
282
283    #[cfg(feature = "candle")]
284    pub fn add_candle(&mut self) -> Result<()> {
285        if self.compiler.sym_tab.symbols.get_id("candle::embed").is_ok() {
286            return Ok(());
287        }
288        add_native_module_fns(self, "candle", &candle_module::CANDLE_NATIVE)
289    }
290
291    pub fn add_root(&mut self) -> Result<()> {
292        if self.compiler.sym_tab.symbols.get_id("root::get").is_ok() {
293            return Ok(());
294        }
295        add_native_module_fns(self, "root", &root_module::ROOT_NATIVE)?;
296        self.add_native_module_context_ptr("root", "add_fn", &[Type::Any, Type::Any], Type::Bool, root_module::root_add_fn_with_vm as *const u8)?;
297        Ok(())
298    }
299
300    pub fn add_time(&mut self) -> Result<()> {
301        if self.compiler.sym_tab.symbols.get_id("time::now").is_ok() {
302            return Ok(());
303        }
304        add_native_module_fns(self, "time", &time_module::TIME_NATIVE)
305    }
306
307    pub fn add_math(&mut self) -> Result<()> {
308        if self.compiler.sym_tab.symbols.get_id("math::sin").is_ok() {
309            return Ok(());
310        }
311        add_native_module_fns(self, "math", &math_module::MATH_NATIVE)
312    }
313
314    #[cfg(feature = "http")]
315    pub fn add_http(&mut self) -> Result<()> {
316        if self.compiler.sym_tab.symbols.get_id("http::request").is_ok() {
317            return Ok(());
318        }
319        add_native_module_fns(self, "http", &http_module::HTTP_NATIVE)?;
320        http_module::add_root_handlers()
321    }
322
323    #[cfg(feature = "db")]
324    pub fn add_db(&mut self) -> Result<()> {
325        if self.compiler.sym_tab.symbols.get_id("db::select").is_ok() {
326            return Ok(());
327        }
328        add_native_module_fns(self, "db", &db_module::DB_NATIVE)
329    }
330
331    #[cfg(feature = "gpu")]
332    pub fn add_gpu(&mut self) -> Result<()> {
333        if self.compiler.sym_tab.symbols.get_id("gpu::spirv_check").is_ok() {
334            return Ok(());
335        }
336        add_native_module_fns(self, "gpu", &gpu_module::GPU_NATIVE)
337    }
338
339    pub fn add_all(&mut self) -> Result<()> {
340        self.add_std()?;
341        self.add_any()?;
342        self.add_vec()?;
343        self.add_root()?;
344        self.add_time()?;
345        self.add_math()?;
346        #[cfg(feature = "llm")]
347        self.add_llm()?;
348        #[cfg(feature = "candle")]
349        self.add_candle()?;
350        #[cfg(feature = "http")]
351        self.add_http()?;
352        #[cfg(feature = "db")]
353        self.add_db()?;
354        #[cfg(feature = "gpu")]
355        self.add_gpu()?;
356        Ok(())
357    }
358}
359
360#[derive(Clone)]
361pub struct Vm {
362    pub jit: Arc<parking_lot::RwLock<JITRunTime>>,
363}
364
365impl Vm {
366    pub fn new() -> Self {
367        dynamic::set_dynamic_return_handler(memory::take_dynamic_return);
368        let jit = Arc::new(RwLock::new(JITRunTime::new(|_| {})));
369        {
370            let mut guard = jit.write();
371            guard.set_owner(Arc::downgrade(&jit));
372            guard.add_memory_runtime().expect("register VM memory runtime");
373            guard.add_std().expect("register VM std runtime");
374            guard.add_any().expect("register VM Any runtime");
375            guard.add_vec().expect("register VM Vec runtime");
376            guard.add_root().expect("register VM root runtime");
377        }
378        Self { jit }
379    }
380
381    pub fn with_all() -> Result<Self> {
382        let vm = Self::new();
383        vm.jit.write().add_all()?;
384        Ok(vm)
385    }
386
387    pub fn import(&self, name: &str, path: &str) -> Result<()> {
388        // 之前用 contains + get 两步会因其他线程并发 add/remove 出现 race;
389        // 改用 if let Some 一次性持有,失败返回明确的错误而不是 host panic。
390        if let Ok(code) = root::get(path) {
391            if code.is_str() {
392                self.jit.write().import_code(name, code.as_str().as_bytes().to_vec())?;
393            } else {
394                self.jit.write().import_code(name, code.get_dynamic("code").ok_or_else(|| anyhow!("{:?} 没有 code 成员", code))?.as_str().as_bytes().to_vec())?;
395            }
396            Ok(())
397        } else {
398            self.jit.write().compiler.import_file(name, path)?;
399            Ok(())
400        }
401    }
402
403    pub fn import_source(&self, name: &str, source: &str) -> Result<()> {
404        self.jit.write().import_source(name, source)
405    }
406
407    pub fn add_native_module_context_ptr(&self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
408        self.jit.write().add_native_module_context_ptr(module, name, arg_tys, ret_ty, fn_ptr)
409    }
410}
411
412impl Default for Vm {
413    fn default() -> Self {
414        Self::new()
415    }
416}
417
418#[cfg(test)]
419mod tests {
420    use super::{GpuStructLayout, NativeContext, Vm, ZustCallback, with_native_context};
421    use dynamic::{CustomProperty, Dynamic, ToJson, Type};
422    use std::collections::BTreeMap;
423
424    /// Test-only wrapper for a compiled function pointer + return type.
425    struct TestFn {
426        ptr: *const u8,
427        ret: Type,
428    }
429
430    impl TestFn {
431        fn ptr(&self) -> *const u8 {
432            self.ptr
433        }
434        fn ret_ty(&self) -> &Type {
435            &self.ret
436        }
437    }
438
439    fn call_i64_0(compiled: &TestFn) -> i64 {
440        match compiled.ret_ty() {
441            Type::I64 => {
442                let f: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
443                f()
444            }
445            Type::I32 => {
446                let f: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
447                f() as i64
448            }
449            Type::Any => {
450                let f: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
451                unsafe { &*f() }.as_int().expect("integer Dynamic return")
452            }
453            other => panic!("expected integer-like return, got {other:?}"),
454        }
455    }
456
457    fn call_i64_1(compiled: &TestFn, arg: i64) -> i64 {
458        match compiled.ret_ty() {
459            Type::I64 => {
460                let f: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
461                f(arg)
462            }
463            Type::I32 => {
464                let f: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
465                f(arg) as i64
466            }
467            Type::Any => {
468                let f: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
469                unsafe { &*f(arg) }.as_int().expect("integer Dynamic return")
470            }
471            other => panic!("expected integer-like return, got {other:?}"),
472        }
473    }
474
475    /// Test-only convenience wrapping `vm.jit.write()` calls.
476    trait VmTestExt {
477        fn import_code(&self, name: &str, code: Vec<u8>) -> anyhow::Result<()>;
478        fn get_fn(&self, name: &str, arg_tys: &[Type]) -> anyhow::Result<TestFn>;
479        fn get_fn_with_params(&self, name: &str, arg_tys: &[Type], generic_args: &[Type]) -> anyhow::Result<TestFn>;
480        fn get_fn_ptr(&self, name: &str, arg_tys: &[Type]) -> anyhow::Result<(*const u8, Type)>;
481        fn infer(&self, name: &str, arg_tys: &[Type]) -> anyhow::Result<Type>;
482        fn add_native_module_ptr(&self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, ptr: *const u8) -> anyhow::Result<u32>;
483        fn add_native_method_ptr(&self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, ptr: *const u8) -> anyhow::Result<u32>;
484        fn add_empty_type(&self, name: &str) -> anyhow::Result<u32>;
485        fn add_std(&self) -> anyhow::Result<()>;
486        fn add_any(&self) -> anyhow::Result<()>;
487        fn get_symbol(&self, name: &str, params: Vec<Type>) -> anyhow::Result<Type>;
488        fn gpu_struct_layout(&self, name: &str, params: &[Type]) -> anyhow::Result<GpuStructLayout>;
489        fn load(&self, code: Vec<u8>, arg_name: smol_str::SmolStr) -> anyhow::Result<(i64, Type)>;
490    }
491
492    impl VmTestExt for Vm {
493        fn import_code(&self, name: &str, code: Vec<u8>) -> anyhow::Result<()> {
494            self.jit.write().import_code(name, code)
495        }
496        fn get_fn(&self, name: &str, arg_tys: &[Type]) -> anyhow::Result<TestFn> {
497            let (ptr, ret) = self.jit.write().get_fn_ptr(name, arg_tys)?;
498            Ok(TestFn { ptr, ret })
499        }
500        fn get_fn_with_params(&self, name: &str, arg_tys: &[Type], generic_args: &[Type]) -> anyhow::Result<TestFn> {
501            let (ptr, ret) = self.jit.write().get_fn_ptr_with_params(name, arg_tys, generic_args)?;
502            Ok(TestFn { ptr, ret })
503        }
504        fn get_fn_ptr(&self, name: &str, arg_tys: &[Type]) -> anyhow::Result<(*const u8, Type)> {
505            self.jit.write().get_fn_ptr(name, arg_tys)
506        }
507        fn infer(&self, name: &str, arg_tys: &[Type]) -> anyhow::Result<Type> {
508            self.jit.write().get_type(name, arg_tys)
509        }
510        fn add_native_module_ptr(&self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, ptr: *const u8) -> anyhow::Result<u32> {
511            self.jit.write().add_native_module_ptr(module, name, arg_tys, ret_ty, ptr)
512        }
513        fn add_native_method_ptr(&self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, ptr: *const u8) -> anyhow::Result<u32> {
514            self.jit.write().add_native_method_ptr(def, method, arg_tys, ret_ty, ptr)
515        }
516        fn add_empty_type(&self, name: &str) -> anyhow::Result<u32> {
517            self.jit.write().add_empty_type(name)
518        }
519        fn add_std(&self) -> anyhow::Result<()> {
520            self.jit.write().add_std()
521        }
522        fn add_any(&self) -> anyhow::Result<()> {
523            self.jit.write().add_any()
524        }
525        fn get_symbol(&self, name: &str, params: Vec<Type>) -> anyhow::Result<Type> {
526            Ok(Type::Symbol { id: self.jit.write().get_id(name)?, params })
527        }
528        fn gpu_struct_layout(&self, name: &str, params: &[Type]) -> anyhow::Result<GpuStructLayout> {
529            let jit = self.jit.write();
530            GpuStructLayout::from_symbol_table(&jit.compiler.sym_tab.symbols, name, params)
531        }
532        fn load(&self, code: Vec<u8>, arg_name: smol_str::SmolStr) -> anyhow::Result<(i64, Type)> {
533            self.jit.write().load(code, arg_name)
534        }
535    }
536
537    extern "C" fn math_double(value: i64) -> i64 {
538        value * 2
539    }
540
541    extern "C" fn context_has_symbol(context: NativeContext, name: *const Dynamic) -> bool {
542        if name.is_null() {
543            return false;
544        }
545        let name = unsafe { (&*name).as_str().to_string() };
546        with_native_context(context, |vm| Ok(vm.jit.write().get_id(&name).is_ok())).unwrap_or(false)
547    }
548
549    #[test]
550    fn vm_import_source_accepts_inline_utf8_zust_code() -> anyhow::Result<()> {
551        let vm = Vm::new();
552        vm.import_source(
553            "vm_utf8_source",
554            r#"
555            pub fn run() {
556                "扩展 Chunk".len()
557            }
558            "#,
559        )?;
560
561        let compiled = vm.get_fn("vm_utf8_source::run", &[])?;
562        assert_eq!(compiled.ret_ty(), &Type::I32);
563        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
564        assert_eq!(run(), 12);
565        Ok(())
566    }
567
568    #[test]
569    fn build_context_set_var_fills_sparse_none_slots() -> anyhow::Result<()> {
570        use crate::context::{BuildContext, LocalVar};
571        use cranelift::codegen::ir::{Function, Signature, UserFuncName};
572        use cranelift::codegen::isa::CallConv;
573        use cranelift::prelude::{FunctionBuilder, FunctionBuilderContext};
574
575        let mut function = Function::with_name_signature(UserFuncName::user(0, 0), Signature::new(CallConv::Fast));
576        let mut function_ctx = FunctionBuilderContext::new();
577        let builder = FunctionBuilder::new(&mut function, &mut function_ctx);
578        let mut ctx = BuildContext::new(builder, &[], Type::Void)?;
579
580        ctx.set_var(33, LocalVar::None)?;
581
582        assert!(matches!(ctx.get_var(32)?, LocalVar::None));
583        assert!(matches!(ctx.get_var(33)?, LocalVar::None));
584        assert!(ctx.get_var(34).is_err());
585        Ok(())
586    }
587
588    #[test]
589    fn vm_can_add_native_after_jit_creation() -> anyhow::Result<()> {
590        let vm = Vm::new();
591        vm.add_native_module_ptr("math", "double", &[Type::I64], Type::I64, math_double as *const u8)?;
592        vm.import_code(
593            "vm_dynamic_native",
594            br#"
595            pub fn run(value: i64) {
596                math::double(value)
597            }
598            "#
599            .to_vec(),
600        )?;
601
602        let compiled = vm.get_fn("vm_dynamic_native::run", &[Type::I64])?;
603        assert_eq!(compiled.ret_ty(), &Type::I64);
604        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
605        assert_eq!(run(21), 42);
606        Ok(())
607    }
608
609    #[test]
610    fn vm_can_add_context_native_after_jit_creation() -> anyhow::Result<()> {
611        let vm = Vm::with_all()?;
612        vm.add_native_module_context_ptr("ctx", "has_symbol", &[Type::Any], Type::Bool, context_has_symbol as *const u8)?;
613        vm.import_code(
614            "vm_dynamic_context_native",
615            br#"
616            pub struct Marker { value: i32 }
617            pub fn run() {
618                ctx::has_symbol("vm_dynamic_context_native::Marker")
619            }
620            "#
621            .to_vec(),
622        )?;
623
624        let compiled = vm.get_fn("vm_dynamic_context_native::run", &[])?;
625        assert_eq!(compiled.ret_ty(), &Type::Bool);
626        let run: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
627        assert!(run());
628        Ok(())
629    }
630
631    #[test]
632    fn vm_new_registers_std_and_any() -> anyhow::Result<()> {
633        let vm = Vm::new();
634        vm.add_std()?;
635        vm.add_any()?;
636        assert_eq!(vm.infer("std::print", &[Type::Any])?, Type::Void);
637        assert_eq!(vm.infer("std::sqrt", &[Type::F64])?, Type::F64);
638        assert_eq!(vm.infer("std::sleep", &[Type::I64])?, Type::Void);
639
640        vm.import_code(
641            "vm_new_default_any",
642            br#"
643            pub fn has_items(content) {
644                if content.is_map() {
645                    if content.contains("items") {
646                        return content.items.len() > 0;
647                    }
648                }
649                false
650            }
651            "#
652            .to_vec(),
653        )?;
654
655        assert_eq!(vm.infer("vm_new_default_any::has_items", &[Type::Any])?, Type::Bool);
656        let compiled = vm.get_fn("vm_new_default_any::has_items", &[Type::Any])?;
657        assert_eq!(compiled.ret_ty(), &Type::Bool);
658        Ok(())
659    }
660
661    #[test]
662    fn std_sqrt_is_available_as_top_level_function() -> anyhow::Result<()> {
663        let vm = Vm::with_all()?;
664        vm.import_code(
665            "vm_std_sqrt",
666            br#"
667            pub fn run() {
668                sqrt(9.0f64)
669            }
670            "#
671            .to_vec(),
672        )?;
673
674        let compiled = vm.get_fn("vm_std_sqrt::run", &[])?;
675        assert_eq!(compiled.ret_ty(), &Type::F64);
676        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
677        assert_eq!(run(), 3.0);
678        Ok(())
679    }
680
681    #[test]
682    fn std_sleep_is_available_as_top_level_function() -> anyhow::Result<()> {
683        let vm = Vm::with_all()?;
684        vm.import_code(
685            "vm_std_sleep",
686            br#"
687            pub fn run() {
688                sleep(0)
689            }
690            "#
691            .to_vec(),
692        )?;
693
694        let compiled = vm.get_fn("vm_std_sleep::run", &[])?;
695        assert_eq!(compiled.ret_ty(), &Type::Void);
696        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
697        run();
698        Ok(())
699    }
700
701    #[test]
702    fn any_trim_replace_chains_like_mlit_price_parsing() -> anyhow::Result<()> {
703        // 覆盖 MLIT 价格字段的清洗链路:" 1,760,000 " → 1760000
704        let vm = Vm::with_all()?;
705        vm.import_code(
706            "vm_any_trim_replace",
707            br#"
708            pub fn clean_price(text) {
709                let stripped = text.trim().replace(",", "");
710                stripped as i64
711            }
712            "#
713            .to_vec(),
714        )?;
715        let compiled = vm.get_fn("vm_any_trim_replace::clean_price", &[Type::Any])?;
716        let clean_price: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
717        let text = Dynamic::from(" 1,760,000 ");
718        assert_eq!(clean_price(&text), 1760000);
719        Ok(())
720    }
721
722    #[test]
723    fn any_to_lower_and_to_upper_round_trip() -> anyhow::Result<()> {
724        let vm = Vm::with_all()?;
725        vm.import_code(
726            "vm_any_case",
727            br#"
728            pub fn lower(text) { text.to_lower() }
729            pub fn upper(text) { text.to_upper() }
730            "#
731            .to_vec(),
732        )?;
733        let compiled = vm.get_fn("vm_any_case::lower", &[Type::Any])?;
734        let lower: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
735        assert_eq!(unsafe { (&*lower(&Dynamic::from("AbCア炎"))) }.as_str(), "abcア炎");
736        let compiled = vm.get_fn("vm_any_case::upper", &[Type::Any])?;
737        let upper: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
738        assert_eq!(unsafe { (&*upper(&Dynamic::from("AbC"))) }.as_str(), "ABC");
739        Ok(())
740    }
741
742    #[test]
743    fn any_find_returns_minus_one_when_substring_absent() -> anyhow::Result<()> {
744        let vm = Vm::with_all()?;
745        vm.import_code(
746            "vm_any_find",
747            br#"
748            pub fn find_comma(text) { text.find(",") }
749            "#
750            .to_vec(),
751        )?;
752        let compiled = vm.get_fn("vm_any_find::find_comma", &[Type::Any])?;
753        let find_comma: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
754        assert_eq!(find_comma(&Dynamic::from("a,b")), 1);
755        assert_eq!(find_comma(&Dynamic::from("abc")), -1);
756        Ok(())
757    }
758
759    #[test]
760    fn any_substring_clamps_out_of_range_indices() -> anyhow::Result<()> {
761        let vm = Vm::with_all()?;
762        vm.import_code(
763            "vm_any_substring",
764            br#"
765            pub fn head(text) { text.substring(0, 100) }
766            pub fn middle(text) { text.substring(1, 3) }
767            "#
768            .to_vec(),
769        )?;
770        let compiled = vm.get_fn("vm_any_substring::head", &[Type::Any])?;
771        let head: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
772        assert_eq!(unsafe { (&*head(&Dynamic::from("hello"))) }.as_str(), "hello");
773        let compiled = vm.get_fn("vm_any_substring::middle", &[Type::Any])?;
774        let middle: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
775        assert_eq!(unsafe { (&*middle(&Dynamic::from("hello"))) }.as_str(), "el");
776        Ok(())
777    }
778
779    #[test]
780    fn math_sin_cos_and_pi_work_in_radians() -> anyhow::Result<()> {
781        let vm = Vm::with_all()?;
782        vm.import_code(
783            "vm_math_trig",
784            br#"
785            pub fn sin_zero() { math::sin(0.0f64) }
786            pub fn atan2_pi() { math::atan2(0.0f64, -1.0f64) }
787            pub fn pi_value() { math::pi() }
788            "#
789            .to_vec(),
790        )?;
791        let compiled = vm.get_fn("vm_math_trig::sin_zero", &[])?;
792        let sin_zero: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
793        assert!((sin_zero()).abs() < 1e-12);
794
795        let compiled = vm.get_fn("vm_math_trig::atan2_pi", &[])?;
796        let atan2_pi: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
797        let compiled = vm.get_fn("vm_math_trig::pi_value", &[])?;
798        let pi_value: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
799        assert!((atan2_pi() - pi_value()).abs() < 1e-12);
800        Ok(())
801    }
802
803    #[test]
804    fn math_floor_ceil_pow_max_min_basics() -> anyhow::Result<()> {
805        let vm = Vm::with_all()?;
806        vm.import_code(
807            "vm_math_basic",
808            br#"
809            pub fn floor_it() { math::floor(3.7f64) as i64 }
810            pub fn ceil_it() { math::ceil(3.2f64) as i64 }
811            pub fn pow_it() { math::pow(2.0f64, 10.0f64) as i64 }
812            pub fn max_it() { math::max(3.0f64, 5.0f64) as i64 }
813            pub fn min_it() { math::min(3.0f64, 5.0f64) as i64 }
814            "#
815            .to_vec(),
816        )?;
817        for (fname, expected) in [("floor_it", 3i64), ("ceil_it", 4), ("pow_it", 1024), ("max_it", 5), ("min_it", 3)] {
818            let full = format!("vm_math_basic::{fname}");
819            let compiled = vm.get_fn(&full, &[])?;
820            let f: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
821            assert_eq!(f(), expected, "{fname}");
822        }
823        Ok(())
824    }
825
826    #[cfg(feature = "candle")]
827    #[test]
828    fn candle_module_registers_embed() -> anyhow::Result<()> {
829        let vm = Vm::with_all()?;
830        assert_eq!(vm.infer("candle::embed", &[Type::Any, Type::Any])?, Type::Any);
831        assert_eq!(vm.infer("candle::load_embedder", &[Type::Any])?, Type::Any);
832        Ok(())
833    }
834
835    #[test]
836    fn time_now_returns_current_unix_millis() -> anyhow::Result<()> {
837        let vm = Vm::with_all()?;
838        vm.import_code(
839            "vm_time_now",
840            br#"
841            pub fn run() {
842                time::now()
843            }
844            "#
845            .to_vec(),
846        )?;
847
848        let compiled = vm.get_fn("vm_time_now::run", &[])?;
849        assert_eq!(compiled.ret_ty(), &Type::I64);
850        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
851        let before = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
852        let now = run();
853        let after = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?.as_millis() as i64;
854        assert!(now >= before && now <= after, "time::now() = {now} not in [{before}, {after}]");
855        Ok(())
856    }
857
858    #[test]
859    fn time_format_and_parse_round_trip() -> anyhow::Result<()> {
860        let vm = Vm::with_all()?;
861        vm.import_code(
862            "vm_time_format",
863            br#"
864            // strftime-style format spec
865            pub fn fmt(tick: i64) {
866                time::format("%Y-%m-%d %H:%M:%S", tick)
867            }
868
869            pub fn parse(text) {
870                time::parse("%Y-%m-%d %H:%M:%S", text)
871            }
872            "#
873            .to_vec(),
874        )?;
875
876        // 2020-01-02 03:04:05 UTC = 1577934245 秒 = 1577934245000 毫秒
877        let known_tick: i64 = 1_577_934_245_000;
878        let fmt = vm.get_fn("vm_time_format::fmt", &[Type::I64])?;
879        let f: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(fmt.ptr()) };
880        let formatted = unsafe { (*f(known_tick)).clone() };
881        assert_eq!(formatted.as_str().to_string(), "2020-01-02 03:04:05");
882
883        // 反向 parse 回来应当得到相同毫秒
884        let parse = vm.get_fn("vm_time_format::parse", &[Type::Any])?;
885        let p: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(parse.ptr()) };
886        let text = Dynamic::from("2020-01-02 03:04:05");
887        let parsed = p(&text as *const _);
888        assert_eq!(parsed, known_tick);
889
890        // 非法输入返回 -1,而不是抛
891        let bad = Dynamic::from("not a date");
892        assert_eq!(p(&bad as *const _), -1);
893        Ok(())
894    }
895
896    #[test]
897    fn tuple_assignment_uses_simultaneous_scalar_temps() -> anyhow::Result<()> {
898        let vm = Vm::with_all()?;
899        vm.import_code(
900            "vm_tuple_assignment",
901            br#"
902            pub fn swap() {
903                let a = 1i64;
904                let b = 2i64;
905                (a, b) = (b, a);
906                a * 10i64 + b
907            }
908
909            pub fn fib(n: i64) {
910                let a = 0i64;
911                let b = 1i64;
912                for _ in 0..n {
913                    (a, b) = (b, (a + b) % 1000000007i64);
914                }
915                a
916            }
917            "#
918            .to_vec(),
919        )?;
920
921        let swap = vm.get_fn("vm_tuple_assignment::swap", &[])?;
922        let swap: extern "C" fn() -> i64 = unsafe { std::mem::transmute(swap.ptr()) };
923        assert_eq!(swap(), 21);
924
925        let fib = vm.get_fn("vm_tuple_assignment::fib", &[Type::I64])?;
926        let fib: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(fib.ptr()) };
927        assert_eq!(fib(10), 55);
928        Ok(())
929    }
930
931    #[test]
932    fn nested_struct_arg_return_struct_field_is_static_field_access() -> anyhow::Result<()> {
933        let vm = Vm::with_all()?;
934        vm.import_code(
935            "vm_nested_struct_return_field",
936            br#"
937            pub struct Inner {
938                value: i64,
939            }
940
941            pub struct RoleMini {
942                inner: Inner,
943                hp: i64,
944            }
945
946            pub struct TeamMini {
947                role: RoleMini,
948            }
949
950            pub struct BigSummary {
951                winner: i64,
952                loser: i64,
953            }
954
955            pub fn make_big_with_team(team: TeamMini) {
956                let score = team.role.inner.value;
957                BigSummary{winner: score, loser: 0}
958            }
959
960            pub fn read_team_winner_direct() {
961                let team = TeamMini{role: RoleMini{inner: Inner{value: 9}, hp: 1}};
962                make_big_with_team(team).winner
963            }
964
965            pub fn read_team_winner_bound() {
966                let team = TeamMini{role: RoleMini{inner: Inner{value: 9}, hp: 1}};
967                let summary = make_big_with_team(team);
968                summary.winner
969            }
970            "#
971            .to_vec(),
972        )?;
973
974        let compiled = vm.get_fn("vm_nested_struct_return_field::read_team_winner_direct", &[])?;
975        assert_eq!(compiled.ret_ty(), &Type::I64);
976        let direct: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
977        assert_eq!(direct(), 9);
978
979        let compiled = vm.get_fn("vm_nested_struct_return_field::read_team_winner_bound", &[])?;
980        assert_eq!(compiled.ret_ty(), &Type::I64);
981        let bound: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
982        assert_eq!(bound(), 9);
983        Ok(())
984    }
985
986    #[test]
987    fn returned_nested_struct_dynamic_fields_are_read_inline() -> anyhow::Result<()> {
988        let vm = Vm::with_all()?;
989        vm.import_code(
990            "vm_returned_nested_struct_dynamic",
991            br#"
992            pub struct Inner {
993                value: i64,
994            }
995
996            pub struct Outer {
997                inner: Inner,
998                tag: i64,
999            }
1000
1001            pub fn make() {
1002                Outer{inner: Inner{value: 17}, tag: 3}
1003            }
1004            "#
1005            .to_vec(),
1006        )?;
1007
1008        let compiled = vm.get_fn("vm_returned_nested_struct_dynamic::make", &[])?;
1009        let make: extern "C" fn() -> *const u8 = unsafe { std::mem::transmute(compiled.ptr()) };
1010        let ty = compiled.ret_ty().clone();
1011        let value = Dynamic::struct_view(make() as usize, ty);
1012        let inner = value.get_dynamic("inner").expect("inner field");
1013        assert_eq!(inner.get_dynamic("value").and_then(|value| value.as_int()), Some(17));
1014        assert_eq!(value.get_dynamic("tag").and_then(|value| value.as_int()), Some(3));
1015        Ok(())
1016    }
1017
1018    #[test]
1019    fn returned_struct_with_dynamic_field_survives_scope_exit() -> anyhow::Result<()> {
1020        let vm = Vm::with_all()?;
1021        vm.import_code(
1022            "vm_returned_struct_dynamic_field",
1023            br#"
1024            pub struct Bag {
1025                name: string,
1026                value: string,
1027            }
1028
1029            pub fn make() {
1030                Bag{name: "alpha", value: "omega"}
1031            }
1032            "#
1033            .to_vec(),
1034        )?;
1035
1036        let compiled = vm.get_fn("vm_returned_struct_dynamic_field::make", &[])?;
1037        let make: extern "C" fn() -> *const u8 = unsafe { std::mem::transmute(compiled.ptr()) };
1038        let value = Dynamic::struct_view(make() as usize, compiled.ret_ty().clone());
1039        assert_eq!(value.get_dynamic("name").map(|value| value.as_str().to_string()), Some("alpha".to_string()));
1040        assert_eq!(value.get_dynamic("value").map(|value| value.as_str().to_string()), Some("omega".to_string()));
1041        Ok(())
1042    }
1043
1044    #[test]
1045    fn any_push_does_not_consume_reused_value() -> anyhow::Result<()> {
1046        let vm = Vm::with_all()?;
1047        vm.import_code(
1048            "vm_any_push_reused_value",
1049            br#"
1050            pub fn run() {
1051                let role_id = "acct_role_2";
1052                let updated = [];
1053                updated.push(role_id);
1054                {
1055                    ok: true,
1056                    user_id: role_id,
1057                    first: updated.get_idx(0)
1058                }
1059            }
1060            "#
1061            .to_vec(),
1062        )?;
1063
1064        let compiled = vm.get_fn("vm_any_push_reused_value::run", &[])?;
1065        assert_eq!(compiled.ret_ty(), &Type::Any);
1066        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1067        let result = unsafe { &*run() };
1068        assert_eq!(result.get_dynamic("ok").and_then(|value| value.as_bool()), Some(true));
1069        assert_eq!(result.get_dynamic("user_id").map(|value| value.as_str().to_string()), Some("acct_role_2".to_string()));
1070        assert_eq!(result.get_dynamic("first").map(|value| value.as_str().to_string()), Some("acct_role_2".to_string()));
1071        Ok(())
1072    }
1073
1074    #[test]
1075    fn inlined_function_returning_dynamic_list_keeps_list_value() -> anyhow::Result<()> {
1076        let vm = Vm::with_all()?;
1077        vm.import_code(
1078            "vm_inline_return_list",
1079            br#"
1080            fn make(value) {
1081                [value]
1082            }
1083
1084            pub fn run() {
1085                let tup = make("node");
1086                tup[0i64]
1087            }
1088            "#
1089            .to_vec(),
1090        )?;
1091
1092        let compiled = vm.get_fn("vm_inline_return_list::run", &[])?;
1093        assert_eq!(compiled.ret_ty(), &Type::Any);
1094        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1095        let result = unsafe { &*run() };
1096        assert_eq!(result.as_str(), "node");
1097        Ok(())
1098    }
1099
1100    #[test]
1101    fn tuple_destructure_evaluates_rhs_once() -> anyhow::Result<()> {
1102        let vm = Vm::with_all()?;
1103        vm.import_code(
1104            "vm_tuple_destructure_once",
1105            br#"
1106            fn make_pair() {
1107                let n = root::get("local/vm_tuple_destructure_once/calls") + 1i64;
1108                root::add("local/vm_tuple_destructure_once/calls", n);
1109                (n, n + 10i64)
1110            }
1111
1112            pub fn run() {
1113                root::add("local/vm_tuple_destructure_once/calls", 0i64);
1114                let (a, b) = make_pair();
1115                a * 100i64 + b * 10i64 + root::get("local/vm_tuple_destructure_once/calls")
1116            }
1117            "#
1118            .to_vec(),
1119        )?;
1120
1121        let compiled = vm.get_fn("vm_tuple_destructure_once::run", &[])?;
1122        assert_eq!(compiled.ret_ty(), &Type::Any);
1123        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1124        let result = unsafe { &*run() };
1125        assert_eq!(result.as_int(), Some(211));
1126        Ok(())
1127    }
1128
1129    #[test]
1130    fn list_destructure_does_not_pop_rhs() -> anyhow::Result<()> {
1131        let vm = Vm::with_all()?;
1132        vm.import_code(
1133            "vm_list_destructure_no_pop",
1134            br#"
1135            pub fn run() {
1136                let values = [1i64, 2i64];
1137                let [x, y] = values;
1138                x * 100i64 + y * 10i64 + values.len()
1139            }
1140            "#
1141            .to_vec(),
1142        )?;
1143
1144        let compiled = vm.get_fn("vm_list_destructure_no_pop::run", &[])?;
1145        assert_eq!(compiled.ret_ty(), &Type::Any);
1146        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1147        let result = unsafe { &*run() };
1148        assert_eq!(result.as_int(), Some(122));
1149        Ok(())
1150    }
1151
1152    #[test]
1153    fn tuple_and_list_patterns_reject_each_other() -> anyhow::Result<()> {
1154        let vm = Vm::with_all()?;
1155        let tuple_from_list = vm
1156            .import_code(
1157                "vm_tuple_pattern_rejects_list",
1158                br#"
1159                pub fn run() {
1160                    let (x, y) = [1i64, 2i64];
1161                    x + y
1162                }
1163                "#
1164                .to_vec(),
1165            )
1166            .expect_err("tuple pattern should reject list RHS");
1167        assert!(tuple_from_list.to_string().contains("元组模式"));
1168
1169        let list_from_tuple = vm
1170            .import_code(
1171                "vm_list_pattern_rejects_tuple",
1172                br#"
1173                pub fn run() {
1174                    let [x, y] = (1i64, 2i64);
1175                    x + y
1176                }
1177                "#
1178                .to_vec(),
1179            )
1180            .expect_err("list pattern should reject tuple RHS");
1181        assert!(list_from_tuple.to_string().contains("列表模式"));
1182
1183        let empty_list_from_unit = vm
1184            .import_code(
1185                "vm_empty_list_pattern_rejects_unit",
1186                br#"
1187                pub fn run() {
1188                    let [] = ();
1189                    1i64
1190                }
1191                "#
1192                .to_vec(),
1193            )
1194            .expect_err("list pattern should reject unit tuple RHS");
1195        assert!(empty_list_from_unit.to_string().contains("列表模式"));
1196        Ok(())
1197    }
1198
1199    #[test]
1200    fn negate_narrow_integers() -> anyhow::Result<()> {
1201        let vm = Vm::with_all()?;
1202        vm.import_code(
1203            "vm_neg_narrow",
1204            br#"
1205            pub fn neg_i8(a: i8) { -a }
1206            pub fn neg_i16(a: i16) { -a }
1207            "#
1208            .to_vec(),
1209        )?;
1210
1211        let neg_i8 = vm.get_fn("vm_neg_narrow::neg_i8", &[Type::I8])?;
1212        assert_eq!(neg_i8.ret_ty(), &Type::I8);
1213        let neg_i8: extern "C" fn(i8) -> i8 = unsafe { std::mem::transmute(neg_i8.ptr()) };
1214        assert_eq!(neg_i8(5), -5);
1215        assert_eq!(neg_i8(-7), 7);
1216
1217        let neg_i16 = vm.get_fn("vm_neg_narrow::neg_i16", &[Type::I16])?;
1218        assert_eq!(neg_i16.ret_ty(), &Type::I16);
1219        let neg_i16: extern "C" fn(i16) -> i16 = unsafe { std::mem::transmute(neg_i16.ptr()) };
1220        assert_eq!(neg_i16(5), -5);
1221        assert_eq!(neg_i16(-300), 300);
1222        Ok(())
1223    }
1224
1225    #[test]
1226    fn integer_divide_by_zero_does_not_crash() -> anyhow::Result<()> {
1227        let vm = Vm::with_all()?;
1228        vm.import_code(
1229            "vm_div_by_zero",
1230            br#"
1231            pub fn divz(a: i64, b: i64) { a / b }
1232            pub fn modz(a: i64, b: i64) { a % b }
1233            pub fn overflow(a: i64, b: i64) { a / b }
1234            "#
1235            .to_vec(),
1236        )?;
1237
1238        let divz = vm.get_fn("vm_div_by_zero::divz", &[Type::I64, Type::I64])?;
1239        let modz = vm.get_fn("vm_div_by_zero::modz", &[Type::I64, Type::I64])?;
1240        let overflow = vm.get_fn("vm_div_by_zero::overflow", &[Type::I64, Type::I64])?;
1241        let divz: extern "C" fn(i64, i64) -> i64 = unsafe { std::mem::transmute(divz.ptr()) };
1242        let modz: extern "C" fn(i64, i64) -> i64 = unsafe { std::mem::transmute(modz.ptr()) };
1243        let overflow: extern "C" fn(i64, i64) -> i64 = unsafe { std::mem::transmute(overflow.ptr()) };
1244
1245        // 正常路径不受守卫影响
1246        let _ = dynamic::take_fault();
1247        assert_eq!(divz(7, 2), 3);
1248        assert_eq!(modz(7, 2), 1);
1249        assert!(dynamic::take_fault().is_none());
1250
1251        // 除零:返回 0 且置 fault,而不是 trap 杀进程
1252        assert_eq!(divz(7, 0), 0);
1253        assert!(dynamic::take_fault().is_some());
1254        assert_eq!(modz(7, 0), 0);
1255        assert!(dynamic::take_fault().is_some());
1256
1257        // INT_MIN / -1 溢出同样被守卫
1258        assert_eq!(overflow(i64::MIN, -1), 0);
1259        assert!(dynamic::take_fault().is_some());
1260        Ok(())
1261    }
1262
1263    #[test]
1264    fn constant_divide_by_zero_does_not_crash() -> anyhow::Result<()> {
1265        let vm = Vm::with_all()?;
1266        vm.import_code(
1267            "vm_const_div_zero",
1268            br#"
1269            pub fn divz(a: i64) { a / 0 }
1270            pub fn modz(a: i64) { a % 0 }
1271            pub fn divc(a: i64) { a / 7 }
1272            "#
1273            .to_vec(),
1274        )?;
1275        let divz: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(vm.get_fn("vm_const_div_zero::divz", &[Type::I64])?.ptr()) };
1276        let modz: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(vm.get_fn("vm_const_div_zero::modz", &[Type::I64])?.ptr()) };
1277        let divc: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(vm.get_fn("vm_const_div_zero::divc", &[Type::I64])?.ptr()) };
1278
1279        let _ = dynamic::take_fault();
1280        // 常量除零:编译期判定 → 返回 0 + 置 fault,不 trap
1281        assert_eq!(divz(42), 0);
1282        assert!(dynamic::take_fault().is_some());
1283        assert_eq!(modz(42), 0);
1284        assert!(dynamic::take_fault().is_some());
1285        // 非零常量除数:正常计算,不置 fault(走无守卫快路径)
1286        assert_eq!(divc(42), 6);
1287        assert!(dynamic::take_fault().is_none());
1288        Ok(())
1289    }
1290
1291    #[test]
1292    fn dynamic_divide_by_zero_returns_null() -> anyhow::Result<()> {
1293        let vm = Vm::with_all()?;
1294        vm.import_code(
1295            "vm_any_div_by_zero",
1296            br#"
1297            pub fn divz(a, b) { a / b }
1298            "#
1299            .to_vec(),
1300        )?;
1301
1302        let divz = vm.get_fn("vm_any_div_by_zero::divz", &[Type::Any, Type::Any])?;
1303        let divz: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(divz.ptr()) };
1304        let a = Dynamic::from(7i64);
1305        let zero = Dynamic::from(0i64);
1306        let _ = dynamic::take_fault();
1307        let result = unsafe { &*divz(&a, &zero) };
1308        assert!(result.is_null());
1309        assert!(dynamic::take_fault().is_some());
1310        Ok(())
1311    }
1312
1313    #[test]
1314    fn compares_any_with_string_literal_as_string() -> anyhow::Result<()> {
1315        let vm = Vm::with_all()?;
1316        vm.import_code(
1317            "vm_string_compare_any",
1318            br#"
1319            pub fn any_ne_empty(chat_path) {
1320                chat_path != ""
1321            }
1322            "#
1323            .to_vec(),
1324        )?;
1325
1326        let compiled = vm.get_fn("vm_string_compare_any::any_ne_empty", &[Type::Any])?;
1327        assert_eq!(compiled.ret_ty(), &Type::Bool);
1328
1329        let any_ne_empty: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1330        let empty = Dynamic::from("");
1331        let non_empty = Dynamic::from("chat");
1332
1333        assert!(!any_ne_empty(&empty));
1334        assert!(any_ne_empty(&non_empty));
1335        Ok(())
1336    }
1337
1338    #[test]
1339    fn compares_bool_values_and_bool_literals() -> anyhow::Result<()> {
1340        let vm = Vm::with_all()?;
1341        vm.import_code(
1342            "vm_bool_compare",
1343            br#"
1344            pub fn eq_true(value: bool) {
1345                value == true
1346            }
1347
1348            pub fn ne_false(value: bool) {
1349                value != false
1350            }
1351
1352            pub fn literal_left(value: bool) {
1353                true == value
1354            }
1355
1356            pub fn eq_pair(left: bool, right: bool) {
1357                left == right
1358            }
1359
1360            pub fn logic_pair(left: bool, right: bool) {
1361                (left && right) || (left == true && right != false)
1362            }
1363            "#
1364            .to_vec(),
1365        )?;
1366
1367        let compiled = vm.get_fn("vm_bool_compare::eq_true", &[Type::Bool])?;
1368        assert_eq!(compiled.ret_ty(), &Type::Bool);
1369        let eq_true: extern "C" fn(bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1370        assert!(eq_true(true));
1371        assert!(!eq_true(false));
1372
1373        let compiled = vm.get_fn("vm_bool_compare::ne_false", &[Type::Bool])?;
1374        assert_eq!(compiled.ret_ty(), &Type::Bool);
1375        let ne_false: extern "C" fn(bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1376        assert!(ne_false(true));
1377        assert!(!ne_false(false));
1378
1379        let compiled = vm.get_fn("vm_bool_compare::literal_left", &[Type::Bool])?;
1380        assert_eq!(compiled.ret_ty(), &Type::Bool);
1381        let literal_left: extern "C" fn(bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1382        assert!(literal_left(true));
1383        assert!(!literal_left(false));
1384
1385        let compiled = vm.get_fn("vm_bool_compare::eq_pair", &[Type::Bool, Type::Bool])?;
1386        assert_eq!(compiled.ret_ty(), &Type::Bool);
1387        let eq_pair: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1388        assert!(eq_pair(true, true));
1389        assert!(eq_pair(false, false));
1390        assert!(!eq_pair(true, false));
1391        assert!(!eq_pair(false, true));
1392
1393        let compiled = vm.get_fn("vm_bool_compare::logic_pair", &[Type::Bool, Type::Bool])?;
1394        assert_eq!(compiled.ret_ty(), &Type::Bool);
1395        let logic_pair: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1396        assert!(logic_pair(true, true));
1397        assert!(!logic_pair(true, false));
1398        assert!(!logic_pair(false, true));
1399        assert!(!logic_pair(false, false));
1400        Ok(())
1401    }
1402
1403    #[test]
1404    fn parenthesized_expression_can_call_any_method() -> anyhow::Result<()> {
1405        let vm = Vm::with_all()?;
1406        vm.import_code(
1407            "vm_parenthesized_method_call",
1408            br#"
1409            pub fn run(value) {
1410                (value + 2).to_i64()
1411            }
1412            "#
1413            .to_vec(),
1414        )?;
1415
1416        let compiled = vm.get_fn("vm_parenthesized_method_call::run", &[Type::Any])?;
1417        assert_eq!(compiled.ret_ty(), &Type::I64);
1418        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1419        let value = Dynamic::from(40i64);
1420
1421        assert_eq!(run(&value), 42);
1422        Ok(())
1423    }
1424
1425    #[test]
1426    fn casts_any_float_to_i32_without_zeroing() -> anyhow::Result<()> {
1427        let vm = Vm::with_all()?;
1428        vm.import_code(
1429            "vm_any_float_to_i32",
1430            br#"
1431            pub fn direct(value) {
1432                value as i32
1433            }
1434
1435            pub fn map_field(value) {
1436                let field = value.v;
1437                field as i32
1438            }
1439
1440            pub fn damage(attacker, def_rate) {
1441                let x = attacker.atk * (1.0 - def_rate);
1442                x as i32
1443            }
1444            "#
1445            .to_vec(),
1446        )?;
1447
1448        let compiled = vm.get_fn("vm_any_float_to_i32::direct", &[Type::Any])?;
1449        assert_eq!(compiled.ret_ty(), &Type::I32);
1450        let direct: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
1451        let value = Dynamic::from(9.5f64);
1452        assert_eq!(direct(&value), 9);
1453
1454        let compiled = vm.get_fn("vm_any_float_to_i32::map_field", &[Type::Any])?;
1455        assert_eq!(compiled.ret_ty(), &Type::I32);
1456        let map_field: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
1457        let value = dynamic::map!("v"=> 9.5f64);
1458        assert_eq!(map_field(&value), 9);
1459
1460        let compiled = vm.get_fn("vm_any_float_to_i32::damage", &[Type::Any, Type::Any])?;
1461        assert_eq!(compiled.ret_ty(), &Type::I32);
1462        let damage: extern "C" fn(*const Dynamic, *const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
1463        let attacker = dynamic::map!("atk"=> 64i64);
1464        let def_rate = Dynamic::from(0.17f64);
1465        assert_eq!(damage(&attacker, &def_rate), 53);
1466        Ok(())
1467    }
1468
1469    #[test]
1470    fn binary_imm_promotes_integer_literals_for_float_left_values() -> anyhow::Result<()> {
1471        let vm = Vm::with_all()?;
1472        vm.import_code(
1473            "vm_float_binary_imm",
1474            br#"
1475            pub fn add_f32(value: f32) {
1476                value + 1i32
1477            }
1478
1479            pub fn sub_f32(value: f32) {
1480                value - 1i32
1481            }
1482
1483            pub fn mul_f32(value: f32) {
1484                value * 2i32
1485            }
1486
1487            pub fn div_f32(value: f32) {
1488                value / 2i32
1489            }
1490
1491            pub fn gt_f32(value: f32) {
1492                value > 2i32
1493            }
1494            "#
1495            .to_vec(),
1496        )?;
1497
1498        let compiled = vm.get_fn("vm_float_binary_imm::add_f32", &[Type::F32])?;
1499        assert_eq!(compiled.ret_ty(), &Type::F32);
1500        let add_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
1501        assert_eq!(add_f32(2.5), 3.5);
1502
1503        let compiled = vm.get_fn("vm_float_binary_imm::sub_f32", &[Type::F32])?;
1504        assert_eq!(compiled.ret_ty(), &Type::F32);
1505        let sub_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
1506        assert_eq!(sub_f32(2.5), 1.5);
1507
1508        let compiled = vm.get_fn("vm_float_binary_imm::mul_f32", &[Type::F32])?;
1509        assert_eq!(compiled.ret_ty(), &Type::F32);
1510        let mul_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
1511        assert_eq!(mul_f32(2.5), 5.0);
1512
1513        let compiled = vm.get_fn("vm_float_binary_imm::div_f32", &[Type::F32])?;
1514        assert_eq!(compiled.ret_ty(), &Type::F32);
1515        let div_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
1516        assert_eq!(div_f32(5.0), 2.5);
1517
1518        let compiled = vm.get_fn("vm_float_binary_imm::gt_f32", &[Type::F32])?;
1519        assert_eq!(compiled.ret_ty(), &Type::Bool);
1520        let gt_f32: extern "C" fn(f32) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1521        assert!(gt_f32(2.5));
1522        assert!(!gt_f32(1.5));
1523        Ok(())
1524    }
1525
1526    #[test]
1527    fn any_keys_returns_map_keys_and_empty_list_for_other_values() -> anyhow::Result<()> {
1528        let vm = Vm::with_all()?;
1529        vm.import_code(
1530            "vm_any_keys",
1531            br#"
1532            pub fn map_keys(value) {
1533                let keys = value.keys();
1534                keys.len() == 2 && keys.contains("alpha") && keys.contains("beta")
1535            }
1536
1537            pub fn non_map_keys(value) {
1538                value.keys().len() == 0
1539            }
1540            "#
1541            .to_vec(),
1542        )?;
1543
1544        let compiled = vm.get_fn("vm_any_keys::map_keys", &[Type::Any])?;
1545        assert_eq!(compiled.ret_ty(), &Type::Bool);
1546        let map_keys: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1547        let value = dynamic::map!("alpha"=> 1i64, "beta"=> 2i64);
1548        assert!(map_keys(&value));
1549
1550        let compiled = vm.get_fn("vm_any_keys::non_map_keys", &[Type::Any])?;
1551        assert_eq!(compiled.ret_ty(), &Type::Bool);
1552        let non_map_keys: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1553        let value = Dynamic::from("alpha");
1554        assert!(non_map_keys(&value));
1555        Ok(())
1556    }
1557
1558    #[test]
1559    fn const_list_contains_uses_any_list_method() -> anyhow::Result<()> {
1560        let vm = Vm::with_all()?;
1561        vm.import_code(
1562            "vm_const_list_contains",
1563            br#"
1564            const IMAGE_EXTS = ["png", "jpg", "webp"];
1565
1566            pub fn is_supported(ext: string) {
1567                IMAGE_EXTS.contains(ext)
1568            }
1569            "#
1570            .to_vec(),
1571        )?;
1572
1573        let compiled = vm.get_fn("vm_const_list_contains::is_supported", &[Type::Str])?;
1574        assert_eq!(compiled.ret_ty(), &Type::Bool);
1575        let is_supported: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1576        assert!(is_supported(&Dynamic::from("png")));
1577        assert!(is_supported(&Dynamic::from("webp")));
1578        assert!(!is_supported(&Dynamic::from("gif")));
1579        Ok(())
1580    }
1581
1582    #[test]
1583    fn any_logic_comparisons_use_bool_abi() -> anyhow::Result<()> {
1584        let vm = Vm::with_all()?;
1585        vm.import_code(
1586            "vm_any_logic_abi",
1587            br#"
1588            pub fn ne_empty(value) {
1589                value != ""
1590            }
1591
1592            pub fn eq_empty(value) {
1593                value == ""
1594            }
1595
1596            pub fn less_than_ten(value) {
1597                value < 10
1598            }
1599
1600            pub fn contains_key(value) {
1601                value.contains("alpha") == true
1602            }
1603            "#
1604            .to_vec(),
1605        )?;
1606
1607        let compiled = vm.get_fn("vm_any_logic_abi::ne_empty", &[Type::Any])?;
1608        assert_eq!(compiled.ret_ty(), &Type::Bool);
1609        let ne_empty: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1610        assert!(ne_empty(&Dynamic::from("x")));
1611        assert!(!ne_empty(&Dynamic::from("")));
1612
1613        let compiled = vm.get_fn("vm_any_logic_abi::eq_empty", &[Type::Any])?;
1614        assert_eq!(compiled.ret_ty(), &Type::Bool);
1615        let eq_empty: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1616        assert!(eq_empty(&Dynamic::from("")));
1617        assert!(!eq_empty(&Dynamic::from("x")));
1618
1619        let compiled = vm.get_fn("vm_any_logic_abi::less_than_ten", &[Type::Any])?;
1620        assert_eq!(compiled.ret_ty(), &Type::Bool);
1621        let less_than_ten: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1622        assert!(less_than_ten(&Dynamic::from(4i64)));
1623        assert!(!less_than_ten(&Dynamic::from(14i64)));
1624
1625        let compiled = vm.get_fn("vm_any_logic_abi::contains_key", &[Type::Any])?;
1626        assert_eq!(compiled.ret_ty(), &Type::Bool);
1627        let contains_key: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1628        assert!(contains_key(&dynamic::map!("alpha"=> 1i64)));
1629        assert!(!contains_key(&dynamic::map!("beta"=> 1i64)));
1630        Ok(())
1631    }
1632
1633    #[test]
1634    fn string_methods_work_on_static_string_and_any_string_values() -> anyhow::Result<()> {
1635        let vm = Vm::with_all()?;
1636        vm.import_code(
1637            "vm_string_methods",
1638            br#"
1639            pub fn static_string_methods(text: string) {
1640                let parts = text.split(",");
1641                text.starts_with("alpha")
1642                    && text.ends_with("beta")
1643                    && text.is_string()
1644                    && !text.is_null()
1645                    && parts.len() == 2
1646                    && parts.get_idx(0) == "alpha"
1647                    && parts.get_idx(1) == "beta"
1648            }
1649
1650            pub fn any_string_methods(value) {
1651                let parts = value.split(",");
1652                value.starts_with("alpha")
1653                    && value.ends_with("beta")
1654                    && value.is_string()
1655                    && !value.is_null()
1656                    && parts.len() == 2
1657                    && parts.get_idx(0) == "alpha"
1658                    && parts.get_idx(1) == "beta"
1659            }
1660
1661            pub fn any_null_methods(value) {
1662                value.is_null() && !value.is_string()
1663            }
1664            "#
1665            .to_vec(),
1666        )?;
1667
1668        let compiled = vm.get_fn("vm_string_methods::static_string_methods", &[Type::Str])?;
1669        assert_eq!(compiled.ret_ty(), &Type::Bool);
1670        let static_string_methods: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1671        let text = Dynamic::from("alpha,beta");
1672        assert!(static_string_methods(&text));
1673
1674        let compiled = vm.get_fn("vm_string_methods::any_string_methods", &[Type::Any])?;
1675        assert_eq!(compiled.ret_ty(), &Type::Bool);
1676        let any_string_methods: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1677        assert!(any_string_methods(&text));
1678
1679        let compiled = vm.get_fn("vm_string_methods::any_null_methods", &[Type::Any])?;
1680        assert_eq!(compiled.ret_ty(), &Type::Bool);
1681        let any_null_methods: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1682        let value = Dynamic::Null;
1683        assert!(any_null_methods(&value));
1684        Ok(())
1685    }
1686
1687    #[test]
1688    fn static_string_add_uses_direct_strcat() -> anyhow::Result<()> {
1689        let vm = Vm::with_all()?;
1690        vm.import_code(
1691            "vm_static_strcat",
1692            br#"
1693            pub fn join(left: string, right: string) {
1694                left + right
1695            }
1696
1697            pub fn suffix(left: string) {
1698                left + "-tail"
1699            }
1700
1701            pub fn append_local() {
1702                let text: string = "alpha";
1703                text += "-beta";
1704                text += "-tail";
1705                text
1706            }
1707
1708            pub fn append_local_assign() {
1709                let text: string = "alpha";
1710                text = text + "-beta";
1711                text = text + "-tail";
1712                text
1713            }
1714
1715            pub fn append_arg(text: string) {
1716                text += "-tail";
1717                text
1718            }
1719
1720            pub fn append_arg_assign(text: string) {
1721                text = text + "-tail";
1722                text
1723            }
1724
1725            pub fn append_any(value) {
1726                value += "-tail";
1727                value
1728            }
1729
1730            pub fn add_sub_assign_form() {
1731                let x = 10i64;
1732                x = x + 1i64;
1733                x = x - 2i64;
1734                x
1735            }
1736            "#
1737            .to_vec(),
1738        )?;
1739
1740        let compiled = vm.get_fn("vm_static_strcat::join", &[Type::Str, Type::Str])?;
1741        assert_eq!(compiled.ret_ty(), &Type::Str);
1742        let join: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1743        let left = Dynamic::from("alpha");
1744        let right = Dynamic::from("-beta");
1745        let result = unsafe { &*join(&left, &right) };
1746        assert!(matches!(result, Dynamic::StringBuf(_)));
1747        assert_eq!(result.as_str(), "alpha-beta");
1748
1749        let compiled = vm.get_fn("vm_static_strcat::suffix", &[Type::Str])?;
1750        assert_eq!(compiled.ret_ty(), &Type::Str);
1751        let suffix: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1752        let result = unsafe { &*suffix(&left) };
1753        assert!(matches!(result, Dynamic::StringBuf(_)));
1754        assert_eq!(result.as_str(), "alpha-tail");
1755
1756        let compiled = vm.get_fn("vm_static_strcat::append_local", &[])?;
1757        assert_eq!(compiled.ret_ty(), &Type::Str);
1758        let append_local: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1759        let result = unsafe { &*append_local() };
1760        assert!(matches!(result, Dynamic::StringBuf(_)));
1761        assert_eq!(result.as_str(), "alpha-beta-tail");
1762
1763        let compiled = vm.get_fn("vm_static_strcat::append_local_assign", &[])?;
1764        assert_eq!(compiled.ret_ty(), &Type::Str);
1765        let append_local_assign: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1766        let result = unsafe { &*append_local_assign() };
1767        assert!(matches!(result, Dynamic::StringBuf(_)));
1768        assert_eq!(result.as_str(), "alpha-beta-tail");
1769
1770        let compiled = vm.get_fn("vm_static_strcat::append_arg", &[Type::Str])?;
1771        assert_eq!(compiled.ret_ty(), &Type::Str);
1772        let append_arg: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1773        let input = Dynamic::from("alpha");
1774        let result = unsafe { &*append_arg(&input) };
1775        assert_eq!(result.as_str(), "alpha-tail");
1776        assert_eq!(input.as_str(), "alpha");
1777
1778        let compiled = vm.get_fn("vm_static_strcat::append_arg_assign", &[Type::Str])?;
1779        assert_eq!(compiled.ret_ty(), &Type::Str);
1780        let append_arg_assign: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1781        let input = Dynamic::from("alpha");
1782        let result = unsafe { &*append_arg_assign(&input) };
1783        assert_eq!(result.as_str(), "alpha-tail");
1784        assert_eq!(input.as_str(), "alpha");
1785
1786        let compiled = vm.get_fn("vm_static_strcat::append_any", &[Type::Any])?;
1787        assert_eq!(compiled.ret_ty(), &Type::Str);
1788        let append_any: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1789        let input = Dynamic::from("alpha");
1790        let result = unsafe { &*append_any(&input) };
1791        assert_eq!(result.as_str(), "alpha-tail");
1792        assert_eq!(input.as_str(), "alpha");
1793
1794        let compiled = vm.get_fn("vm_static_strcat::add_sub_assign_form", &[])?;
1795        assert_eq!(compiled.ret_ty(), &Type::I64);
1796        let add_sub_assign_form: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1797        assert_eq!(add_sub_assign_form(), 9);
1798        Ok(())
1799    }
1800
1801    #[test]
1802    fn primitive_type_check_methods_call_any_runtime() -> anyhow::Result<()> {
1803        let vm = Vm::with_all()?;
1804        vm.import_code(
1805            "vm_primitive_type_check_methods",
1806            br#"
1807            pub fn int_checks() {
1808                !42i64.is_list()
1809                    && !42i64.is_map()
1810                    && !42i64.is_string()
1811                    && !42i64.is_null()
1812            }
1813
1814            pub fn bool_checks() {
1815                !true.is_list() && !true.is_map() && !true.is_null()
1816            }
1817            "#
1818            .to_vec(),
1819        )?;
1820
1821        let compiled = vm.get_fn("vm_primitive_type_check_methods::int_checks", &[])?;
1822        assert_eq!(compiled.ret_ty(), &Type::Bool);
1823        let int_checks: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1824        assert!(int_checks());
1825
1826        let compiled = vm.get_fn("vm_primitive_type_check_methods::bool_checks", &[])?;
1827        assert_eq!(compiled.ret_ty(), &Type::Bool);
1828        let bool_checks: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1829        assert!(bool_checks());
1830        Ok(())
1831    }
1832
1833    #[test]
1834    fn for_loop_iterates_any_list_and_map_values() -> anyhow::Result<()> {
1835        let vm = Vm::with_all()?;
1836        vm.import_code(
1837            "vm_for_any_collections",
1838            br#"
1839            pub fn list_sum(items) {
1840                let total = 0i64;
1841                for item in items {
1842                    total += item;
1843                }
1844                total
1845            }
1846
1847            pub fn map_sum(data) {
1848                let total = 0i64;
1849                for (key, value) in data {
1850                    total += value;
1851                }
1852                total
1853            }
1854            "#
1855            .to_vec(),
1856        )?;
1857
1858        let compiled = vm.get_fn("vm_for_any_collections::list_sum", &[Type::Any])?;
1859        assert_eq!(compiled.ret_ty(), &Type::I64);
1860        let list_sum: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1861        let items = Dynamic::list(vec![1i64.into(), 2i64.into(), 3i64.into()]);
1862        assert_eq!(list_sum(&items), 6);
1863
1864        let compiled = vm.get_fn("vm_for_any_collections::map_sum", &[Type::Any])?;
1865        assert_eq!(compiled.ret_ty(), &Type::I64);
1866        let map_sum: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1867        let data = dynamic::map!("a"=> 4i64, "b"=> 5i64);
1868        assert_eq!(map_sum(&data), 9);
1869        Ok(())
1870    }
1871
1872    #[test]
1873    fn compares_concrete_value_with_string_literal_as_string() -> anyhow::Result<()> {
1874        let vm = Vm::with_all()?;
1875        vm.import_code(
1876            "vm_string_compare_imm",
1877            br#"
1878            pub fn int_eq_str(value: i64) {
1879                value == "42"
1880            }
1881
1882            pub fn int_to_str(value: i64) {
1883                value + ""
1884            }
1885            "#
1886            .to_vec(),
1887        )?;
1888
1889        let compiled = vm.get_fn("vm_string_compare_imm::int_eq_str", &[Type::I64])?;
1890        assert_eq!(compiled.ret_ty(), &Type::Bool);
1891
1892        let int_eq_str: extern "C" fn(i64) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1893
1894        let compiled = vm.get_fn("vm_string_compare_imm::int_to_str", &[Type::I64])?;
1895        assert_eq!(compiled.ret_ty(), &Type::Str);
1896        let int_to_str: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1897        let text = int_to_str(42);
1898        assert_eq!(unsafe { &*text }.as_str(), "42");
1899
1900        assert!(int_eq_str(42));
1901        assert!(!int_eq_str(7));
1902        Ok(())
1903    }
1904
1905    #[test]
1906    fn concatenates_string_with_integer_values() -> anyhow::Result<()> {
1907        let vm = Vm::with_all()?;
1908        vm.import_code(
1909            "vm_string_concat_integer",
1910            br#"
1911            pub fn idx_key(idx: i64) {
1912                "" + idx
1913            }
1914
1915            pub fn level_text(level: i64) {
1916                "" + level + " level"
1917            }
1918
1919            pub fn gold_text(currency) {
1920                "" + currency.gold
1921            }
1922            "#
1923            .to_vec(),
1924        )?;
1925
1926        let compiled = vm.get_fn("vm_string_concat_integer::idx_key", &[Type::I64])?;
1927        let idx_key: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1928        let result = unsafe { &*idx_key(7) };
1929        assert!(matches!(result, Dynamic::StringBuf(_)));
1930        assert_eq!(result.as_str(), "7");
1931
1932        let compiled = vm.get_fn("vm_string_concat_integer::level_text", &[Type::I64])?;
1933        let level_text: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1934        let result = unsafe { &*level_text(12) };
1935        assert_eq!(result.as_str(), "12 level");
1936
1937        let compiled = vm.get_fn("vm_string_concat_integer::gold_text", &[Type::Any])?;
1938        let gold_text: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1939        let currency = dynamic::map!("gold"=> 345i64);
1940        let result = unsafe { &*gold_text(&currency) };
1941        assert_eq!(result.as_str(), "345");
1942        Ok(())
1943    }
1944
1945    #[test]
1946    fn coerces_string_concat_to_i64_without_unimplemented_log() -> anyhow::Result<()> {
1947        let vm = Vm::with_all()?;
1948        vm.import_code(
1949            "vm_string_concat_to_i64",
1950            br#"
1951            pub fn run(idx: i64) {
1952                ("" + idx) as i64
1953            }
1954            "#
1955            .to_vec(),
1956        )?;
1957
1958        let compiled = vm.get_fn("vm_string_concat_to_i64::run", &[Type::I64])?;
1959        assert_eq!(compiled.ret_ty(), &Type::I64);
1960        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1961        assert_eq!(run(7), 7);
1962        Ok(())
1963    }
1964
1965    #[test]
1966    fn casts_dynamic_string_numbers_to_ints_and_floats() -> anyhow::Result<()> {
1967        let vm = Vm::with_all()?;
1968        vm.import_code(
1969            "vm_string_number_casts",
1970            br#"
1971            pub fn limit_i64(req) {
1972                req["@query"].limit as i64
1973            }
1974
1975            pub fn limit_i32(req) {
1976                req["@query"].limit as i32
1977            }
1978
1979            pub fn price_f64(req) {
1980                req["@query"].price as f64
1981            }
1982
1983            pub fn price_f32(req) {
1984                req["@query"].price as f32
1985            }
1986
1987            pub fn literal_i64() {
1988                "42" as i64
1989            }
1990
1991            pub fn literal_f64() {
1992                "3.5" as f64
1993            }
1994
1995            pub fn bad_number(req) {
1996                req["@query"].bad as i64
1997            }
1998            "#
1999            .to_vec(),
2000        )?;
2001
2002        let req = dynamic::map!("@query"=> dynamic::map!("limit"=> "50", "price"=> "3.5", "bad"=> "nope"));
2003
2004        let limit_i64 = vm.get_fn("vm_string_number_casts::limit_i64", &[Type::Any])?;
2005        assert_eq!(limit_i64.ret_ty(), &Type::I64);
2006        let limit_i64: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(limit_i64.ptr()) };
2007        assert_eq!(limit_i64(&req), 50);
2008
2009        let limit_i32 = vm.get_fn("vm_string_number_casts::limit_i32", &[Type::Any])?;
2010        assert_eq!(limit_i32.ret_ty(), &Type::I32);
2011        let limit_i32: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(limit_i32.ptr()) };
2012        assert_eq!(limit_i32(&req), 50);
2013
2014        let price_f64 = vm.get_fn("vm_string_number_casts::price_f64", &[Type::Any])?;
2015        assert_eq!(price_f64.ret_ty(), &Type::F64);
2016        let price_f64: extern "C" fn(*const Dynamic) -> f64 = unsafe { std::mem::transmute(price_f64.ptr()) };
2017        assert_eq!(price_f64(&req), 3.5);
2018
2019        let price_f32 = vm.get_fn("vm_string_number_casts::price_f32", &[Type::Any])?;
2020        assert_eq!(price_f32.ret_ty(), &Type::F32);
2021        let price_f32: extern "C" fn(*const Dynamic) -> f32 = unsafe { std::mem::transmute(price_f32.ptr()) };
2022        assert_eq!(price_f32(&req), 3.5);
2023
2024        let literal_i64 = vm.get_fn("vm_string_number_casts::literal_i64", &[])?;
2025        assert_eq!(literal_i64.ret_ty(), &Type::I64);
2026        let literal_i64: extern "C" fn() -> i64 = unsafe { std::mem::transmute(literal_i64.ptr()) };
2027        assert_eq!(literal_i64(), 42);
2028
2029        let literal_f64 = vm.get_fn("vm_string_number_casts::literal_f64", &[])?;
2030        assert_eq!(literal_f64.ret_ty(), &Type::F64);
2031        let literal_f64: extern "C" fn() -> f64 = unsafe { std::mem::transmute(literal_f64.ptr()) };
2032        assert_eq!(literal_f64(), 3.5);
2033
2034        let bad_number = vm.get_fn("vm_string_number_casts::bad_number", &[Type::Any])?;
2035        assert_eq!(bad_number.ret_ty(), &Type::I64);
2036        let bad_number: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(bad_number.ptr()) };
2037        assert_eq!(bad_number(&req), 0);
2038        Ok(())
2039    }
2040
2041    #[test]
2042    fn unifies_explicit_return_and_tail_integer_widths() -> anyhow::Result<()> {
2043        let vm = Vm::with_all()?;
2044        vm.import_code(
2045            "vm_return_integer_widths",
2046            br#"
2047            pub fn selected(flag, slot) {
2048                if flag {
2049                    return slot;
2050                }
2051                0
2052            }
2053            "#
2054            .to_vec(),
2055        )?;
2056
2057        let compiled = vm.get_fn("vm_return_integer_widths::selected", &[Type::Bool, Type::I64])?;
2058        assert_eq!(compiled.ret_ty(), &Type::I64);
2059        let selected: extern "C" fn(bool, i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2060
2061        assert_eq!(selected(true, 7), 7);
2062        assert_eq!(selected(false, 7), 0);
2063        Ok(())
2064    }
2065
2066    #[test]
2067    fn root_contains_string_concat_is_bool_condition() -> anyhow::Result<()> {
2068        let vm = Vm::with_all()?;
2069        vm.import_code(
2070            "vm_root_contains_condition",
2071            br#"
2072            pub fn exists(user_id) {
2073                if root::contains("redis/user/" + user_id) {
2074                    return 1;
2075                }
2076                0
2077            }
2078            "#
2079            .to_vec(),
2080        )?;
2081
2082        assert_eq!(vm.infer("root::contains", &[Type::Any])?, Type::Bool);
2083        let compiled = vm.get_fn("vm_root_contains_condition::exists", &[Type::Any])?;
2084        assert_eq!(compiled.ret_ty(), &Type::I64);
2085        Ok(())
2086    }
2087
2088    #[test]
2089    fn root_add_map_can_be_printed() -> anyhow::Result<()> {
2090        let vm = Vm::with_all()?;
2091        assert_eq!(vm.infer("root::add_map", &[Type::Any])?, Type::Bool);
2092        vm.import_code(
2093            "vm_root_add_map_print",
2094            br#"
2095            pub fn run() {
2096                print(root::add_map("local/world_handlers/til_map_novicevillage"));
2097            }
2098            "#
2099            .to_vec(),
2100        )?;
2101
2102        let compiled = vm.get_fn("vm_root_add_map_print::run", &[])?;
2103        assert!(compiled.ret_ty().is_void());
2104        Ok(())
2105    }
2106
2107    #[test]
2108    fn root_keys_returns_map_key_list() -> anyhow::Result<()> {
2109        let vm = Vm::with_all()?;
2110        assert_eq!(vm.infer("root::keys", &[Type::Any])?, Type::Any);
2111        vm.import_code(
2112            "vm_root_keys",
2113            br#"
2114            pub fn run() {
2115                root::add_map("local/test/vm_root_keys");
2116                root::insert("local/test/vm_root_keys", "0", "zero");
2117                root::insert("local/test/vm_root_keys", "1", "one");
2118                root::keys("local/test/vm_root_keys").len()
2119            }
2120            "#
2121            .to_vec(),
2122        )?;
2123
2124        let compiled = vm.get_fn("vm_root_keys::run", &[])?;
2125        assert_eq!(compiled.ret_ty(), &Type::I32);
2126        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2127        assert_eq!(run(), 2);
2128        Ok(())
2129    }
2130
2131    #[test]
2132    fn root_mount_fjall_accepts_mount_name() -> anyhow::Result<()> {
2133        let vm = Vm::with_all()?;
2134        assert_eq!(vm.infer("root::mount_fjall", &[Type::Any, Type::Any])?, Type::Void);
2135        vm.import_code(
2136            "vm_root_mount_fjall_named",
2137            br#"
2138            pub fn run(name, data_dir) {
2139                root::mount_fjall(name, data_dir);
2140            }
2141            "#
2142            .to_vec(),
2143        )?;
2144
2145        let compiled = vm.get_fn("vm_root_mount_fjall_named::run", &[Type::Any, Type::Any])?;
2146        assert!(compiled.ret_ty().is_void());
2147        Ok(())
2148    }
2149
2150    #[test]
2151    fn std_log_accepts_any_and_returns_void() -> anyhow::Result<()> {
2152        let vm = Vm::with_all()?;
2153        vm.import_code(
2154            "vm_std_log",
2155            br#"
2156            pub fn run(value) {
2157                log({ ok: true, value: value });
2158            }
2159            "#
2160            .to_vec(),
2161        )?;
2162
2163        let compiled = vm.get_fn("vm_std_log::run", &[Type::Any])?;
2164        assert!(compiled.ret_ty().is_void());
2165        let run: extern "C" fn(*const Dynamic) = unsafe { std::mem::transmute(compiled.ptr()) };
2166        let value = Dynamic::from(7i64);
2167        run(&value);
2168        Ok(())
2169    }
2170
2171    #[test]
2172    fn unary_not_any_loop_var_is_bool_condition() -> anyhow::Result<()> {
2173        let vm = Vm::with_all()?;
2174        vm.import_code(
2175            "vm_unary_not_any_loop_var",
2176            br#"
2177            pub fn count_missing(flags) {
2178                let missing = 0;
2179                for exists in flags {
2180                    if !exists {
2181                        missing = missing + 1;
2182                    }
2183                }
2184                missing
2185            }
2186            "#
2187            .to_vec(),
2188        )?;
2189
2190        let compiled = vm.get_fn("vm_unary_not_any_loop_var::count_missing", &[Type::Any])?;
2191        assert_eq!(compiled.ret_ty(), &Type::I64);
2192        Ok(())
2193    }
2194
2195    #[test]
2196    fn closure_literal_can_be_called_immediately() -> anyhow::Result<()> {
2197        let vm = Vm::with_all()?;
2198        vm.import_code(
2199            "vm_closure_immediate_call",
2200            br#"
2201            pub fn no_args() {
2202                let r = || { 1i32 }();
2203                r
2204            }
2205
2206            pub fn with_arg() {
2207                |value: i32| { value + 1i32 }(2i32)
2208            }
2209            "#
2210            .to_vec(),
2211        )?;
2212
2213        let compiled = vm.get_fn("vm_closure_immediate_call::no_args", &[])?;
2214        assert_eq!(compiled.ret_ty(), &Type::I32);
2215        let no_args: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2216        assert_eq!(no_args(), 1);
2217
2218        let compiled = vm.get_fn("vm_closure_immediate_call::with_arg", &[])?;
2219        assert_eq!(compiled.ret_ty(), &Type::I32);
2220        let with_arg: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2221        assert_eq!(with_arg(), 3);
2222        Ok(())
2223    }
2224
2225    #[test]
2226    fn returned_closure_can_be_called() -> anyhow::Result<()> {
2227        let vm = Vm::with_all()?;
2228        vm.import_code(
2229            "vm_returned_closure_call",
2230            br#"
2231            pub fn make_adder() {
2232                |value: i64| { value + 1i64 }
2233            }
2234
2235            pub fn make_offset_adder(offset: i64) {
2236                |value: i64| { value + offset }
2237            }
2238
2239            pub fn run() {
2240                make_adder()(41i64)
2241            }
2242
2243            pub fn run_captured() {
2244                make_offset_adder(2i64)(40i64)
2245            }
2246            "#
2247            .to_vec(),
2248        )?;
2249
2250        let compiled = vm.get_fn("vm_returned_closure_call::run", &[])?;
2251        assert_eq!(compiled.ret_ty(), &Type::Any);
2252        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2253        let result = unsafe { &*run() };
2254        assert_eq!(result.as_int(), Some(42));
2255
2256        let compiled = vm.get_fn("vm_returned_closure_call::run_captured", &[])?;
2257        assert_eq!(compiled.ret_ty(), &Type::Any);
2258        let run_captured: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2259        let result = unsafe { &*run_captured() };
2260        assert_eq!(result.as_int(), Some(42));
2261        Ok(())
2262    }
2263
2264    #[test]
2265    fn small_expression_calls_keep_direct_semantics() -> anyhow::Result<()> {
2266        let vm = Vm::with_all()?;
2267        vm.import_code(
2268            "vm_small_expression_inline",
2269            br#"
2270            pub fn add_i64(left: i64, right: i64) {
2271                left + right
2272            }
2273
2274            pub fn normal_caller() {
2275                add_i64(1i64, 2i64)
2276            }
2277
2278            pub fn closure_caller() {
2279                let add = |left: i64, right: i64| { left + right };
2280                add(add_i64(1i64, 2i64), 4i64)
2281            }
2282
2283            pub fn closure_assignment() {
2284                let acc = 0i64;
2285                let add = |left: i64, right: i64| { left + right };
2286                acc = add(acc, 4i64);
2287                acc
2288            }
2289            "#
2290            .to_vec(),
2291        )?;
2292
2293        let compiled = vm.get_fn("vm_small_expression_inline::normal_caller", &[])?;
2294        assert_eq!(compiled.ret_ty(), &Type::I64);
2295        let normal_caller: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2296        assert_eq!(normal_caller(), 3);
2297
2298        let compiled = vm.get_fn("vm_small_expression_inline::closure_caller", &[])?;
2299        assert_eq!(compiled.ret_ty(), &Type::Any);
2300        let closure_caller: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2301        let result = unsafe { &*closure_caller() };
2302        assert_eq!(result.as_int(), Some(7));
2303
2304        let compiled = vm.get_fn("vm_small_expression_inline::closure_assignment", &[])?;
2305        assert_eq!(compiled.ret_ty(), &Type::I64);
2306        let closure_assignment: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2307        assert_eq!(closure_assignment(), 4);
2308        Ok(())
2309    }
2310
2311    #[test]
2312    fn nested_closure_captures_outer_closure_arg() -> anyhow::Result<()> {
2313        let vm = Vm::with_all()?;
2314        vm.import_code(
2315            "vm_nested_closure_capture",
2316            br#"
2317            pub fn run() {
2318                let reference_label = "reference";
2319                |path: string| {
2320                    let upload_done = |uploaded: bool| {
2321                        if uploaded {
2322                            reference_label + ":" + path
2323                        } else {
2324                            "missing"
2325                        }
2326                    };
2327                    upload_done(true)
2328                }("reference.png")
2329            }
2330            "#
2331            .to_vec(),
2332        )?;
2333
2334        let compiled = vm.get_fn("vm_nested_closure_capture::run", &[])?;
2335        assert_eq!(compiled.ret_ty(), &Type::Any);
2336        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2337        let result = unsafe { &*run() };
2338        assert_eq!(result.as_str(), "reference:reference.png");
2339        Ok(())
2340    }
2341
2342    #[test]
2343    fn semicolon_tail_call_makes_function_void() -> anyhow::Result<()> {
2344        let vm = Vm::with_all()?;
2345        vm.import_code(
2346            "vm_semicolon_tail_void",
2347            br#"
2348            pub fn send_role_select(idx, account_id, selected_slot) {
2349                root::send("local/ui/send_dialog", {
2350                    idx: idx,
2351                    account_id: account_id,
2352                    selected_slot: selected_slot
2353                });
2354            }
2355            "#
2356            .to_vec(),
2357        )?;
2358
2359        let compiled = vm.get_fn("vm_semicolon_tail_void::send_role_select", &[Type::Any, Type::Any, Type::Any])?;
2360        assert_eq!(compiled.ret_ty(), &Type::Void);
2361        Ok(())
2362    }
2363
2364    #[test]
2365    fn bare_return_conflicts_with_non_void_return() -> anyhow::Result<()> {
2366        let vm = Vm::with_all()?;
2367        vm.import_code(
2368            "vm_bare_return_conflict",
2369            br#"
2370            pub fn run(flag) {
2371                if flag {
2372                    return;
2373                }
2374                1
2375            }
2376            "#
2377            .to_vec(),
2378        )?;
2379
2380        let err = match vm.get_fn("vm_bare_return_conflict::run", &[Type::Bool]) {
2381            Ok(_) => panic!("expected mismatched return types to fail"),
2382            Err(err) => err,
2383        };
2384        assert!(format!("{err:#}").contains("返回类型不一致"));
2385        Ok(())
2386    }
2387
2388    #[test]
2389    fn root_get_accepts_string_concat_with_dynamic_field() -> anyhow::Result<()> {
2390        let vm = Vm::with_all()?;
2391        vm.import_code(
2392            "vm_root_get_dynamic_concat",
2393            br#"
2394            pub fn get_action(req) {
2395                root::get("local/game/panel_actions/" + req.idx)
2396            }
2397            "#
2398            .to_vec(),
2399        )?;
2400
2401        root::add("local/game/panel_actions/7", dynamic::map!("id"=> "action-7").into())?;
2402        let compiled = vm.get_fn("vm_root_get_dynamic_concat::get_action", &[Type::Any])?;
2403        assert_eq!(compiled.ret_ty(), &Type::Any);
2404        let get_action: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2405        let req = dynamic::map!("idx"=> 7i64);
2406        let result = unsafe { &*get_action(&req) };
2407
2408        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("action-7".to_string()));
2409        Ok(())
2410    }
2411
2412    #[test]
2413    fn root_add_fn_registers_handler_with_dynamic_field_path_concat() -> anyhow::Result<()> {
2414        let vm = Vm::with_all()?;
2415        vm.import_code(
2416            "vm_registered_panel_action",
2417            br#"
2418            pub fn panel_action(req) {
2419                root::get("local/game/panel_actions/" + req.idx)
2420            }
2421
2422            pub fn register() {
2423                root::add_fn("local/ui/panel_action", "vm_registered_panel_action::panel_action")
2424            }
2425            "#
2426            .to_vec(),
2427        )?;
2428
2429        let compiled = vm.get_fn("vm_registered_panel_action::register", &[])?;
2430        assert_eq!(compiled.ret_ty(), &Type::Bool);
2431        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2432        assert!(register());
2433        Ok(())
2434    }
2435
2436    #[test]
2437    fn std_spawn_runs_named_function_with_tuple_args() -> anyhow::Result<()> {
2438        let zero_path = "local/vm_std_spawn/zero";
2439        let sum_path = "local/vm_std_spawn/sum";
2440        let closure_path = "local/vm_std_spawn/closure";
2441        let closure_vars_path = "local/vm_std_spawn/closure_vars";
2442        let _ = root::remove(zero_path);
2443        let _ = root::remove(sum_path);
2444        let _ = root::remove(closure_path);
2445        let _ = root::remove(closure_vars_path);
2446        let vm = Vm::with_all()?;
2447        vm.import_code(
2448            "vm_std_spawn",
2449            br#"
2450            pub fn zero() {
2451                root::add("local/vm_std_spawn/zero", 1);
2452            }
2453
2454            pub fn job(left, right) {
2455                root::add("local/vm_std_spawn/sum", left + right);
2456            }
2457
2458            pub fn start_zero() {
2459                spawn("vm_std_spawn::zero", ())
2460            }
2461
2462            pub fn start_sum() {
2463                spawn("vm_std_spawn::job", (10, 20))
2464            }
2465
2466            pub fn start_closure() {
2467                spawn(|x, y| {
2468                    root::add("local/vm_std_spawn/closure", x + y);
2469                }, (3, 4))
2470            }
2471
2472            pub fn start_closure_vars() {
2473                let x = 5;
2474                let y = 6;
2475                spawn(|left, right| {
2476                    root::add("local/vm_std_spawn/closure_vars", left + right);
2477                }, (x, y))
2478            }
2479            "#
2480            .to_vec(),
2481        )?;
2482
2483        let compiled = vm.get_fn("vm_std_spawn::start_zero", &[])?;
2484        assert_eq!(compiled.ret_ty(), &Type::Bool);
2485        let start_zero: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2486        assert!(start_zero());
2487
2488        let compiled = vm.get_fn("vm_std_spawn::start_sum", &[])?;
2489        assert_eq!(compiled.ret_ty(), &Type::Bool);
2490        let start_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2491        assert!(start_sum());
2492
2493        let compiled = vm.get_fn("vm_std_spawn::start_closure", &[])?;
2494        assert_eq!(compiled.ret_ty(), &Type::Bool);
2495        let start_closure: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2496        assert!(start_closure());
2497
2498        let compiled = vm.get_fn("vm_std_spawn::start_closure_vars", &[])?;
2499        assert_eq!(compiled.ret_ty(), &Type::Bool);
2500        let start_closure_vars: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2501        assert!(start_closure_vars());
2502
2503        for _ in 0..50 {
2504            let zero_done = root::get(zero_path).ok().and_then(|value| value.as_int()) == Some(1);
2505            let sum_done = root::get(sum_path).ok().and_then(|value| value.as_int()) == Some(30);
2506            let closure_done = root::get(closure_path).ok().and_then(|value| value.as_int()) == Some(7);
2507            let closure_vars_done = root::get(closure_vars_path).ok().and_then(|value| value.as_int()) == Some(11);
2508            if zero_done && sum_done && closure_done && closure_vars_done {
2509                return Ok(());
2510            }
2511            std::thread::sleep(std::time::Duration::from_millis(10));
2512        }
2513
2514        anyhow::bail!("spawned jobs did not write expected results");
2515    }
2516
2517    #[test]
2518    fn native_can_save_and_later_call_closure_callback() -> anyhow::Result<()> {
2519        static SAVED_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2520
2521        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2522            if callback.is_null() {
2523                return false;
2524            }
2525            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2526                return false;
2527            };
2528            *SAVED_CALLBACK.lock() = Some(callback);
2529            true
2530        }
2531
2532        let path = "local/vm_callback/result";
2533        let _ = root::remove(path);
2534        *SAVED_CALLBACK.lock() = None;
2535
2536        let vm = Vm::with_all()?;
2537        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2538        vm.import_code(
2539            "vm_callback",
2540            br#"
2541            pub fn register() {
2542                let n = 41;
2543                callback_test::save(|| {
2544                    root::add("local/vm_callback/result", n + 1);
2545                    true
2546                })
2547            }
2548            "#
2549            .to_vec(),
2550        )?;
2551
2552        let compiled = vm.get_fn("vm_callback::register", &[])?;
2553        assert_eq!(compiled.ret_ty(), &Type::Bool);
2554        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2555        assert!(register());
2556        assert!(root::get(path).is_err());
2557
2558        let callback = SAVED_CALLBACK.lock().clone().expect("callback should be saved");
2559        let result = callback.call0()?;
2560        assert_eq!(result.as_bool(), Some(true));
2561        assert_eq!(root::get(path)?.as_int(), Some(42));
2562        Ok(())
2563    }
2564
2565    #[test]
2566    fn closure_captures_share_state_between_callbacks() -> anyhow::Result<()> {
2567        static SAVED_CALLBACKS: parking_lot::Mutex<Vec<ZustCallback>> = parking_lot::Mutex::new(Vec::new());
2568
2569        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2570            if callback.is_null() {
2571                return false;
2572            }
2573            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2574                return false;
2575            };
2576            SAVED_CALLBACKS.lock().push(callback);
2577            true
2578        }
2579
2580        SAVED_CALLBACKS.lock().clear();
2581
2582        let vm = Vm::with_all()?;
2583        vm.add_native_module_ptr("capture_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2584        vm.import_code(
2585            "vm_shared_capture",
2586            br#"
2587            pub fn register() {
2588                let state = {};
2589                state.drag_kind = 0;
2590                capture_test::save(|| {
2591                    state.drag_kind = 2;
2592                    true
2593                });
2594                capture_test::save(|| {
2595                    state.drag_kind
2596                })
2597            }
2598            "#
2599            .to_vec(),
2600        )?;
2601
2602        let register = vm.get_fn("vm_shared_capture::register", &[])?;
2603        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2604        assert!(register());
2605
2606        let (writer, reader) = {
2607            let saved = SAVED_CALLBACKS.lock();
2608            assert_eq!(saved.len(), 2);
2609            (saved[0].clone(), saved[1].clone())
2610        };
2611        assert_eq!(reader.call0()?.as_int(), Some(0));
2612        assert_eq!(writer.call0()?.as_bool(), Some(true));
2613        assert_eq!(reader.call0()?.as_int(), Some(2));
2614        Ok(())
2615    }
2616
2617    #[test]
2618    fn native_can_save_and_later_call_named_function_callback() -> anyhow::Result<()> {
2619        static SAVED_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2620
2621        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2622            if callback.is_null() {
2623                return false;
2624            }
2625            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2626                return false;
2627            };
2628            *SAVED_CALLBACK.lock() = Some(callback);
2629            true
2630        }
2631
2632        let path = "local/vm_named_callback/result";
2633        let _ = root::remove(path);
2634        *SAVED_CALLBACK.lock() = None;
2635
2636        let vm = Vm::with_all()?;
2637        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2638        vm.import_code(
2639            "vm_named_callback",
2640            br#"
2641            pub fn on_result() {
2642                root::add("local/vm_named_callback/result", "done");
2643                true
2644            }
2645
2646            pub fn register() {
2647                callback_test::save(on_result)
2648            }
2649            "#
2650            .to_vec(),
2651        )?;
2652
2653        let register = vm.get_fn("vm_named_callback::register", &[])?;
2654        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2655        assert!(register());
2656        assert!(root::get(path).is_err());
2657
2658        let callback = SAVED_CALLBACK.lock().clone().expect("callback should be saved");
2659        assert_eq!(callback.call1(dynamic::map!("text"=> "done"))?.as_bool(), Some(true));
2660        assert_eq!(root::get(path)?.as_str(), "done");
2661        Ok(())
2662    }
2663
2664    #[test]
2665    fn native_callback_can_receive_later_dynamic_args() -> anyhow::Result<()> {
2666        static SAVED_PATH_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2667        static SAVED_SUM_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2668
2669        extern "C" fn save_path_callback(callback: *const Dynamic) -> bool {
2670            if callback.is_null() {
2671                return false;
2672            }
2673            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2674                return false;
2675            };
2676            *SAVED_PATH_CALLBACK.lock() = Some(callback);
2677            true
2678        }
2679
2680        extern "C" fn save_sum_callback(callback: *const Dynamic) -> bool {
2681            if callback.is_null() {
2682                return false;
2683            }
2684            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2685                return false;
2686            };
2687            *SAVED_SUM_CALLBACK.lock() = Some(callback);
2688            true
2689        }
2690
2691        let path_result = "local/vm_callback/path";
2692        let sum_result = "local/vm_callback/sum8";
2693        let _ = root::remove(path_result);
2694        let _ = root::remove(sum_result);
2695        *SAVED_PATH_CALLBACK.lock() = None;
2696        *SAVED_SUM_CALLBACK.lock() = None;
2697
2698        let vm = Vm::with_all()?;
2699        vm.add_native_module_ptr("callback_test", "save_path", &[Type::Any], Type::Bool, save_path_callback as *const u8)?;
2700        vm.add_native_module_ptr("callback_test", "save_sum", &[Type::Any], Type::Bool, save_sum_callback as *const u8)?;
2701        vm.import_code(
2702            "vm_callback_args",
2703            br#"
2704            pub fn register_path() {
2705                let key = "local/vm_callback/path";
2706                callback_test::save_path(|path| {
2707                    root::add(key, path);
2708                    true
2709                })
2710            }
2711
2712            pub fn register_sum() {
2713                callback_test::save_sum(|a, b, c, d, e, f, g, h| {
2714                    root::add("local/vm_callback/sum8", a + b + c + d + e + f + g + h);
2715                    true
2716                })
2717            }
2718            "#
2719            .to_vec(),
2720        )?;
2721
2722        let register_path = vm.get_fn("vm_callback_args::register_path", &[])?;
2723        let register_path: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_path.ptr()) };
2724        assert!(register_path());
2725
2726        let register_sum = vm.get_fn("vm_callback_args::register_sum", &[])?;
2727        let register_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_sum.ptr()) };
2728        assert!(register_sum());
2729
2730        let path_callback = SAVED_PATH_CALLBACK.lock().clone().expect("path callback should be saved");
2731        assert_eq!(path_callback.call1(Dynamic::from("picked.txt"))?.as_bool(), Some(true));
2732        assert_eq!(root::get(path_result)?.as_str(), "picked.txt");
2733
2734        let sum_callback = SAVED_SUM_CALLBACK.lock().clone().expect("sum callback should be saved");
2735        let sum_args = (1i64..=8).map(Dynamic::from).collect();
2736        assert_eq!(sum_callback.call(sum_args)?.as_bool(), Some(true));
2737        assert_eq!(root::get(sum_result)?.as_int(), Some(36));
2738        Ok(())
2739    }
2740
2741    #[test]
2742    fn callback_with_16_explicit_args_and_captures() -> anyhow::Result<()> {
2743        static SAVED_SUM16: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2744
2745        extern "C" fn save_sum16(callback: *const Dynamic) -> bool {
2746            if callback.is_null() {
2747                return false;
2748            }
2749            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2750                return false;
2751            };
2752            *SAVED_SUM16.lock() = Some(callback);
2753            true
2754        }
2755
2756        let sum16_path = "local/vm_callback/sum16";
2757        let _ = root::remove(sum16_path);
2758        *SAVED_SUM16.lock() = None;
2759
2760        let vm = Vm::with_all()?;
2761        vm.add_native_module_ptr("callback_test", "save_sum16", &[Type::Any], Type::Bool, save_sum16 as *const u8)?;
2762        vm.import_code(
2763            "vm_callback_16_args",
2764            br#"
2765            pub fn register_sum16() {
2766                let prefix = "sum=";
2767                callback_test::save_sum16(|a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p| {
2768                    let total = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p;
2769                    root::add("local/vm_callback/sum16", prefix + total);
2770                    true
2771                })
2772            }
2773            "#
2774            .to_vec(),
2775        )?;
2776
2777        let register = vm.get_fn("vm_callback_16_args::register_sum16", &[])?;
2778        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2779        assert!(register());
2780
2781        let callback = SAVED_SUM16.lock().clone().expect("sum16 callback saved");
2782        let args: Vec<Dynamic> = (1i64..=16).map(Dynamic::from).collect();
2783        assert_eq!(callback.call(args)?.as_bool(), Some(true));
2784        assert_eq!(root::get(sum16_path)?.as_str(), "sum=136");
2785        Ok(())
2786    }
2787
2788    #[test]
2789    fn spawn_closure_with_16_args() -> anyhow::Result<()> {
2790        let spawn16_path = "local/vm_spawn/spawn16";
2791        let _ = root::remove(spawn16_path);
2792
2793        let vm = Vm::with_all()?;
2794        vm.import_code(
2795            "vm_spawn_16_args",
2796            br#"
2797            pub fn start_spawn16() {
2798                spawn(|a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p| {
2799                    root::add("local/vm_spawn/spawn16", a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p);
2800                }, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
2801            }
2802            "#
2803            .to_vec(),
2804        )?;
2805
2806        let compiled = vm.get_fn("vm_spawn_16_args::start_spawn16", &[])?;
2807        assert_eq!(compiled.ret_ty(), &Type::Bool);
2808        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2809        assert!(start());
2810
2811        for _ in 0..50 {
2812            if root::get(spawn16_path).ok().and_then(|v| v.as_int()) == Some(136) {
2813                return Ok(());
2814            }
2815            std::thread::sleep(std::time::Duration::from_millis(10));
2816        }
2817        anyhow::bail!("spawned job did not write expected result");
2818    }
2819
2820    #[test]
2821    fn spawn_native_closure_avoids_any_boxing() -> anyhow::Result<()> {
2822        let nat_path = "local/vm_spawn_native/result";
2823        let _ = root::remove(nat_path);
2824        let vm = Vm::with_all()?;
2825        vm.import_code(
2826            "vm_spawn_native",
2827            br#"
2828            pub fn start() {
2829                spawn(|x: i64, y: i64| {
2830                    root::add("local/vm_spawn_native/result", x + y);
2831                }, (10i64, 20i64))
2832            }
2833            "#
2834            .to_vec(),
2835        )?;
2836        let compiled = vm.get_fn("vm_spawn_native::start", &[])?;
2837        assert_eq!(compiled.ret_ty(), &Type::Bool);
2838        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2839        assert!(start());
2840        for _ in 0..50 {
2841            if root::get(nat_path).ok().and_then(|v| v.as_int()) == Some(30) {
2842                return Ok(());
2843            }
2844            std::thread::sleep(std::time::Duration::from_millis(10));
2845        }
2846        anyhow::bail!("spawned native closure did not write expected result");
2847    }
2848
2849    #[test]
2850    fn multi_level_nested_closure_captures() -> anyhow::Result<()> {
2851        let vm = Vm::with_all()?;
2852        vm.import_code(
2853            "vm_multi_level_captures",
2854            br#"
2855            pub fn run() {
2856                let level1 = "L1";
2857                let level2 = "L2";
2858                |path: string| {
2859                    let level3 = "L3";
2860                    let inner = |suffix: string| {
2861                        let level4 = "L4";
2862                        |flag: bool| {
2863                            if flag {
2864                                level1 + "." + level2 + "." + level3 + "." + level4 + "." + path + suffix
2865                            } else {
2866                                "off"
2867                            }
2868                        }(true)
2869                    };
2870                    inner(".ext")
2871                }("file.txt")
2872            }
2873            "#
2874            .to_vec(),
2875        )?;
2876
2877        let compiled = vm.get_fn("vm_multi_level_captures::run", &[])?;
2878        assert_eq!(compiled.ret_ty(), &Type::Any);
2879        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2880        let result = unsafe { &*run() };
2881        assert_eq!(result.as_str(), "L1.L2.L3.L4.file.txt.ext");
2882        Ok(())
2883    }
2884
2885    #[test]
2886    fn root_add_fn_accepts_string_concat_in_registered_handler() -> anyhow::Result<()> {
2887        let vm = Vm::with_all()?;
2888        vm.import_code(
2889            "vm_registered_string_concat",
2890            br#"
2891            pub fn send_panel(idx: i64) {
2892                let idx_key = "" + idx;
2893                idx_key
2894            }
2895            "#
2896            .to_vec(),
2897        )?;
2898
2899        assert!(vm.get_fn_ptr("vm_registered_string_concat::send_panel", &[Type::Any]).is_ok());
2900        Ok(())
2901    }
2902
2903    #[test]
2904    fn dynamic_method_error_reports_source_location() -> anyhow::Result<()> {
2905        let vm = Vm::with_all()?;
2906        vm.import_code(
2907            "vm_bad_dynamic_method",
2908            br#"
2909            pub fn main(value) {
2910                let out = "";
2911                out = out + value.fetch("name");
2912            }
2913            "#
2914            .to_vec(),
2915        )?;
2916
2917        let err = vm.get_fn_ptr("vm_bad_dynamic_method::main", &[Type::Any]).expect_err("bad dynamic method should fail to compile");
2918        let msg = format!("{err:#}");
2919        assert!(msg.contains("vm_bad_dynamic_method:4:"), "{msg}");
2920        assert!(msg.contains("`Any.fetch` 不是成员函数"), "{msg}");
2921        assert!(msg.contains(r#"out = out + value.fetch("name");"#), "{msg}");
2922        Ok(())
2923    }
2924
2925    #[test]
2926    fn root_send_idx_returns_handler_value() -> anyhow::Result<()> {
2927        fn echo_handler(msg: Dynamic) -> Dynamic {
2928            dynamic::map!("type"=> "echo", "id"=> msg.get_dynamic("id").unwrap_or(Dynamic::Null))
2929        }
2930
2931        let vm = Vm::with_all()?;
2932        vm.import_code(
2933            "vm_root_send_idx_return",
2934            br#"
2935            pub fn call(req) {
2936                root::send_idx("local/send_idx_return_handlers", 0, req)
2937            }
2938            "#
2939            .to_vec(),
2940        )?;
2941
2942        root::add_list("local/send_idx_return_handlers")?;
2943        let (mount, name) = root::get_mount("local/send_idx_return_handlers")?;
2944        mount.push(name, root::Object::Native(echo_handler))?;
2945
2946        assert_eq!(vm.infer("root::send_idx", &[Type::Any, Type::I64, Type::Any])?, Type::Any);
2947        let compiled = vm.get_fn("vm_root_send_idx_return::call", &[Type::Any])?;
2948        assert_eq!(compiled.ret_ty(), &Type::Any);
2949        let call: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2950        let req = dynamic::map!("id"=> 42i64);
2951        let result = unsafe { &*call(&req) };
2952
2953        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("echo".to_string()));
2954        assert_eq!(result.get_dynamic("id").and_then(|value| value.as_int()), Some(42));
2955        Ok(())
2956    }
2957
2958    #[test]
2959    fn compiles_public_hotspots_with_string_paths_and_keys() -> anyhow::Result<()> {
2960        let vm = Vm::with_all()?;
2961        vm.import_code(
2962            "vm_public_hotspots",
2963            br#"
2964            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
2965                {
2966                    path: action_map_path,
2967                    panel_id: panel_id,
2968                    action_id: action_id,
2969                    id: hotspot.id
2970                }
2971            }
2972
2973            pub fn public_hotspots(idx, panel_id, hotspots) {
2974                let idx_key = "" + idx;
2975                let action_map_path = "local/game/panel_actions/" + idx_key;
2976
2977                let existing_action_map = root::get(action_map_path);
2978                if !existing_action_map.is_map() {
2979                    root::add_map(action_map_path);
2980                }
2981
2982                if hotspots.is_map() {
2983                    let public_items = {};
2984                    for action_id in hotspots.keys() {
2985                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
2986                    }
2987                    return public_items;
2988                }
2989
2990                let public_items = [];
2991                let i = 0;
2992                while i < hotspots.len() {
2993                    let hotspot = hotspots.get_idx(i);
2994                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
2995                    public_items.push(item);
2996                    i = i + 1;
2997                }
2998
2999                public_items
3000            }
3001            "#
3002            .to_vec(),
3003        )?;
3004
3005        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::I64, Type::Any, Type::Any]).is_ok());
3006        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::Any, Type::Any, Type::Any]).is_ok());
3007        Ok(())
3008    }
3009
3010    #[test]
3011    fn send_panel_calls_public_hotspots_with_dynamic_request() -> anyhow::Result<()> {
3012        let vm = Vm::with_all()?;
3013        vm.import_code(
3014            "vm_send_panel_public_hotspots",
3015            br#"
3016            pub fn ok(value) {
3017                value
3018            }
3019
3020            pub fn panel_from_node(req) {
3021                {
3022                    panel_id: req.panel_id,
3023                    hotspots: req.hotspots
3024                }
3025            }
3026
3027            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
3028                {
3029                    path: action_map_path,
3030                    panel_id: panel_id,
3031                    action_id: action_id,
3032                    id: hotspot.id
3033                }
3034            }
3035
3036            pub fn public_hotspots(idx, panel_id, hotspots) {
3037                let idx_key = "" + idx;
3038                let action_map_path = "local/game/panel_actions/" + idx_key;
3039
3040                let existing_action_map = root::get(action_map_path);
3041                if !existing_action_map.is_map() {
3042                    root::add_map(action_map_path);
3043                }
3044
3045                if hotspots.is_map() {
3046                    let public_items = {};
3047                    for action_id in hotspots.keys() {
3048                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
3049                    }
3050                    return public_items;
3051                }
3052
3053                let public_items = [];
3054                let i = 0;
3055                while i < hotspots.len() {
3056                    let hotspot = hotspots.get_idx(i);
3057                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
3058                    public_items.push(item);
3059                    i = i + 1;
3060                }
3061
3062                public_items
3063            }
3064
3065            pub fn send_panel(req) {
3066                let panel = req.panel;
3067                if !panel.is_map() {
3068                    panel = panel_from_node(req);
3069                }
3070                if !panel.is_map() {
3071                    return ok({
3072                        id: 4,
3073                        type: "panel_rejected",
3074                        reason: "invalid panel"
3075                    });
3076                }
3077                panel.id = 4;
3078                panel.idx = req.idx;
3079                if !panel.contains("type") {
3080                    panel.type = "panel";
3081                }
3082                if panel.contains("hotspots") {
3083                    panel.hotspots = public_hotspots(req.idx, panel.panel_id, panel.hotspots);
3084                }
3085                root::send_idx("local/ws", req.idx, panel);
3086                ok({
3087                    id: 4,
3088                    type: "panel",
3089                    panel_id: panel.panel_id
3090                })
3091            }
3092            "#
3093            .to_vec(),
3094        )?;
3095
3096        let compiled = vm.get_fn("vm_send_panel_public_hotspots::send_panel", &[Type::Any])?;
3097        assert_eq!(compiled.ret_ty(), &Type::Any);
3098        let send_panel: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3099        let req = dynamic::map!(
3100            "idx"=> 7i64,
3101            "panel"=> dynamic::map!(
3102                "panel_id"=> "main",
3103                "hotspots"=> dynamic::map!(
3104                    "open"=> dynamic::map!("id"=> "open")
3105                )
3106            )
3107        );
3108        let result = unsafe { &*send_panel(&req) };
3109
3110        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("panel".to_string()));
3111        assert_eq!(result.get_dynamic("panel_id").map(|value| value.as_str().to_string()), Some("main".to_string()));
3112        Ok(())
3113    }
3114
3115    #[test]
3116    fn map_assignment_accepts_string_concat_key() -> anyhow::Result<()> {
3117        let vm = Vm::with_all()?;
3118        vm.import_code(
3119            "vm_string_concat_map_key",
3120            br##"
3121            pub fn write_action(action_map, panel_id, action_id, action) {
3122                action_map[panel_id + "#" + action_id] = action;
3123                action_map[panel_id + "#" + action_id]
3124            }
3125            "##
3126            .to_vec(),
3127        )?;
3128
3129        let compiled = vm.get_fn("vm_string_concat_map_key::write_action", &[Type::Any, Type::Any, Type::Any, Type::Any])?;
3130        let write_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3131        let action_map = dynamic::map!();
3132        let panel_id: Dynamic = "panel".into();
3133        let action_id: Dynamic = "open".into();
3134        let action = dynamic::map!("id"=> "open");
3135
3136        let result = unsafe { &*write_action(&action_map, &panel_id, &action_id, &action) };
3137
3138        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3139        assert_eq!(action_map.get_dynamic("panel#open").and_then(|value| value.get_dynamic("id")).map(|value| value.as_str().to_string()), Some("open".to_string()));
3140        Ok(())
3141    }
3142
3143    #[test]
3144    fn map_get_key_accepts_string_concat_key_variable() -> anyhow::Result<()> {
3145        let vm = Vm::with_all()?;
3146        vm.import_code(
3147            "vm_get_key_string_concat_key",
3148            br##"
3149            pub fn read_action(action_map, panel_id, action_id) {
3150                let action_key = panel_id + "#" + action_id;
3151                action_map.get_key(action_key)
3152            }
3153            "##
3154            .to_vec(),
3155        )?;
3156
3157        let compiled = vm.get_fn("vm_get_key_string_concat_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
3158        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3159        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3160        let panel_id: Dynamic = "panel".into();
3161        let action_id: Dynamic = "open".into();
3162
3163        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
3164
3165        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3166        Ok(())
3167    }
3168
3169    #[test]
3170    fn const_map_bracket_accepts_dynamic_string_key() -> anyhow::Result<()> {
3171        let vm = Vm::with_all()?;
3172        vm.import_code(
3173            "vm_const_map_dynamic_key",
3174            r#"
3175            const DIRECTION_LABELS = {left: "左", right: "右", up: "上", down: "下"};
3176
3177            pub fn label(direction) {
3178                DIRECTION_LABELS[direction]
3179            }
3180            "#
3181            .as_bytes()
3182            .to_vec(),
3183        )?;
3184
3185        let compiled = vm.get_fn("vm_const_map_dynamic_key::label", &[Type::Any])?;
3186        assert_eq!(compiled.ret_ty(), &Type::Any);
3187        let label: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3188        let direction: Dynamic = "left".into();
3189        let result = unsafe { &*label(&direction) };
3190        assert_eq!(result.as_str(), "左");
3191        Ok(())
3192    }
3193
3194    #[test]
3195    fn map_get_alias_matches_get_key() -> anyhow::Result<()> {
3196        let vm = Vm::with_all()?;
3197        vm.import_code(
3198            "vm_map_get_alias",
3199            br#"
3200            pub fn read_name(data) {
3201                data.get("name")
3202            }
3203
3204            pub fn read_missing(data) {
3205                data.get("missing")
3206            }
3207            "#
3208            .to_vec(),
3209        )?;
3210
3211        let data = dynamic::map!("name"=> "zust");
3212
3213        let compiled = vm.get_fn("vm_map_get_alias::read_name", &[Type::Any])?;
3214        assert_eq!(compiled.ret_ty(), &Type::Any);
3215        let read_name: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3216        let result = unsafe { &*read_name(&data) };
3217        assert_eq!(result.as_str(), "zust");
3218
3219        let compiled = vm.get_fn("vm_map_get_alias::read_missing", &[Type::Any])?;
3220        assert_eq!(compiled.ret_ty(), &Type::Any);
3221        let read_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3222        let result = unsafe { &*read_missing(&data) };
3223        assert!(result.is_null());
3224        Ok(())
3225    }
3226
3227    #[test]
3228    fn map_get_key_accepts_helper_string_key() -> anyhow::Result<()> {
3229        let vm = Vm::with_all()?;
3230        vm.import_code(
3231            "vm_get_key_helper_string_key",
3232            br##"
3233            pub fn make_action_key(panel_id, action_id) {
3234                panel_id + "#" + action_id
3235            }
3236
3237            pub fn read_action(action_map, panel_id, action_id) {
3238                let action_key = make_action_key(panel_id, action_id);
3239                let action = action_map.get_key(action_key);
3240                action
3241            }
3242            "##
3243            .to_vec(),
3244        )?;
3245
3246        let compiled = vm.get_fn("vm_get_key_helper_string_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
3247        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3248        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3249        let panel_id: Dynamic = "panel".into();
3250        let action_id: Dynamic = "open".into();
3251
3252        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
3253
3254        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3255        Ok(())
3256    }
3257
3258    #[test]
3259    fn map_del_key_removes_string_key_and_returns_removed_value() -> anyhow::Result<()> {
3260        let vm = Vm::with_all()?;
3261        vm.import_code(
3262            "vm_del_key_string_key",
3263            br##"
3264            pub fn remove_action(action_map, panel_id, action_id) {
3265                let action_key = panel_id + "#" + action_id;
3266                let removed = action_map.del_key(action_key);
3267                [removed, action_map.get_key(action_key)]
3268            }
3269            "##
3270            .to_vec(),
3271        )?;
3272
3273        let compiled = vm.get_fn("vm_del_key_string_key::remove_action", &[Type::Any, Type::Any, Type::Any])?;
3274        let remove_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3275        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3276        let panel_id: Dynamic = "panel".into();
3277        let action_id: Dynamic = "open".into();
3278
3279        let result = unsafe { &*remove_action(&action_map, &panel_id, &action_id) };
3280
3281        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("id")).map(|value| value.as_str().to_string()), Some("open".to_string()));
3282        assert!(result.get_idx(1).is_some_and(|value| value.is_null()));
3283        assert!(action_map.get_dynamic("panel#open").is_none());
3284        Ok(())
3285    }
3286
3287    #[test]
3288    fn dynamic_field_value_participates_in_or_expression() -> anyhow::Result<()> {
3289        let vm = Vm::with_all()?;
3290        vm.import_code(
3291            "vm_dynamic_field_or",
3292            r#"
3293            pub fn direct_next() {
3294                let choice = {
3295                    label: "颜色",
3296                    next: "color"
3297                };
3298                choice.next
3299            }
3300
3301            pub fn bracket_next() {
3302                let choice = {
3303                    label: "颜色",
3304                    next: "color"
3305                };
3306                choice["next"]
3307            }
3308            "#
3309            .as_bytes()
3310            .to_vec(),
3311        )?;
3312
3313        let compiled = vm.get_fn("vm_dynamic_field_or::direct_next", &[])?;
3314        assert_eq!(compiled.ret_ty(), &Type::Any);
3315        let direct_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3316        assert_eq!(unsafe { &*direct_next() }.as_str(), "color");
3317
3318        let compiled = vm.get_fn("vm_dynamic_field_or::bracket_next", &[])?;
3319        assert_eq!(compiled.ret_ty(), &Type::Any);
3320        let bracket_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3321        assert_eq!(unsafe { &*bracket_next() }.as_str(), "color");
3322        Ok(())
3323    }
3324
3325    #[test]
3326    fn empty_object_literal_in_if_branch_stays_dynamic() -> anyhow::Result<()> {
3327        let vm = Vm::with_all()?;
3328        vm.import_code(
3329            "vm_if_empty_object_branch",
3330            r#"
3331            pub fn first_note(steps) {
3332                let first = if steps.len() > 0 { steps[0] } else { {} };
3333                let first_note = if first.contains("note") { first.note } else { "fallback" };
3334                first_note
3335            }
3336
3337            pub fn first_ja(steps) {
3338                let first = if steps.len() > 0 { steps[0] } else { {} };
3339                if first.contains("ja") { first.ja } else { "すみません" }
3340            }
3341
3342            pub fn assign_first_note(steps) {
3343                let first = {};
3344                first = if steps.len() > 0 { steps[0] } else { {} };
3345                if first.contains("note") { first.note } else { "fallback" }
3346            }
3347            "#
3348            .as_bytes()
3349            .to_vec(),
3350        )?;
3351
3352        let compiled = vm.get_fn("vm_if_empty_object_branch::first_note", &[Type::Any])?;
3353        assert_eq!(compiled.ret_ty(), &Type::Str);
3354        let first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3355
3356        let empty_steps = Dynamic::list(Vec::new());
3357        assert_eq!(unsafe { &*first_note(&empty_steps) }.as_str(), "fallback");
3358
3359        let mut step = std::collections::BTreeMap::new();
3360        step.insert("note".into(), "hello".into());
3361        let steps = Dynamic::list(vec![Dynamic::map(step)]);
3362        assert_eq!(unsafe { &*first_note(&steps) }.as_str(), "hello");
3363
3364        let compiled = vm.get_fn("vm_if_empty_object_branch::first_ja", &[Type::Any])?;
3365        assert_eq!(compiled.ret_ty(), &Type::Any);
3366        let first_ja: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3367        assert_eq!(unsafe { &*first_ja(&empty_steps) }.as_str(), "すみません");
3368
3369        let compiled = vm.get_fn("vm_if_empty_object_branch::assign_first_note", &[Type::Any])?;
3370        assert_eq!(compiled.ret_ty(), &Type::Any);
3371        let assign_first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3372        assert_eq!(unsafe { &*assign_first_note(&empty_steps) }.as_str(), "fallback");
3373        assert_eq!(unsafe { &*assign_first_note(&steps) }.as_str(), "hello");
3374        Ok(())
3375    }
3376
3377    #[test]
3378    fn list_literal_can_be_function_tail_expression() -> anyhow::Result<()> {
3379        let vm = Vm::with_all()?;
3380        vm.import_code(
3381            "vm_tail_list_literal",
3382            r#"
3383            pub fn numbers() {
3384                [1, 2, 3]
3385            }
3386
3387            pub fn maps() {
3388                [
3389                    {note: "first"},
3390                    {note: "second"}
3391                ]
3392            }
3393
3394            pub fn object_with_maps() {
3395                {
3396                    steps: [
3397                        {note: "first"},
3398                        {note: "second"}
3399                    ]
3400                }
3401            }
3402
3403            pub fn return_maps() {
3404                return [
3405                    {note: "first"},
3406                    {note: "second"}
3407                ];
3408            }
3409
3410            pub fn return_maps_without_semicolon() {
3411                return [
3412                    {note: "first"},
3413                    {note: "second"}
3414                ]
3415            }
3416
3417            pub fn tail_bare_variable() {
3418                let value = [
3419                    {note: "first"},
3420                    {note: "second"}
3421                ];
3422                value
3423            }
3424
3425            pub fn return_bare_variable_without_semicolon() {
3426                let value = [
3427                    {note: "first"},
3428                    {note: "second"}
3429                ];
3430                return value
3431            }
3432
3433            pub fn tail_object_variable() {
3434                let result = {
3435                    steps: [
3436                        {note: "first"},
3437                        {note: "second"}
3438                    ]
3439                };
3440                result
3441            }
3442            "#
3443            .as_bytes()
3444            .to_vec(),
3445        )?;
3446
3447        let compiled = vm.get_fn("vm_tail_list_literal::numbers", &[])?;
3448        assert_eq!(compiled.ret_ty(), &Type::Any);
3449        let numbers: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3450        let result = unsafe { &*numbers() };
3451        assert_eq!(result.len(), 3);
3452        assert_eq!(result.get_idx(1).and_then(|value| value.as_int()), Some(2));
3453
3454        let compiled = vm.get_fn("vm_tail_list_literal::maps", &[])?;
3455        assert_eq!(compiled.ret_ty(), &Type::Any);
3456        let maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3457        let result = unsafe { &*maps() };
3458        assert_eq!(result.len(), 2);
3459        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3460
3461        let compiled = vm.get_fn("vm_tail_list_literal::object_with_maps", &[])?;
3462        assert_eq!(compiled.ret_ty(), &Type::Any);
3463        let object_with_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3464        let result = unsafe { &*object_with_maps() };
3465        let steps = result.get_dynamic("steps").expect("steps");
3466        assert_eq!(steps.len(), 2);
3467        assert_eq!(steps.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3468
3469        let compiled = vm.get_fn("vm_tail_list_literal::return_maps", &[])?;
3470        assert_eq!(compiled.ret_ty(), &Type::Any);
3471        let return_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3472        let result = unsafe { &*return_maps() };
3473        assert_eq!(result.len(), 2);
3474        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3475
3476        let compiled = vm.get_fn("vm_tail_list_literal::return_maps_without_semicolon", &[])?;
3477        assert_eq!(compiled.ret_ty(), &Type::Any);
3478        let return_maps_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3479        let result = unsafe { &*return_maps_without_semicolon() };
3480        assert_eq!(result.len(), 2);
3481        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3482
3483        let compiled = vm.get_fn("vm_tail_list_literal::tail_bare_variable", &[])?;
3484        assert_eq!(compiled.ret_ty(), &Type::Any);
3485        let tail_bare_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3486        let result = unsafe { &*tail_bare_variable() };
3487        assert_eq!(result.len(), 2);
3488        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3489
3490        let compiled = vm.get_fn("vm_tail_list_literal::return_bare_variable_without_semicolon", &[])?;
3491        assert_eq!(compiled.ret_ty(), &Type::Any);
3492        let return_bare_variable_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3493        let result = unsafe { &*return_bare_variable_without_semicolon() };
3494        assert_eq!(result.len(), 2);
3495        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3496
3497        let compiled = vm.get_fn("vm_tail_list_literal::tail_object_variable", &[])?;
3498        assert_eq!(compiled.ret_ty(), &Type::Any);
3499        let tail_object_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3500        let result = unsafe { &*tail_object_variable() };
3501        let steps = result.get_dynamic("steps").expect("steps");
3502        assert_eq!(steps.len(), 2);
3503        assert_eq!(steps.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3504        Ok(())
3505    }
3506
3507    #[test]
3508    fn match_literals_or_guard_order_and_block_body() -> anyhow::Result<()> {
3509        let vm = Vm::with_all()?;
3510        vm.import_code(
3511            "vm_match_scalar",
3512            r#"
3513            pub fn classify(value: i64) {
3514                match value {
3515                    0i64 => 10i64,
3516                    1i64 | 2i64 => 20i64,
3517                    x if x > 10i64 => x + 100i64,
3518                    _ => -1i64,
3519                }
3520            }
3521
3522            pub fn first_arm_wins() {
3523                match 1i64 {
3524                    _ => 7i64,
3525                    1i64 => 9i64,
3526                }
3527            }
3528
3529            pub fn block_body(value: i64) {
3530                match value {
3531                    3i64 => {
3532                        let base = 4i64;
3533                        base + 5i64
3534                    },
3535                    _ => 1i64,
3536                }
3537            }
3538            "#
3539            .as_bytes()
3540            .to_vec(),
3541        )?;
3542
3543        let classify = vm.get_fn("vm_match_scalar::classify", &[Type::I64])?;
3544        assert_eq!(call_i64_1(&classify, 0), 10);
3545        assert_eq!(call_i64_1(&classify, 1), 20);
3546        assert_eq!(call_i64_1(&classify, 2), 20);
3547        assert_eq!(call_i64_1(&classify, 12), 112);
3548        assert_eq!(call_i64_1(&classify, 5), -1);
3549
3550        let first_arm_wins = vm.get_fn("vm_match_scalar::first_arm_wins", &[])?;
3551        assert_eq!(call_i64_0(&first_arm_wins), 7);
3552
3553        let block_body = vm.get_fn("vm_match_scalar::block_body", &[Type::I64])?;
3554        assert_eq!(call_i64_1(&block_body, 3), 9);
3555        assert_eq!(call_i64_1(&block_body, 4), 1);
3556        Ok(())
3557    }
3558
3559    #[test]
3560    fn match_binds_tuple_list_rest_and_struct_fields() -> anyhow::Result<()> {
3561        let vm = Vm::with_all()?;
3562        vm.import_code(
3563            "vm_match_bindings",
3564            r#"
3565            pub fn tuple_sum() {
3566                match (3i64, 4i64) {
3567                    (a, b) => a + b,
3568                    _ => 0i64,
3569                }
3570            }
3571
3572            pub fn list_rest_score() {
3573                let items = [1i64, 2i64, 3i64, 4i64];
3574                match items {
3575                    [head, second, ..tail] if tail.len() == 2 => head * 100i64 + second * 10i64 + tail[1],
3576                    _ => -1i64,
3577                }
3578            }
3579
3580            pub fn struct_field_score() {
3581                let data = {
3582                    id: 7i64,
3583                    tags: ["a", "b", "c"],
3584                    nested: { value: 5i64 }
3585                };
3586                match data {
3587                    Data { id, tags: ["a", second, ..rest], nested: Data { value } } => {
3588                        id * 100i64 + value * 10i64 + rest.len()
3589                    },
3590                    _ => -1i64,
3591                }
3592            }
3593            "#
3594            .as_bytes()
3595            .to_vec(),
3596        )?;
3597
3598        let tuple_sum = vm.get_fn("vm_match_bindings::tuple_sum", &[])?;
3599        assert_eq!(call_i64_0(&tuple_sum), 7);
3600
3601        let list_rest_score = vm.get_fn("vm_match_bindings::list_rest_score", &[])?;
3602        assert_eq!(call_i64_0(&list_rest_score), 124);
3603
3604        let struct_field_score = vm.get_fn("vm_match_bindings::struct_field_score", &[])?;
3605        assert_eq!(call_i64_0(&struct_field_score), 751);
3606        Ok(())
3607    }
3608
3609    #[test]
3610    fn match_supports_nested_expressions_and_null_miss() -> anyhow::Result<()> {
3611        let vm = Vm::with_all()?;
3612        vm.import_code(
3613            "vm_match_nested",
3614            r#"
3615            pub fn nested(value: i64) {
3616                match value {
3617                    1i64 => match "a" {
3618                        "a" => 11i64,
3619                        _ => 12i64,
3620                    },
3621                    2i64 => match [1i64, 2i64] {
3622                        [_, tail] => tail + 20i64,
3623                        _ => 0i64,
3624                    },
3625                    _ => 0i64,
3626                }
3627            }
3628
3629            pub fn no_arm(value: i64) {
3630                match value {
3631                    1i64 => 10i64,
3632                }
3633            }
3634            "#
3635            .as_bytes()
3636            .to_vec(),
3637        )?;
3638
3639        let nested = vm.get_fn("vm_match_nested::nested", &[Type::I64])?;
3640        assert_eq!(call_i64_1(&nested, 1), 11);
3641        assert_eq!(call_i64_1(&nested, 2), 22);
3642        assert_eq!(call_i64_1(&nested, 3), 0);
3643
3644        let no_arm = vm.get_fn("vm_match_nested::no_arm", &[Type::I64])?;
3645        assert_eq!(no_arm.ret_ty(), &Type::Any);
3646        let no_arm: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(no_arm.ptr()) };
3647        assert_eq!(unsafe { &*no_arm(1) }.as_int(), Some(10));
3648        assert!(unsafe { &*no_arm(2) }.is_null());
3649        Ok(())
3650    }
3651
3652    #[test]
3653    fn match_rejects_binding_after_first_or_pattern() -> anyhow::Result<()> {
3654        let vm = Vm::with_all()?;
3655        let err = vm
3656            .import_code(
3657                "vm_match_bad_or",
3658                r#"
3659                pub fn bad(value: i64) {
3660                    match value {
3661                        a | b => 1i64,
3662                    }
3663                }
3664                "#
3665                .as_bytes()
3666                .to_vec(),
3667            )
3668            .expect_err("non-first or-pattern alternatives cannot bind");
3669        assert!(err.to_string().contains("or-pattern"));
3670        Ok(())
3671    }
3672
3673    #[test]
3674    fn list_return_value_supports_get_idx_method_call() -> anyhow::Result<()> {
3675        let vm = Vm::with_all()?;
3676        vm.import_code(
3677            "vm_returned_list_get_idx",
3678            r#"
3679            pub fn ids() {
3680                [
3681                    "base",
3682                    "2",
3683                    "3"
3684                ]
3685            }
3686
3687            pub fn combinations() {
3688                let result = [];
3689                let values = ids();
3690                let idx = 0;
3691                while idx < values.len() {
3692                    result.push(values.get_idx(idx));
3693                    idx = idx + 1;
3694                }
3695                result
3696            }
3697            "#
3698            .as_bytes()
3699            .to_vec(),
3700        )?;
3701
3702        let compiled = vm.get_fn("vm_returned_list_get_idx::combinations", &[])?;
3703        assert_eq!(compiled.ret_ty(), &Type::Any);
3704        let combinations: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3705        let result = unsafe { &*combinations() };
3706
3707        assert_eq!(result.len(), 3);
3708        assert_eq!(result.get_idx(0).map(|value| value.as_str().to_string()), Some("base".to_string()));
3709        assert_eq!(result.get_idx(2).map(|value| value.as_str().to_string()), Some("3".to_string()));
3710        Ok(())
3711    }
3712
3713    #[test]
3714    fn repeated_deep_step_literals_import_successfully() -> anyhow::Result<()> {
3715        fn extra_page_literal(depth: usize) -> String {
3716            let mut value = "{leaf: \"done\"}".to_string();
3717            for idx in 0..depth {
3718                value = format!("{{kind: \"page\", idx: {idx}, children: [{value}], meta: {{title: \"extra\", visible: true}}}}");
3719            }
3720            value
3721        }
3722
3723        let extra = extra_page_literal(48);
3724        let code = format!(
3725            r#"
3726            pub fn script() {{
3727                return [
3728                    {{ja: "一つ目", note: "first", extra: {extra}}},
3729                    {{ja: "二つ目", note: "second", extra: {extra}}},
3730                    {{ja: "三つ目", note: "third", extra: {extra}}}
3731                ]
3732            }}
3733            "#
3734        );
3735
3736        let vm = Vm::with_all()?;
3737        vm.import_code("vm_repeated_deep_step_literals", code.into_bytes())?;
3738        let compiled = vm.get_fn("vm_repeated_deep_step_literals::script", &[])?;
3739        assert_eq!(compiled.ret_ty(), &Type::Any);
3740        let script: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3741        let result = unsafe { &*script() };
3742        assert_eq!(result.len(), 3);
3743        assert_eq!(result.get_idx(2).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("third".to_string()));
3744        Ok(())
3745    }
3746
3747    #[test]
3748    fn native_import_uses_owning_vm() -> anyhow::Result<()> {
3749        let module_path = std::env::temp_dir().join(format!("zust_vm_import_owner_{}.zs", std::process::id()));
3750        std::fs::write(&module_path, "pub fn value() { 41 }")?;
3751        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
3752
3753        let vm1 = Vm::with_all()?;
3754        vm1.import_code(
3755            "vm_import_owner",
3756            format!(
3757                r#"
3758                pub fn run() {{
3759                    import("vm_imported_owner", "{module_path}");
3760                }}
3761                "#
3762            )
3763            .into_bytes(),
3764        )?;
3765        let compiled = vm1.get_fn("vm_import_owner::run", &[])?;
3766
3767        let vm2 = Vm::with_all()?;
3768        vm2.import_code("vm_import_other", b"pub fn run() { 0 }".to_vec())?;
3769        let _ = vm2.get_fn("vm_import_other::run", &[])?;
3770
3771        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
3772        run();
3773
3774        assert!(vm1.get_fn("vm_imported_owner::value", &[]).is_ok());
3775        assert!(vm2.get_fn("vm_imported_owner::value", &[]).is_err());
3776        Ok(())
3777    }
3778
3779    #[test]
3780    fn object_last_field_call_does_not_need_trailing_comma() -> anyhow::Result<()> {
3781        let vm = Vm::with_all()?;
3782        vm.import_code(
3783            "vm_object_last_call_field",
3784            r#"
3785            pub fn extra_page() {
3786                {
3787                    title: "extra",
3788                    pages: [
3789                        {note: "nested"}
3790                    ]
3791                }
3792            }
3793
3794            pub fn data() {
3795                return [
3796                    {
3797                        note: "first",
3798                        choices: ["a", "b"],
3799                        extras: extra_page()
3800                    },
3801                    {
3802                        note: "second",
3803                        choices: ["c"],
3804                        extras: extra_page()
3805                    }
3806                ]
3807            }
3808            "#
3809            .as_bytes()
3810            .to_vec(),
3811        )?;
3812
3813        let compiled = vm.get_fn("vm_object_last_call_field::data", &[])?;
3814        assert_eq!(compiled.ret_ty(), &Type::Any);
3815        let data: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3816        let result = unsafe { &*data() };
3817        assert_eq!(result.len(), 2);
3818        let first = result.get_idx(0).expect("first step");
3819        assert_eq!(first.get_dynamic("extras").and_then(|extras| extras.get_dynamic("title")).map(|title| title.as_str().to_string()), Some("extra".to_string()));
3820        Ok(())
3821    }
3822
3823    #[test]
3824    fn string_return_survives_scope_exit() -> anyhow::Result<()> {
3825        let vm = Vm::with_all()?;
3826        vm.import_code(
3827            "vm_string_return_scope",
3828            r#"
3829            pub fn source_root() {
3830                "../assets/character/男主角换装"
3831            }
3832
3833            pub fn binary_root() {
3834                "character_binary/男主角换装"
3835            }
3836
3837            pub fn runtime_binary_url() {
3838                "/" + binary_root()
3839            }
3840
3841            pub fn action_groups() {
3842                let root = source_root();
3843                let binary_url = runtime_binary_url();
3844                let binary_root = binary_root();
3845                [
3846                    {
3847                        id: "field_bottom",
3848                        source_spine: root + "/战斗外/boy_b.spine",
3849                        skeleton: binary_url + "/战斗外/boy_b/boy_b.skel.bytes",
3850                        export_skeleton: binary_root + "/战斗外/boy_b/boy_b.skel.bytes"
3851                    }
3852                ]
3853            }
3854            "#
3855            .as_bytes()
3856            .to_vec(),
3857        )?;
3858
3859        let compiled = vm.get_fn("vm_string_return_scope::source_root", &[])?;
3860        assert_eq!(compiled.ret_ty(), &Type::Str);
3861        let source_root: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3862        let source_root = unsafe { &*source_root() };
3863        assert_eq!(source_root.as_str(), "../assets/character/男主角换装");
3864
3865        let compiled = vm.get_fn("vm_string_return_scope::action_groups", &[])?;
3866        assert_eq!(compiled.ret_ty(), &Type::Any);
3867        let action_groups: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3868        let groups = unsafe { &*action_groups() };
3869        let first = groups.get_idx(0).expect("first action group");
3870        assert_eq!(first.get_dynamic("source_spine").map(|value| value.as_str().to_string()), Some("../assets/character/男主角换装/战斗外/boy_b.spine".to_string()));
3871        assert_eq!(first.get_dynamic("skeleton").map(|value| value.as_str().to_string()), Some("/character_binary/男主角换装/战斗外/boy_b/boy_b.skel.bytes".to_string()));
3872        Ok(())
3873    }
3874
3875    #[test]
3876    fn dynamic_string_add_uses_any_binary_fast_path() -> anyhow::Result<()> {
3877        let vm = Vm::with_all()?;
3878        vm.import_code(
3879            "vm_dynamic_string_add",
3880            br#"
3881            pub fn concat(left, right) {
3882                left + right
3883            }
3884            "#
3885            .to_vec(),
3886        )?;
3887
3888        let compiled = vm.get_fn("vm_dynamic_string_add::concat", &[Type::Any, Type::Any])?;
3889        assert_eq!(compiled.ret_ty(), &Type::Any);
3890        let concat: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3891        let left = Dynamic::from("hello");
3892        let right = Dynamic::from(" world");
3893        let result = unsafe { &*concat(&left, &right) };
3894        assert_eq!(result.as_str(), "hello world");
3895        Ok(())
3896    }
3897
3898    #[test]
3899    fn large_dynamic_object_accepts_inline_call_fields() -> anyhow::Result<()> {
3900        let vm = Vm::with_all()?;
3901        let model_count = 180;
3902        let combination_count = 90;
3903        let models = (0..model_count)
3904            .map(|idx| {
3905                format!(
3906                    r#"{{id: "model_{idx}", name: "模型_{idx}", source: "/美术资源/角色/少年/套装_{idx}/模型_{idx}.model.json", parts: [
3907                        {{slot: "hair", path: "/模型/头发/颜色_{idx}/默认.png", z: 10}},
3908                        {{slot: "body", path: "/模型/身体/套装_{idx}/默认.png", z: 1}},
3909                        {{slot: "face", path: "/模型/表情/表情_{idx}/默认.png", z: 20}}
3910                    ]}}"#
3911                )
3912            })
3913            .collect::<Vec<_>>()
3914            .join(",\n");
3915        let combinations = (0..combination_count).map(|idx| format!(r#"{{hair: "color_{idx}", body: "set_{idx}", face: "face_{idx}"}}"#)).collect::<Vec<_>>().join(",\n");
3916        let code = format!(
3917            r#"
3918            pub fn source_root() {{
3919                "/美术资源/角色/少年/默认"
3920            }}
3921
3922            pub fn runtime_boy_url() {{
3923                "/cdn/runtime/角色/少年/少年.model.json"
3924            }}
3925
3926            pub fn parts() {{
3927                [
3928                    {{id: "hair", path: "/模型/头发/黑色/默认.png", z: 10}},
3929                    {{id: "body", path: "/模型/身体/校服/默认.png", z: 1}},
3930                    {{id: "face", path: "/模型/表情/微笑/默认.png", z: 20}}
3931                ]
3932            }}
3933
3934            pub fn action_groups() {{
3935                {{
3936                    idle: [
3937                        {{id: "stand", name: "站立", frames: ["待机/0001.png", "待机/0002.png"]}},
3938                        {{id: "blink", name: "眨眼", frames: ["表情/眨眼/0001.png", "表情/眨眼/0002.png"]}}
3939                    ],
3940                    move: [
3941                        {{id: "walk", name: "行走", frames: ["行走/0001.png", "行走/0002.png"]}},
3942                        {{id: "run", name: "奔跑", frames: ["奔跑/0001.png", "奔跑/0002.png"]}}
3943                    ]
3944                }}
3945            }}
3946
3947            pub fn default_model() {{
3948                {{
3949                    id: "runtime_boy",
3950                    name: "运行时少年",
3951                    skins: [
3952                        {{id: "school", title: "校服", source: "/套装/校服/model.json"}},
3953                        {{id: "casual", title: "便服", source: "/套装/便服/model.json"}}
3954                    ],
3955                    models: [
3956                        {models}
3957                    ]
3958                }}
3959            }}
3960
3961            pub fn first_nine_combinations() {{
3962                [
3963                    {combinations}
3964                ]
3965            }}
3966
3967            pub fn config() {{
3968                {{
3969                    source_root: source_root(),
3970                    runtime_boy_url: runtime_boy_url(),
3971                    parts: parts(),
3972                    action_groups: action_groups(),
3973                    default_model: default_model(),
3974                    first_nine_combinations: first_nine_combinations()
3975                }}
3976            }}
3977
3978            pub fn start() {{
3979                root::add("local/vm_large_inline_call_object/config", {{
3980                    source_root: source_root(),
3981                    runtime_boy_url: runtime_boy_url(),
3982                    parts: parts(),
3983                    action_groups: action_groups(),
3984                    default_model: default_model(),
3985                    first_nine_combinations: first_nine_combinations()
3986                }})
3987            }}
3988            "#
3989        );
3990        vm.import_code("vm_large_inline_call_object", code.into_bytes())?;
3991
3992        let compiled = vm.get_fn("vm_large_inline_call_object::config", &[])?;
3993        assert_eq!(compiled.ret_ty(), &Type::Any);
3994        let config: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3995        let result = unsafe { &*config() };
3996        assert_eq!(result.get_dynamic("source_root").map(|value| value.as_str().to_string()), Some("/美术资源/角色/少年/默认".to_string()));
3997        assert_eq!(result.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
3998
3999        let compiled = vm.get_fn("vm_large_inline_call_object::start", &[])?;
4000        assert_eq!(compiled.ret_ty(), &Type::Bool);
4001        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4002        assert!(start());
4003        let saved = root::get("local/vm_large_inline_call_object/config")?;
4004        assert_eq!(saved.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
4005        Ok(())
4006    }
4007
4008    #[cfg(feature = "http")]
4009    #[test]
4010    fn http_serve_accepts_inline_config_map() -> anyhow::Result<()> {
4011        let vm = Vm::with_all()?;
4012        vm.import_code(
4013            "vm_http_serve_inline_config",
4014            br#"
4015            pub fn start() {
4016                let server = http::serve({host: "127.0.0.1:5192"});
4017                server
4018            }
4019            "#
4020            .to_vec(),
4021        )?;
4022
4023        let compiled = vm.get_fn("vm_http_serve_inline_config::start", &[])?;
4024        assert_eq!(compiled.ret_ty(), &Type::Any);
4025        Ok(())
4026    }
4027
4028    #[cfg(feature = "http")]
4029    #[test]
4030    fn http_serve_accepts_variable_and_quoted_static_key() -> anyhow::Result<()> {
4031        let vm = Vm::with_all()?;
4032        vm.import_code(
4033            "vm_http_serve_quoted_static",
4034            br#"
4035            pub fn start(server_addr) {
4036                let http_server = http::serve({
4037                    host: server_addr,
4038                    ws: true,
4039                    upload: "upload",
4040                    "static": {
4041                        path: "/",
4042                        dir: "public/local"
4043                    }
4044                });
4045                http_server
4046            }
4047            "#
4048            .to_vec(),
4049        )?;
4050
4051        let compiled = vm.get_fn("vm_http_serve_quoted_static::start", &[Type::Any])?;
4052        assert_eq!(compiled.ret_ty(), &Type::Any);
4053        Ok(())
4054    }
4055
4056    #[cfg(all(feature = "http", feature = "llm"))]
4057    #[test]
4058    fn oss_helpers_accept_explicit_config() -> anyhow::Result<()> {
4059        let vm = Vm::with_all()?;
4060        vm.import_code(
4061            "vm_oss_explicit_config",
4062            br#"
4063            pub fn upload(oss, bytes) {
4064                oss::upload(oss, "llm/input/audio.wav", bytes)
4065            }
4066
4067            pub fn http_upload(oss, bytes) {
4068                http::upload(oss, "uploads/input.bin", bytes)
4069            }
4070
4071            pub fn link(oss, uploaded) {
4072                oss::signed_url(oss, {oss_url: uploaded, expires: 3600})
4073            }
4074            "#
4075            .to_vec(),
4076        )?;
4077
4078        assert_eq!(vm.get_fn("vm_oss_explicit_config::upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
4079        assert_eq!(vm.get_fn("vm_oss_explicit_config::http_upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
4080        assert_eq!(vm.get_fn("vm_oss_explicit_config::link", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
4081        Ok(())
4082    }
4083
4084    #[cfg(feature = "http")]
4085    #[test]
4086    fn load_script_accepts_http_serve_inline_config() -> anyhow::Result<()> {
4087        let vm = Vm::with_all()?;
4088        let (_fn_ptr, ty) = vm.load(
4089            br#"
4090            let server_addr = "127.0.0.1:5192";
4091            let http_server = http::serve({
4092                host: server_addr,
4093                ws: true,
4094                upload: "upload",
4095                "static": {
4096                    path: "/",
4097                    dir: "public/local"
4098                }
4099            });
4100            http_server
4101            "#
4102            .to_vec(),
4103            "arg".into(),
4104        )?;
4105
4106        assert_eq!(ty, Type::Any);
4107        Ok(())
4108    }
4109
4110    #[test]
4111    fn load_script_resolves_import_before_compile() -> anyhow::Result<()> {
4112        let module_path = std::env::temp_dir().join(format!("zust_vm_load_import_{}.zs", std::process::id()));
4113        std::fs::write(&module_path, "pub fn init() { return {ok: true}; }")?;
4114        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
4115
4116        let vm = Vm::with_all()?;
4117        let (_fn_ptr, ty) = vm.load(
4118            format!(
4119                r#"
4120                import("create_scene", "{module_path}");
4121                create_scene::init();
4122                "#
4123            )
4124            .into_bytes(),
4125            "req".into(),
4126        )?;
4127
4128        assert_eq!(ty, Type::Void);
4129        Ok(())
4130    }
4131
4132    #[test]
4133    fn gpu_struct_layout_packs_and_unpacks_dynamic_maps() -> anyhow::Result<()> {
4134        let vm = Vm::with_all()?;
4135        vm.import_code(
4136            "vm_gpu_layout",
4137            br#"
4138            pub struct Params {
4139                a: u32,
4140                b: u32,
4141                c: u32,
4142            }
4143            "#
4144            .to_vec(),
4145        )?;
4146
4147        let layout = vm.gpu_struct_layout("vm_gpu_layout::Params", &[])?;
4148        assert_eq!(layout.size, 16);
4149        assert_eq!(layout.fields.iter().map(|field| (field.name.as_str(), field.offset)).collect::<Vec<_>>(), vec![("a", 0), ("b", 4), ("c", 8)]);
4150
4151        let value = dynamic::map!("a"=> 1u32, "b"=> 2u32, "c"=> 3u32);
4152        let bytes = layout.pack_map(&value)?;
4153        assert_eq!(bytes.len(), 16);
4154        assert_eq!(&bytes[0..4], &1u32.to_ne_bytes());
4155        assert_eq!(&bytes[4..8], &2u32.to_ne_bytes());
4156        assert_eq!(&bytes[8..12], &3u32.to_ne_bytes());
4157
4158        let read = layout.unpack_map(&bytes)?;
4159        assert_eq!(read.get_dynamic("a").and_then(|value| value.as_uint()), Some(1));
4160        assert_eq!(read.get_dynamic("b").and_then(|value| value.as_uint()), Some(2));
4161        assert_eq!(read.get_dynamic("c").and_then(|value| value.as_uint()), Some(3));
4162        Ok(())
4163    }
4164
4165    #[test]
4166    fn root_native_calls_do_not_take_ownership_of_dynamic_args() -> anyhow::Result<()> {
4167        let vm = Vm::with_all()?;
4168        vm.import_code(
4169            "vm_root_clone_bridge",
4170            br#"
4171            pub fn add_then_reuse(arg) {
4172                let user = {
4173                    address: "test-wallet",
4174                    points: 20
4175                };
4176                root::add("local/root-clone-bridge-user", user);
4177                user.points = user.points - 7;
4178                root::add("local/root-clone-bridge-user", user);
4179                {
4180                    user: user,
4181                    points: user.points
4182                }
4183            }
4184
4185            pub fn clone_then_mutate(arg) {
4186                let user = {
4187                    profile: {
4188                        points: 20
4189                    }
4190                };
4191                let copied = user.clone();
4192                copied.profile.points = 13;
4193                user
4194            }
4195            "#
4196            .to_vec(),
4197        )?;
4198
4199        let compiled = vm.get_fn("vm_root_clone_bridge::add_then_reuse", &[Type::Any])?;
4200        assert_eq!(compiled.ret_ty(), &Type::Any);
4201        let add_then_reuse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4202        let arg = Dynamic::Null;
4203        let result = add_then_reuse(&arg);
4204        let result = unsafe { &*result };
4205
4206        assert_eq!(result.get_dynamic("points").and_then(|value| value.as_int()), Some(13));
4207        let mut json = String::new();
4208        result.to_json(&mut json);
4209        assert!(json.contains("\"points\": 13"));
4210
4211        let clone_then_mutate = vm.get_fn("vm_root_clone_bridge::clone_then_mutate", &[Type::Any])?;
4212        let clone_then_mutate: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(clone_then_mutate.ptr()) };
4213        let result = clone_then_mutate(&arg);
4214        let result = unsafe { &*result };
4215        assert_eq!(result.get_dynamic("profile").unwrap().get_dynamic("points").and_then(|value| value.as_int()), Some(20));
4216        Ok(())
4217    }
4218
4219    struct CounterForTypedReceiver {
4220        value: i64,
4221    }
4222
4223    extern "C" fn counter_for_typed_receiver_get(value: *const Dynamic) -> i64 {
4224        unsafe { &*value }.as_custom::<CounterForTypedReceiver>().map(|counter| counter.value).unwrap_or(-1)
4225    }
4226
4227    struct NavMapForFunctionArg;
4228
4229    extern "C" fn nav_map_for_function_arg_new() -> *const Dynamic {
4230        Box::into_raw(Box::new(Dynamic::custom(NavMapForFunctionArg)))
4231    }
4232
4233    #[derive(Debug, Default)]
4234    struct PropertyForwardingObject {
4235        values: parking_lot::RwLock<BTreeMap<String, Dynamic>>,
4236    }
4237
4238    impl CustomProperty for PropertyForwardingObject {
4239        fn get_key(&self, key: &str) -> Option<Dynamic> {
4240            self.values.read().get(key).cloned()
4241        }
4242
4243        fn set_key(&self, key: &str, value: Dynamic) -> bool {
4244            self.values.write().insert(key.to_string(), value);
4245            true
4246        }
4247    }
4248
4249    extern "C" fn property_forwarding_object_new() -> *const Dynamic {
4250        Box::into_raw(Box::new(Dynamic::custom_with_properties(PropertyForwardingObject::default())))
4251    }
4252
4253    #[test]
4254    fn typed_receiver_method_call_dispatches_with_type_hint() -> anyhow::Result<()> {
4255        let vm = Vm::with_all()?;
4256        vm.add_empty_type("Counter")?;
4257        let counter_ty = vm.get_symbol("Counter", Vec::new())?;
4258        vm.add_native_method_ptr("Counter", "get", &[counter_ty], Type::I64, counter_for_typed_receiver_get as *const u8)?;
4259        vm.import_code(
4260            "vm_typed_receiver_method",
4261            br#"
4262            pub fn run(value) {
4263                value::<Counter>::get()
4264            }
4265            "#
4266            .to_vec(),
4267        )?;
4268
4269        let compiled = vm.get_fn("vm_typed_receiver_method::run", &[Type::Any])?;
4270        assert_eq!(compiled.ret_ty(), &Type::I64);
4271        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4272        let value = Dynamic::custom(CounterForTypedReceiver { value: 42 });
4273
4274        assert_eq!(run(&value), 42);
4275        Ok(())
4276    }
4277
4278    #[test]
4279    fn native_custom_object_can_be_passed_to_zs_function() -> anyhow::Result<()> {
4280        let vm = Vm::with_all()?;
4281        vm.add_empty_type("NavMap")?;
4282        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
4283        vm.import_code(
4284            "vm_native_custom_arg",
4285            br#"
4286            pub fn add_nav_spawns(world, navmap) {
4287                navmap
4288            }
4289
4290            pub fn run(world) {
4291                let navmap = NavMap::new();
4292                let with_spawns = add_nav_spawns(world, navmap);
4293                with_spawns
4294            }
4295            "#
4296            .to_vec(),
4297        )?;
4298
4299        let compiled = vm.get_fn("vm_native_custom_arg::run", &[Type::Any])?;
4300        assert_eq!(compiled.ret_ty(), &Type::Any);
4301        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4302        let world = Dynamic::Null;
4303        let result = run(&world);
4304        let result = unsafe { &*result };
4305
4306        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
4307        Ok(())
4308    }
4309
4310    #[test]
4311    fn any_field_assignment_forwards_to_custom_properties() -> anyhow::Result<()> {
4312        let vm = Vm::with_all()?;
4313        vm.add_empty_type("Dialog")?;
4314        vm.add_native_method_ptr("Dialog", "new", &[], Type::Any, property_forwarding_object_new as *const u8)?;
4315        vm.import_code(
4316            "vm_custom_property_forwarding",
4317            br#"
4318            pub fn run() {
4319                let dialog = Dialog::new();
4320                dialog.file_mode = 3;
4321                dialog.file_mode
4322            }
4323            "#
4324            .to_vec(),
4325        )?;
4326
4327        let compiled = vm.get_fn("vm_custom_property_forwarding::run", &[])?;
4328        assert_eq!(compiled.ret_ty(), &Type::Any);
4329        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4330        let result = unsafe { &*run() };
4331
4332        assert_eq!(result.as_int(), Some(3));
4333        Ok(())
4334    }
4335
4336    #[test]
4337    fn native_custom_object_typed_local_can_be_passed_to_zs_function() -> anyhow::Result<()> {
4338        let vm = Vm::with_all()?;
4339        vm.add_empty_type("NavMap")?;
4340        let _nav_map_ty = vm.get_symbol("NavMap", Vec::new())?;
4341        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
4342        vm.import_code(
4343            "vm_native_custom_typed_arg",
4344            br#"
4345            pub fn add_nav_spawns(world, navmap) {
4346                navmap
4347            }
4348
4349            pub fn run(world) {
4350                let navmap: NavMap = NavMap::new();
4351                let with_spawns = add_nav_spawns(world, navmap);
4352                with_spawns
4353            }
4354            "#
4355            .to_vec(),
4356        )?;
4357
4358        let compiled = vm.get_fn("vm_native_custom_typed_arg::run", &[Type::Any])?;
4359        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4360        let world = Dynamic::Null;
4361        let result = run(&world);
4362        let result = unsafe { &*result };
4363
4364        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
4365        Ok(())
4366    }
4367
4368    // ---- 新增边界条件测试 ----
4369
4370    #[test]
4371    fn dynamic_type_checks_on_null_and_primitive_values() -> anyhow::Result<()> {
4372        let vm = Vm::with_all()?;
4373        vm.import_code(
4374            "vm_dynamic_type_checks",
4375            br#"
4376            pub fn is_list_on_int() {
4377                let x = 42i64;
4378                x.is_list()
4379            }
4380
4381            pub fn is_map_on_int() {
4382                let x = 42i64;
4383                x.is_map()
4384            }
4385
4386            pub fn is_null_on_int() {
4387                let x = 42i64;
4388                x.is_null()
4389            }
4390            "#
4391            .to_vec(),
4392        )?;
4393
4394        let compiled = vm.get_fn("vm_dynamic_type_checks::is_list_on_int", &[])?;
4395        assert_eq!(compiled.ret_ty(), &Type::Bool);
4396        let is_list_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4397        assert!(!is_list_on_int());
4398
4399        let compiled = vm.get_fn("vm_dynamic_type_checks::is_map_on_int", &[])?;
4400        assert_eq!(compiled.ret_ty(), &Type::Bool);
4401        let is_map_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4402        assert!(!is_map_on_int());
4403
4404        let compiled = vm.get_fn("vm_dynamic_type_checks::is_null_on_int", &[])?;
4405        assert_eq!(compiled.ret_ty(), &Type::Bool);
4406        let is_null_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4407        assert!(!is_null_on_int());
4408        Ok(())
4409    }
4410
4411    #[test]
4412    fn void_and_null_are_false_in_boolean_context() -> anyhow::Result<()> {
4413        let vm = Vm::with_all()?;
4414        vm.import_code(
4415            "vm_void_bool_context",
4416            br#"
4417            pub fn run() {
4418                let items = [1i32, 2i32];
4419                let ok1 = !(items.push(3i32) && false);
4420                let ok2 = !(true && items.push(4i32));
4421                let ok3 = null || true;
4422                let ok4 = null || items.len() == 4;
4423                ok1 && ok2 && ok3 && ok4
4424            }
4425            "#
4426            .to_vec(),
4427        )?;
4428
4429        let compiled = vm.get_fn("vm_void_bool_context::run", &[])?;
4430        assert_eq!(compiled.ret_ty(), &Type::Bool);
4431        let run: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4432        assert!(run());
4433        Ok(())
4434    }
4435
4436    #[test]
4437    fn empty_for_loop_range_has_zero_iterations() -> anyhow::Result<()> {
4438        let vm = Vm::with_all()?;
4439        vm.import_code(
4440            "vm_empty_for_range",
4441            br#"
4442            pub fn empty_exclusive() {
4443                let count = 0i32;
4444                for i in 0..0 {
4445                    count += i;
4446                }
4447                count
4448            }
4449
4450            pub fn single_inclusive_iteration() {
4451                let count = 0i32;
4452                for i in 5..=5 {
4453                    count += i;
4454                }
4455                count
4456            }
4457            "#
4458            .to_vec(),
4459        )?;
4460
4461        // 无后缀 range 字面量(0..0 / 5..=5)默认 I64,累加器随复合赋值提升为 I64
4462        let compiled = vm.get_fn("vm_empty_for_range::empty_exclusive", &[])?;
4463        assert_eq!(compiled.ret_ty(), &Type::I64);
4464        let empty_exclusive: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4465        assert_eq!(empty_exclusive(), 0);
4466
4467        let compiled = vm.get_fn("vm_empty_for_range::single_inclusive_iteration", &[])?;
4468        assert_eq!(compiled.ret_ty(), &Type::I64);
4469        let single_inclusive: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4470        assert_eq!(single_inclusive(), 5);
4471        Ok(())
4472    }
4473
4474    #[test]
4475    fn for_loop_range_accepts_dynamic_i64_bounds() -> anyhow::Result<()> {
4476        let vm = Vm::with_all()?;
4477        vm.import_code(
4478            "vm_dynamic_for_range",
4479            br#"
4480            pub fn main() {
4481                let view = {};
4482                view.grid_min_x = -2i64;
4483                view.grid_max_x = 2i64;
4484
4485                let end_x = view.grid_max_x + 1i64;
4486                let count = 0i64;
4487
4488                for x in view.grid_min_x..end_x {
4489                    count += 1i64;
4490                }
4491
4492                count
4493            }
4494            "#
4495            .to_vec(),
4496        )?;
4497
4498        let compiled = vm.get_fn("vm_dynamic_for_range::main", &[])?;
4499        assert_eq!(compiled.ret_ty(), &Type::I64);
4500        let main: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4501        assert_eq!(main(), 5);
4502        Ok(())
4503    }
4504
4505    #[test]
4506    fn map_contains_key_on_non_existent_and_nested_keys() -> anyhow::Result<()> {
4507        let vm = Vm::with_all()?;
4508        vm.import_code(
4509            "vm_map_contains",
4510            br#"
4511            pub fn contains_existing(data) {
4512                data.contains("name")
4513            }
4514
4515            pub fn contains_missing(data) {
4516                data.contains("nothing")
4517            }
4518            "#
4519            .to_vec(),
4520        )?;
4521
4522        let compiled = vm.get_fn("vm_map_contains::contains_existing", &[Type::Any])?;
4523        assert_eq!(compiled.ret_ty(), &Type::Bool);
4524        let contains_existing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4525        let data = dynamic::map!("name"=> "test");
4526        assert!(contains_existing(&data));
4527
4528        let compiled = vm.get_fn("vm_map_contains::contains_missing", &[Type::Any])?;
4529        assert_eq!(compiled.ret_ty(), &Type::Bool);
4530        let contains_missing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4531        assert!(!contains_missing(&data));
4532        Ok(())
4533    }
4534
4535    #[test]
4536    fn list_pop_on_empty_list_returns_null() -> anyhow::Result<()> {
4537        let vm = Vm::with_all()?;
4538        vm.import_code(
4539            "vm_pop_empty",
4540            br#"
4541            pub fn pop_new_list() {
4542                let items = [];
4543                let value = items.pop();
4544                let still_empty = items.len() == 0;
4545                {value: value, empty: still_empty}
4546            }
4547
4548            pub fn pop_until_empty() {
4549                let items = [1i64, 2i64];
4550                items.pop();
4551                let last = items.pop();
4552                let drained = items.pop();
4553                {last: last, drained: drained}
4554            }
4555            "#
4556            .to_vec(),
4557        )?;
4558
4559        let compiled = vm.get_fn("vm_pop_empty::pop_new_list", &[])?;
4560        assert_eq!(compiled.ret_ty(), &Type::Any);
4561        let pop_new_list: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4562        let result = unsafe { &*pop_new_list() };
4563        assert!(result.get_dynamic("value").is_some_and(|v| v.is_null()));
4564        assert_eq!(result.get_dynamic("empty").and_then(|v| v.as_bool()), Some(true));
4565
4566        let compiled = vm.get_fn("vm_pop_empty::pop_until_empty", &[])?;
4567        assert_eq!(compiled.ret_ty(), &Type::Any);
4568        let pop_until_empty: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4569        let result = unsafe { &*pop_until_empty() };
4570        assert_eq!(result.get_dynamic("last").and_then(|v| v.as_int()), Some(1));
4571        assert!(result.get_dynamic("drained").is_some_and(|v| v.is_null()));
4572        Ok(())
4573    }
4574
4575    #[test]
4576    fn void_function_with_multiple_code_paths() -> anyhow::Result<()> {
4577        let vm = Vm::with_all()?;
4578        vm.import_code(
4579            "vm_void_multi_path",
4580            br#"
4581            pub fn log_if_positive(value: i64) {
4582                if value > 0 {
4583                    print(value);
4584                    return;
4585                }
4586                if value < 0 {
4587                    print(-value);
4588                    return;
4589                }
4590                print(0);
4591            }
4592            "#
4593            .to_vec(),
4594        )?;
4595
4596        let compiled = vm.get_fn("vm_void_multi_path::log_if_positive", &[Type::I64])?;
4597        assert!(compiled.ret_ty().is_void());
4598        Ok(())
4599    }
4600
4601    #[test]
4602    fn any_method_call_chain_on_returned_dynamic_value() -> anyhow::Result<()> {
4603        let vm = Vm::with_all()?;
4604        vm.import_code(
4605            "vm_any_method_chain",
4606            br#"
4607            pub fn get_tags(data) {
4608                let tags = data.tags;
4609                if tags.is_list() {
4610                    return tags.len();
4611                }
4612                0
4613            }
4614            "#
4615            .to_vec(),
4616        )?;
4617
4618        let compiled = vm.get_fn("vm_any_method_chain::get_tags", &[Type::Any])?;
4619        assert_eq!(compiled.ret_ty(), &Type::I64);
4620        let get_tags: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4621        let data = dynamic::map!("tags"=> Dynamic::list(vec!["a".into(), "b".into(), "c".into()]));
4622        assert_eq!(get_tags(&data), 3);
4623
4624        let empty_data = Dynamic::Null;
4625        assert_eq!(get_tags(&empty_data), 0);
4626        Ok(())
4627    }
4628
4629    #[test]
4630    fn infers_any_arg_function_return_before_body_compile() -> anyhow::Result<()> {
4631        let vm = Vm::with_all()?;
4632        vm.import_code(
4633            "vm_infer_any_arg_return",
4634            br#"
4635            pub fn caller(candidate) {
4636                let center = polygon_center(candidate.visualPolygon);
4637                center[0]
4638            }
4639
4640            pub fn polygon_center(point_list) {
4641                let total_x = 0;
4642                let total_y = 0;
4643                let count = 0;
4644                if point_list.is_list() {
4645                    for point in point_list {
4646                        if point.is_list() && point.len() >= 2 {
4647                            total_x += point[0];
4648                            total_y += point[1];
4649                            count += 1;
4650                        }
4651                    }
4652                }
4653                if count == 0 {
4654                    return [0, 0];
4655                }
4656                [total_x / count, total_y / count]
4657            }
4658            "#
4659            .to_vec(),
4660        )?;
4661
4662        let compiled = vm.get_fn("vm_infer_any_arg_return::caller", &[Type::Any])?;
4663        assert_eq!(compiled.ret_ty(), &Type::Any);
4664        let caller: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4665        let candidate = dynamic::map!(
4666            "visualPolygon"=> Dynamic::list(vec![
4667                Dynamic::list(vec![2i64.into(), 4i64.into()]),
4668                Dynamic::list(vec![6i64.into(), 8i64.into()]),
4669            ])
4670        );
4671        let result = unsafe { &*caller(&candidate) };
4672        assert_eq!(result.as_int(), Some(4));
4673        Ok(())
4674    }
4675
4676    #[test]
4677    fn recursive_factorial_keeps_static_return_type() -> anyhow::Result<()> {
4678        let vm = Vm::with_all()?;
4679        vm.import_code(
4680            "vm_recursive_factorial",
4681            br#"
4682            fn factorial(n: i64) {
4683                if n <= 1 {
4684                    return 1;
4685                }
4686                n * factorial(n - 1)
4687            }
4688
4689            pub fn run(n: i64) {
4690                factorial(n)
4691            }
4692            "#
4693            .to_vec(),
4694        )?;
4695
4696        let compiled = vm.get_fn("vm_recursive_factorial::run", &[Type::I64])?;
4697        assert_eq!(compiled.ret_ty(), &Type::I64);
4698        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4699        assert_eq!(run(5), 120);
4700        Ok(())
4701    }
4702
4703    #[test]
4704    fn explicit_const_generic_function_calls_generate_distinct_variants() -> anyhow::Result<()> {
4705        let vm = Vm::with_all()?;
4706        vm.import_code(
4707            "vm_generic_const_variants",
4708            br#"
4709            fn value<N>() {
4710                N
4711            }
4712
4713            pub fn two() {
4714                value::<2>()
4715            }
4716
4717            pub fn three() {
4718                value::<3>()
4719            }
4720            "#
4721            .to_vec(),
4722        )?;
4723
4724        let compiled = vm.get_fn("vm_generic_const_variants::two", &[])?;
4725        assert_eq!(compiled.ret_ty(), &Type::I32);
4726        let two: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4727        assert_eq!(two(), 2);
4728
4729        let compiled = vm.get_fn("vm_generic_const_variants::three", &[])?;
4730        assert_eq!(compiled.ret_ty(), &Type::I32);
4731        let three: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4732        assert_eq!(three(), 3);
4733        Ok(())
4734    }
4735
4736    #[test]
4737    fn generic_function_body_resolves_private_generic_helper_after_import() -> anyhow::Result<()> {
4738        let vm = Vm::with_all()?;
4739        vm.import_code(
4740            "vm_generic_private_helper",
4741            br#"
4742            fn helper<N>() {
4743                N
4744            }
4745
4746            pub fn bench<N>() {
4747                helper::<N>()
4748            }
4749            "#
4750            .to_vec(),
4751        )?;
4752
4753        let compiled = vm.get_fn_with_params("vm_generic_private_helper::bench", &[], &[Type::ConstInt(7)])?;
4754        assert_eq!(compiled.ret_ty(), &Type::I32);
4755        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4756        assert_eq!(run(), 7);
4757        Ok(())
4758    }
4759
4760    #[test]
4761    fn const_generic_repeat_array_initializes_all_items() -> anyhow::Result<()> {
4762        let vm = Vm::with_all()?;
4763        vm.import_code(
4764            "vm_generic_repeat_array",
4765            br#"
4766            fn bench<N>() {
4767                let is_prime = [true; N];
4768                is_prime[0] = false;
4769                is_prime[1] = false;
4770                let count = 0i64;
4771                for p in 2i64..N {
4772                    if is_prime[p] == true {
4773                        count = count + 1;
4774                        let step = p;
4775                        let j = p * p;
4776                        while j < N {
4777                            is_prime[j] = false;
4778                            j = j + step;
4779                        }
4780                    }
4781                }
4782                count
4783            }
4784
4785            pub fn run() {
4786                bench::<10>()
4787            }
4788
4789            pub fn run_1000() {
4790                bench::<1000>()
4791            }
4792
4793            pub fn run_100000() {
4794                bench::<100000>()
4795            }
4796            "#
4797            .to_vec(),
4798        )?;
4799
4800        let compiled = vm.get_fn("vm_generic_repeat_array::run", &[])?;
4801        assert_eq!(compiled.ret_ty(), &Type::I64);
4802        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4803        assert_eq!(run(), 4);
4804
4805        let compiled = vm.get_fn("vm_generic_repeat_array::run_1000", &[])?;
4806        assert_eq!(compiled.ret_ty(), &Type::I64);
4807        let run_1000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4808        assert_eq!(run_1000(), 168);
4809
4810        let compiled = vm.get_fn("vm_generic_repeat_array::run_100000", &[])?;
4811        assert_eq!(compiled.ret_ty(), &Type::I64);
4812        let run_100000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4813        assert_eq!(run_100000(), 9592);
4814        Ok(())
4815    }
4816
4817    #[test]
4818    fn repeat_array_initializes_scalar_patterns() -> anyhow::Result<()> {
4819        let vm = Vm::with_all()?;
4820        vm.import_code(
4821            "vm_repeat_scalar_patterns",
4822            br#"
4823            pub fn count_true() {
4824                let items = [true; 100000];
4825                let count = 0i64;
4826                for idx in 0i64..100000 {
4827                    if items[idx] == true {
4828                        count = count + 1;
4829                    }
4830                }
4831                count
4832            }
4833
4834            pub fn i32_pair() {
4835                let items = [-7i32; 1000];
4836                items[0i64] + items[999i64]
4837            }
4838
4839            pub fn i64_pair() {
4840                let items = [1234567890123i64; 1000];
4841                items[0i64] + items[999i64]
4842            }
4843
4844            pub fn f64_pair() {
4845                let items = [1.5f64; 1000];
4846                items[0i64] + items[999i64]
4847            }
4848            "#
4849            .to_vec(),
4850        )?;
4851
4852        let compiled = vm.get_fn("vm_repeat_scalar_patterns::count_true", &[])?;
4853        assert_eq!(compiled.ret_ty(), &Type::I64);
4854        let count_true: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4855        assert_eq!(count_true(), 100000);
4856
4857        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i32_pair", &[])?;
4858        assert_eq!(compiled.ret_ty(), &Type::I32);
4859        let i32_pair: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4860        assert_eq!(i32_pair(), -14);
4861
4862        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i64_pair", &[])?;
4863        assert_eq!(compiled.ret_ty(), &Type::I64);
4864        let i64_pair: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4865        assert_eq!(i64_pair(), 2469135780246);
4866
4867        let compiled = vm.get_fn("vm_repeat_scalar_patterns::f64_pair", &[])?;
4868        assert_eq!(compiled.ret_ty(), &Type::F64);
4869        let f64_pair: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
4870        assert_eq!(f64_pair(), 3.0);
4871        Ok(())
4872    }
4873
4874    #[test]
4875    fn bool_array_store_normalizes_condition_values() -> anyhow::Result<()> {
4876        let vm = Vm::with_all()?;
4877        vm.import_code(
4878            "vm_bool_array_store",
4879            br#"
4880            pub fn run() {
4881                let items = [false; 4];
4882                items[1] = 3i64 > 2i64;
4883                items[2] = 3i64 < 2i64;
4884                if items[1] == true && items[2] == false {
4885                    1i64
4886                } else {
4887                    0i64
4888                }
4889            }
4890            "#
4891            .to_vec(),
4892        )?;
4893
4894        let compiled = vm.get_fn("vm_bool_array_store::run", &[])?;
4895        assert_eq!(compiled.ret_ty(), &Type::I64);
4896        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4897        assert_eq!(run(), 1);
4898        Ok(())
4899    }
4900
4901    #[test]
4902    fn bool_array_large_sequential_writes() -> anyhow::Result<()> {
4903        let vm = Vm::with_all()?;
4904        vm.import_code(
4905            "vm_bool_array_large_writes",
4906            br#"
4907            pub fn run() {
4908                let items = [true; 100000];
4909                for idx in 0i64..100000 {
4910                    items[idx] = false;
4911                }
4912                let count = 0i64;
4913                for idx in 0i64..100000 {
4914                    if items[idx] == false {
4915                        count = count + 1;
4916                    }
4917                }
4918                count
4919            }
4920            "#
4921            .to_vec(),
4922        )?;
4923
4924        let compiled = vm.get_fn("vm_bool_array_large_writes::run", &[])?;
4925        assert_eq!(compiled.ret_ty(), &Type::I64);
4926        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4927        assert_eq!(run(), 100000);
4928        Ok(())
4929    }
4930
4931    #[test]
4932    fn bool_array_sieve_style_indices_stay_in_bounds() -> anyhow::Result<()> {
4933        let vm = Vm::with_all()?;
4934        vm.import_code(
4935            "vm_bool_array_sieve_indices",
4936            br#"
4937            pub fn run() {
4938                let items = [true; 100000];
4939                let writes = 0i64;
4940                for p in 2i64..100000 {
4941                    let step = p;
4942                    let j = p * p;
4943                    while j < 100000 {
4944                        items[j] = false;
4945                        writes = writes + 1;
4946                        j = j + step;
4947                    }
4948                }
4949                writes
4950            }
4951            "#
4952            .to_vec(),
4953        )?;
4954
4955        let compiled = vm.get_fn("vm_bool_array_sieve_indices::run", &[])?;
4956        assert_eq!(compiled.ret_ty(), &Type::I64);
4957        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4958        assert!(run() > 0);
4959        Ok(())
4960    }
4961
4962    #[test]
4963    fn sieve_style_indices_compute_in_bounds_without_array_write() -> anyhow::Result<()> {
4964        let vm = Vm::with_all()?;
4965        vm.import_code(
4966            "vm_sieve_indices_no_write",
4967            br#"
4968            pub fn run() {
4969                let max_j = 0i64;
4970                for p in 2i64..100000 {
4971                    let step = p;
4972                    let j = p * p;
4973                    while j < 100000 {
4974                        if j < 0i64 {
4975                            return -1i64;
4976                        }
4977                        if j > max_j {
4978                            max_j = j;
4979                        }
4980                        j = j + step;
4981                    }
4982                }
4983                max_j
4984            }
4985            "#
4986            .to_vec(),
4987        )?;
4988
4989        let compiled = vm.get_fn("vm_sieve_indices_no_write::run", &[])?;
4990        assert_eq!(compiled.ret_ty(), &Type::I64);
4991        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4992        assert_eq!(run(), 99999);
4993        Ok(())
4994    }
4995
4996    #[test]
4997    fn dynamic_list_index_sum_uses_static_accumulator_type() -> anyhow::Result<()> {
4998        let vm = Vm::with_all()?;
4999        vm.import_code(
5000            "vm_dynamic_index_sum",
5001            br#"
5002            pub fn sum_list(n: i64) {
5003                let l = [];
5004                for i in 0..n {
5005                    l.push(i);
5006                }
5007                let sum = 0i64;
5008                for j in 0..n {
5009                    sum = sum + l[j];
5010                }
5011                sum
5012            }
5013            "#
5014            .to_vec(),
5015        )?;
5016
5017        let compiled = vm.get_fn("vm_dynamic_index_sum::sum_list", &[Type::I64])?;
5018        let sum_list_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_dynamic_index_sum::sum_list")?;
5019        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_list_id, &[], &[Type::I64]);
5020        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I64)), "local type hints: {:?}", hints);
5021        assert_eq!(compiled.ret_ty(), &Type::I64);
5022        let sum_list: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5023        assert_eq!(sum_list(1000), 499500);
5024        Ok(())
5025    }
5026
5027    #[test]
5028    fn loop_pushed_list_is_typed_vector() -> anyhow::Result<()> {
5029        let vm = Vm::with_all()?;
5030        vm.import_code(
5031            "vm_loop_pushed_list",
5032            br#"
5033            pub fn make(n: i64) {
5034                let l = [];
5035                for i in 0..n {
5036                    l.push(i);
5037                }
5038                l
5039            }
5040            "#
5041            .to_vec(),
5042        )?;
5043        let compiled = vm.get_fn("vm_loop_pushed_list::make", &[Type::I64])?;
5044        let make: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5045        let result = unsafe { &*make(3) };
5046        assert!(matches!(result, Dynamic::VecI64(v) if v == &vec![0, 1, 2]), "expected flat VecI64, got: {:?}", result);
5047        Ok(())
5048    }
5049
5050    #[test]
5051    fn inferred_empty_list_uses_typed_dynamic_vector() -> anyhow::Result<()> {
5052        let vm = Vm::with_all()?;
5053        vm.import_code(
5054            "vm_inferred_typed_list",
5055            br#"
5056            pub fn make() {
5057                let l = [];
5058                l.push(1i64);
5059                l
5060            }
5061            "#
5062            .to_vec(),
5063        )?;
5064
5065        let compiled = vm.get_fn("vm_inferred_typed_list::make", &[])?;
5066        assert_eq!(compiled.ret_ty(), &Type::Any);
5067        let make: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5068        let result = unsafe { &*make() };
5069        assert!(matches!(result, Dynamic::VecI64(values) if values == &vec![1]), "result: {:?}", result);
5070        Ok(())
5071    }
5072
5073    #[test]
5074    fn for_in_iterates_list_filled_in_same_function() -> anyhow::Result<()> {
5075        let vm = Vm::with_all()?;
5076        vm.import_code(
5077            "vm_for_in_local_pushed_list",
5078            br#"
5079            pub fn sum_i32_items() {
5080                let items = [];
5081                items.push(6000i32);
5082                items.push(4000i32);
5083                let total = 0i32;
5084                for item in items {
5085                    total += item;
5086                }
5087                total
5088            }
5089
5090            pub fn sum_split_bps() {
5091                let splits = [];
5092                splits.push({ bps: "6000" });
5093                splits.push({ bps: 4000 });
5094                let total = 0i32;
5095                let count = 0i32;
5096                for split in splits {
5097                    total += split.bps as i32;
5098                    count += 1i32;
5099                }
5100                total + count
5101            }
5102            "#
5103            .to_vec(),
5104        )?;
5105
5106        let compiled = vm.get_fn("vm_for_in_local_pushed_list::sum_i32_items", &[])?;
5107        assert_eq!(compiled.ret_ty(), &Type::I32);
5108        let sum_i32_items: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5109        assert_eq!(sum_i32_items(), 10000);
5110
5111        let compiled = vm.get_fn("vm_for_in_local_pushed_list::sum_split_bps", &[])?;
5112        assert_eq!(compiled.ret_ty(), &Type::I32);
5113        let sum_split_bps: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5114        assert_eq!(sum_split_bps(), 10002);
5115        Ok(())
5116    }
5117
5118    #[test]
5119    fn inferred_list_shortcuts_cover_scalar_types() -> anyhow::Result<()> {
5120        let vm = Vm::with_all()?;
5121        vm.import_code(
5122            "vm_inferred_list_shortcuts",
5123            br#"
5124            pub fn second_bool() {
5125                let l = [];
5126                l.push(true);
5127                l.push(false);
5128                l[1]
5129            }
5130
5131            pub fn first_u8() {
5132                let l = [];
5133                l.push(7u8);
5134                l[0]
5135            }
5136
5137            pub fn sum_u8_for_in() {
5138                let l = [];
5139                l.push(7u8);
5140                l.push(8u8);
5141                let sum = 0i64;
5142                for item in l {
5143                    sum = sum + item as i64;
5144                }
5145                sum
5146            }
5147
5148            pub fn count_bool_for_in() {
5149                let l = [];
5150                l.push(true);
5151                l.push(false);
5152                l.push(true);
5153                let count = 0i64;
5154                for item in l {
5155                    if item {
5156                        count += 1i64;
5157                    }
5158                }
5159                count
5160            }
5161
5162            pub fn sum_i32(n: i64) {
5163                let l = [];
5164                for i in 0..n {
5165                    l.push(i as i32);
5166                }
5167                let sum = 0i32;
5168                for j in 0..n {
5169                    sum = sum + l[j];
5170                }
5171                sum
5172            }
5173
5174            pub fn sum_f32(n: i64) {
5175                let l = [];
5176                for i in 0..n {
5177                    l.push(i as f32);
5178                }
5179                let sum = 0f32;
5180                for j in 0..n {
5181                    sum = sum + l[j];
5182                }
5183                sum
5184            }
5185
5186            pub fn second_str() {
5187                let l = [];
5188                l.push("first");
5189                l.push("second");
5190                l[1]
5191            }
5192            "#
5193            .to_vec(),
5194        )?;
5195
5196        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_bool", &[])?;
5197        let second_bool_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::second_bool")?;
5198        let hints = vm.jit.write().compiler.inferred_local_type_hints(second_bool_id, &[], &[]);
5199        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Bool)), "bool local type hints: {:?}", hints);
5200        assert_eq!(compiled.ret_ty(), &Type::Bool);
5201        let second_bool: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5202        assert!(!second_bool());
5203
5204        let compiled = vm.get_fn("vm_inferred_list_shortcuts::first_u8", &[])?;
5205        let first_u8_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::first_u8")?;
5206        let hints = vm.jit.write().compiler.inferred_local_type_hints(first_u8_id, &[], &[]);
5207        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::U8)), "u8 local type hints: {:?}", hints);
5208        assert_eq!(compiled.ret_ty(), &Type::U8);
5209        let first_u8: extern "C" fn() -> u8 = unsafe { std::mem::transmute(compiled.ptr()) };
5210        assert_eq!(first_u8(), 7);
5211
5212        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_u8_for_in", &[])?;
5213        assert_eq!(compiled.ret_ty(), &Type::I64);
5214        let sum_u8_for_in: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5215        assert_eq!(sum_u8_for_in(), 15);
5216
5217        let compiled = vm.get_fn("vm_inferred_list_shortcuts::count_bool_for_in", &[])?;
5218        assert_eq!(compiled.ret_ty(), &Type::I64);
5219        let count_bool_for_in: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5220        assert_eq!(count_bool_for_in(), 2);
5221
5222        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_i32", &[Type::I64])?;
5223        let sum_i32_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::sum_i32")?;
5224        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_i32_id, &[], &[Type::I64]);
5225        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I32)), "i32 local type hints: {:?}", hints);
5226        assert_eq!(compiled.ret_ty(), &Type::I32);
5227        let sum_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5228        assert_eq!(sum_i32(100), 4950);
5229
5230        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_f32", &[Type::I64])?;
5231        let sum_f32_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::sum_f32")?;
5232        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_f32_id, &[], &[Type::I64]);
5233        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::F32)), "f32 local type hints: {:?}", hints);
5234        assert_eq!(compiled.ret_ty(), &Type::F32);
5235        let sum_f32: extern "C" fn(i64) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
5236        assert_eq!(sum_f32(10), 45.0);
5237
5238        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_str", &[])?;
5239        let second_str_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::second_str")?;
5240        let hints = vm.jit.write().compiler.inferred_local_type_hints(second_str_id, &[], &[]);
5241        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Str)), "str local type hints: {:?}", hints);
5242        assert_eq!(compiled.ret_ty(), &Type::Str);
5243        let second_str: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5244        let result = unsafe { &*second_str() };
5245        assert_eq!(result.as_str(), "second");
5246        Ok(())
5247    }
5248
5249    #[test]
5250    fn inferred_list_supports_bracket_set_idx() -> anyhow::Result<()> {
5251        let vm = Vm::with_all()?;
5252        vm.import_code(
5253            "vm_inferred_list_set_idx",
5254            br#"
5255            pub fn swap_first_two() {
5256                let items = [];
5257                items.push(1i64);
5258                items.push(2i64);
5259                let j = 0i64;
5260                let a = items[j];
5261                let b = items[j + 1];
5262                items[j] = b;
5263                items[j + 1] = a;
5264                items[0] * 10i64 + items[1]
5265            }
5266
5267            pub fn replace_string() {
5268                let items = [];
5269                items.push("old");
5270                items[0] = "new";
5271                items[0]
5272            }
5273            "#
5274            .to_vec(),
5275        )?;
5276
5277        let compiled = vm.get_fn("vm_inferred_list_set_idx::swap_first_two", &[])?;
5278        assert_eq!(compiled.ret_ty(), &Type::I64);
5279        let swap_first_two: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5280        assert_eq!(swap_first_two(), 21);
5281
5282        let compiled = vm.get_fn("vm_inferred_list_set_idx::replace_string", &[])?;
5283        assert_eq!(compiled.ret_ty(), &Type::Str);
5284        let replace_string: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5285        let result = unsafe { &*replace_string() };
5286        assert_eq!(result.as_str(), "new");
5287        Ok(())
5288    }
5289
5290    #[test]
5291    fn root_get_returns_null_for_missing_key_which_compares_correctly() -> anyhow::Result<()> {
5292        let vm = Vm::with_all()?;
5293        vm.import_code(
5294            "vm_root_get_missing",
5295            br#"
5296            pub fn check_missing() {
5297                let existing = root::get("local/vm_root_get_missing_test");
5298                if existing.is_map() {
5299                    return false;
5300                }
5301                true
5302            }
5303            "#
5304            .to_vec(),
5305        )?;
5306
5307        let compiled = vm.get_fn("vm_root_get_missing::check_missing", &[])?;
5308        assert_eq!(compiled.ret_ty(), &Type::Bool);
5309        let check_missing: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5310        assert!(check_missing());
5311        Ok(())
5312    }
5313
5314    #[test]
5315    fn map_get_key_on_null_map_returns_null() -> anyhow::Result<()> {
5316        let vm = Vm::with_all()?;
5317        vm.import_code(
5318            "vm_get_key_null_map",
5319            br#"
5320            pub fn get_key_null(data) {
5321                data.get_key("missing")
5322            }
5323            "#
5324            .to_vec(),
5325        )?;
5326
5327        let compiled = vm.get_fn("vm_get_key_null_map::get_key_null", &[Type::Any])?;
5328        assert_eq!(compiled.ret_ty(), &Type::Any);
5329        let get_key_null: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5330
5331        let data_map = dynamic::map!("exists"=> 1i64);
5332        let missing = unsafe { &*get_key_null(&data_map) };
5333        assert!(missing.is_null());
5334
5335        let null = Dynamic::Null;
5336        let result = unsafe { &*get_key_null(&null) };
5337        assert!(result.is_null());
5338        Ok(())
5339    }
5340
5341    #[test]
5342    fn keys_on_empty_map_returns_empty_list() -> anyhow::Result<()> {
5343        let vm = Vm::with_all()?;
5344        vm.import_code(
5345            "vm_keys_empty_map",
5346            br#"
5347            pub fn empty_map_keys() {
5348                let data = {};
5349                data.keys().len()
5350            }
5351            "#
5352            .to_vec(),
5353        )?;
5354
5355        let compiled = vm.get_fn("vm_keys_empty_map::empty_map_keys", &[])?;
5356        assert_eq!(compiled.ret_ty(), &Type::I32);
5357        let empty_map_keys: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5358        assert_eq!(empty_map_keys(), 0);
5359        Ok(())
5360    }
5361
5362    #[test]
5363    fn cast_between_all_integer_widths() -> anyhow::Result<()> {
5364        let vm = Vm::with_all()?;
5365        vm.import_code(
5366            "vm_cast_integer_widths",
5367            br#"
5368            pub fn i64_to_i32(value: i64) {
5369                value as i32
5370            }
5371
5372            pub fn i32_to_i64(value: i32) {
5373                value as i64
5374            }
5375
5376            pub fn u32_to_i64(value: u32) {
5377                value as i64
5378            }
5379            "#
5380            .to_vec(),
5381        )?;
5382
5383        let compiled = vm.get_fn("vm_cast_integer_widths::i64_to_i32", &[Type::I64])?;
5384        assert_eq!(compiled.ret_ty(), &Type::I32);
5385        let i64_to_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5386        assert_eq!(i64_to_i32(42), 42);
5387
5388        let compiled = vm.get_fn("vm_cast_integer_widths::i32_to_i64", &[Type::I32])?;
5389        assert_eq!(compiled.ret_ty(), &Type::I64);
5390        let i32_to_i64: extern "C" fn(i32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5391        assert_eq!(i32_to_i64(-1), -1);
5392
5393        let compiled = vm.get_fn("vm_cast_integer_widths::u32_to_i64", &[Type::U32])?;
5394        assert_eq!(compiled.ret_ty(), &Type::I64);
5395        let u32_to_i64: extern "C" fn(u32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5396        assert_eq!(u32_to_i64(42), 42);
5397        Ok(())
5398    }
5399
5400    #[test]
5401    fn boolean_literals_in_complex_expression_trees() -> anyhow::Result<()> {
5402        let vm = Vm::with_all()?;
5403        vm.import_code(
5404            "vm_complex_boolean",
5405            br#"
5406            pub fn exclusive_or(a: bool, b: bool) {
5407                (a && !b) || (!a && b)
5408            }
5409
5410            pub fn implies(a: bool, b: bool) {
5411                !a || b
5412            }
5413            "#
5414            .to_vec(),
5415        )?;
5416
5417        let compiled = vm.get_fn("vm_complex_boolean::exclusive_or", &[Type::Bool, Type::Bool])?;
5418        assert_eq!(compiled.ret_ty(), &Type::Bool);
5419        let exclusive_or: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5420        assert!(exclusive_or(true, false));
5421        assert!(exclusive_or(false, true));
5422        assert!(!exclusive_or(true, true));
5423        assert!(!exclusive_or(false, false));
5424
5425        let compiled = vm.get_fn("vm_complex_boolean::implies", &[Type::Bool, Type::Bool])?;
5426        assert_eq!(compiled.ret_ty(), &Type::Bool);
5427        let implies: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5428        assert!(implies(false, true));
5429        assert!(implies(false, false));
5430        assert!(implies(true, true));
5431        assert!(!implies(true, false));
5432        Ok(())
5433    }
5434
5435    #[test]
5436    fn concrete_struct_method_returning_self_type() -> anyhow::Result<()> {
5437        let vm = Vm::with_all()?;
5438        vm.import_code(
5439            "vm_struct_method_self",
5440            br#"
5441            pub struct Vec3 {
5442                x: f64,
5443                y: f64,
5444                z: f64,
5445            }
5446
5447            impl Vec3 {
5448                pub fn add(self: Vec3, other: Vec3) {
5449                    Vec3{x: self.x + other.x, y: self.y + other.y, z: self.z + other.z}
5450                }
5451            }
5452
5453            pub fn run() {
5454                let v1 = Vec3{x: 1.0f64, y: 2.0f64, z: 3.0f64};
5455                let v2 = Vec3{x: 4.0f64, y: 5.0f64, z: 6.0f64};
5456                let sum = v1.add(v2);
5457                sum.x + sum.y + sum.z
5458            }
5459            "#
5460            .to_vec(),
5461        )?;
5462
5463        let compiled = vm.get_fn("vm_struct_method_self::run", &[])?;
5464        assert_eq!(compiled.ret_ty(), &Type::F64);
5465        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
5466        assert_eq!(run(), 21.0);
5467        Ok(())
5468    }
5469
5470    #[test]
5471    fn deep_nested_struct_access_with_multiple_field_levels() -> anyhow::Result<()> {
5472        let vm = Vm::with_all()?;
5473        vm.import_code(
5474            "vm_deep_nested_struct",
5475            br#"
5476            pub struct A {
5477                value: i64,
5478            }
5479
5480            pub struct B {
5481                a: A,
5482            }
5483
5484            pub struct C {
5485                b: B,
5486            }
5487
5488            pub fn direct_access() {
5489                let c = C{b: B{a: A{value: 99}}};
5490                c.b.a.value
5491            }
5492
5493            pub fn via_variable() {
5494                let c = C{b: B{a: A{value: 77}}};
5495                let b = c.b;
5496                let a = b.a;
5497                a.value
5498            }
5499            "#
5500            .to_vec(),
5501        )?;
5502
5503        let compiled = vm.get_fn("vm_deep_nested_struct::direct_access", &[])?;
5504        assert_eq!(compiled.ret_ty(), &Type::I64);
5505        let direct_access: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5506        assert_eq!(direct_access(), 99);
5507
5508        let compiled = vm.get_fn("vm_deep_nested_struct::via_variable", &[])?;
5509        assert_eq!(compiled.ret_ty(), &Type::I64);
5510        let via_variable: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5511        assert_eq!(via_variable(), 77);
5512        Ok(())
5513    }
5514
5515    #[test]
5516    fn array_index_with_dynamic_value_via_method() -> anyhow::Result<()> {
5517        let vm = Vm::with_all()?;
5518        vm.import_code(
5519            "vm_array_idx_dynamic",
5520            br#"
5521            pub fn get_by_idx(list, idx) {
5522                list.get_idx(idx)
5523            }
5524            "#
5525            .to_vec(),
5526        )?;
5527
5528        let compiled = vm.get_fn("vm_array_idx_dynamic::get_by_idx", &[Type::Any, Type::I64])?;
5529        assert_eq!(compiled.ret_ty(), &Type::Any);
5530        let get_by_idx: extern "C" fn(*const Dynamic, i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5531
5532        let list = Dynamic::list(vec!["a".into(), "b".into()]);
5533        let first = unsafe { &*get_by_idx(&list, 0) };
5534        assert_eq!(first.as_str(), "a");
5535
5536        let out = unsafe { &*get_by_idx(&list, 10) };
5537        assert!(out.is_null());
5538        Ok(())
5539    }
5540
5541    #[test]
5542    fn dynamic_field_access_with_optional_or_fallback() -> anyhow::Result<()> {
5543        let vm = Vm::with_all()?;
5544        vm.import_code(
5545            "vm_dynamic_or_fallback",
5546            br#"
5547            pub fn with_fallback(data) {
5548                if data.contains("name") { data.name } else { "unknown" }
5549            }
5550
5551            pub fn with_fallback_missing(data) {
5552                if data.contains("nickname") { data.nickname } else { "unnamed" }
5553            }
5554            "#
5555            .to_vec(),
5556        )?;
5557
5558        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback", &[Type::Any])?;
5559        assert_eq!(compiled.ret_ty(), &Type::Any);
5560        let with_fallback: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5561        let data = dynamic::map!("name"=> "Alice");
5562        let result = unsafe { &*with_fallback(&data) };
5563        assert_eq!(result.as_str(), "Alice");
5564
5565        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback_missing", &[Type::Any])?;
5566        let with_fallback_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5567        let result = unsafe { &*with_fallback_missing(&data) };
5568        assert_eq!(result.as_str(), "unnamed");
5569        Ok(())
5570    }
5571
5572    #[test]
5573    fn for_in_loop_iterates_over_list_and_map_directly() -> anyhow::Result<()> {
5574        let vm = Vm::with_all()?;
5575        vm.import_code(
5576            "vm_for_in_collection",
5577            br#"
5578            pub fn sum_list(items) {
5579                let total = 0i64;
5580                for item in items {
5581                    total = total + 1;
5582                }
5583                total
5584            }
5585
5586            pub fn count_map_keys(data) {
5587                let count = 0i64;
5588                for key in data.keys() {
5589                    count = count + 1;
5590                }
5591                count
5592            }
5593
5594            pub fn for_in_list_works(items) {
5595                let exists = false;
5596                for item in items {
5597                    exists = true;
5598                }
5599                exists
5600            }
5601
5602            pub fn for_in_map_values_works(data) {
5603                let exists = false;
5604                for value in data {
5605                    exists = true;
5606                }
5607                exists
5608            }
5609            "#
5610            .to_vec(),
5611        )?;
5612
5613        let compiled = vm.get_fn("vm_for_in_collection::sum_list", &[Type::Any])?;
5614        assert_eq!(compiled.ret_ty(), &Type::I64);
5615        let sum_list: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5616        let items = Dynamic::list(vec![Dynamic::from(1i64), Dynamic::from(2i64), Dynamic::from(3i64)]);
5617        assert_eq!(sum_list(&items), 3);
5618
5619        let data = dynamic::map!("x"=> 1i64, "y"=> 2i64);
5620        let compiled = vm.get_fn("vm_for_in_collection::count_map_keys", &[Type::Any])?;
5621        assert_eq!(compiled.ret_ty(), &Type::I64);
5622        let count_map_keys: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5623        assert_eq!(count_map_keys(&data), 2);
5624
5625        let compiled = vm.get_fn("vm_for_in_collection::for_in_list_works", &[Type::Any])?;
5626        assert_eq!(compiled.ret_ty(), &Type::Bool);
5627        let for_in_list_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5628        let empty = Dynamic::list(Vec::new());
5629        assert!(!for_in_list_works(&empty));
5630        assert!(for_in_list_works(&items));
5631
5632        let compiled = vm.get_fn("vm_for_in_collection::for_in_map_values_works", &[Type::Any])?;
5633        assert_eq!(compiled.ret_ty(), &Type::Bool);
5634        let for_in_map_values_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5635        let empty_map = dynamic::map!();
5636        assert!(!for_in_map_values_works(&empty_map));
5637        assert!(for_in_map_values_works(&data));
5638
5639        Ok(())
5640    }
5641
5642    #[test]
5643    fn concurrent_100_threads_no_memory_leak() -> anyhow::Result<()> {
5644        let vm = Vm::with_all()?;
5645        vm.import_code(
5646            "vm_stress",
5647            br#"
5648            pub fn heavy_alloc(idx: i64) {
5649                let items = [];
5650                let i = 0;
5651                while i < 50 {
5652                    items.push({
5653                        id: i + idx,
5654                        name: "item-" + i,
5655                        tags: ["tag-a", "tag-b", "tag-c"],
5656                        meta: {
5657                            created: 1234567890i64,
5658                            score: (i * 3.14f64) as i64,
5659                            extra: "prefix/" + i + "/" + idx
5660                        }
5661                    });
5662                    i = i + 1;
5663                }
5664                items
5665            }
5666
5667            pub fn string_concat_stress() {
5668                let i = 0;
5669                let result = "";
5670                while i < 200 {
5671                    result = result + "data-" + i + ",";
5672                    i = i + 1;
5673                }
5674                result
5675            }
5676            "#
5677            .to_vec(),
5678        )?;
5679
5680        let (heavy_ptr, _) = vm.get_fn_ptr("vm_stress::heavy_alloc", &[Type::I64])?;
5681        let (concat_ptr, _) = vm.get_fn_ptr("vm_stress::string_concat_stress", &[])?;
5682
5683        let threads: usize = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).max(100);
5684        let iters_per_thread = 200;
5685        let total_calls = threads * iters_per_thread * 2;
5686
5687        let before = current_rss_kb();
5688        eprintln!("threads={threads} iters_per_thread={iters_per_thread} total_calls={total_calls} rss_before={before}KB");
5689
5690        // Round 1: first concurrent execution (arena warm-up)
5691        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5692        let r1 = current_rss_kb();
5693        eprintln!("rss_after_round1={r1}KB");
5694
5695        // Round 2: should stabilize (no unbounded growth)
5696        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5697        let r2 = current_rss_kb();
5698        eprintln!("rss_after_round2={r2}KB");
5699
5700        // Round 3: final check
5701        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5702        let r3 = current_rss_kb();
5703        eprintln!("rss_after_round3={r3}KB");
5704
5705        // Round 4: confirm that any one-time allocator growth has settled.
5706        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5707        let r4 = current_rss_kb();
5708        eprintln!("rss_after_round4={r4}KB");
5709
5710        // Allocator/arena growth is allowed during warm-up, but it must settle.
5711        let d12 = r2.saturating_sub(r1);
5712        let d23 = r3.saturating_sub(r2);
5713        let d34 = r4.saturating_sub(r3);
5714        eprintln!("delta_r1→r2={d12}KB delta_r2→r3={d23}KB delta_r3→r4={d34}KB");
5715
5716        // The last interval must be small to prove the growth is not continuing.
5717        let max_growth_kb = 20 * 1024;
5718        assert!(d34 < max_growth_kb, "memory keeps growing after allocator warm-up: round1={r1} round2={r2} round3={r3} round4={r4} delta12={d12}KB delta23={d23}KB delta34={d34}KB (max stable growth={max_growth_kb}KB)");
5719
5720        Ok(())
5721    }
5722
5723    fn run_stress_round(threads: usize, iters: usize, heavy_ptr: usize, concat_ptr: usize) {
5724        std::thread::scope(|scope| {
5725            let mut handles = Vec::with_capacity(threads);
5726            for t in 0..threads {
5727                let heavy_ptr = heavy_ptr;
5728                let concat_ptr = concat_ptr;
5729                handles.push(scope.spawn(move || {
5730                    let heavy_fn: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(heavy_ptr as *const u8) };
5731                    let concat_fn: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(concat_ptr as *const u8) };
5732                    for i in 0..iters {
5733                        // heavy_alloc: drop returned value to free heap allocation
5734                        let r_ptr = heavy_fn((t * iters + i) as i64);
5735                        assert!(!r_ptr.is_null());
5736                        unsafe {
5737                            let r = &*r_ptr;
5738                            assert!(r.len() > 0, "heavy_alloc returned empty list");
5739                            drop(Box::from_raw(r_ptr as *mut Dynamic));
5740                        }
5741
5742                        // concat: same, drop returned value
5743                        let s_ptr = concat_fn();
5744                        assert!(!s_ptr.is_null());
5745                        unsafe {
5746                            let s = &*s_ptr;
5747                            assert!(s.len() > 0, "string_concat_stress returned empty");
5748                            drop(Box::from_raw(s_ptr as *mut Dynamic));
5749                        }
5750                    }
5751                }));
5752            }
5753            for h in handles {
5754                h.join().unwrap();
5755            }
5756        });
5757    }
5758
5759    fn current_rss_kb() -> u64 {
5760        // macOS: use ps
5761        let pid = std::process::id();
5762        if let Ok(output) = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "rss="]).output() {
5763            if let Ok(s) = String::from_utf8(output.stdout) {
5764                if let Some(kb) = s.trim().parse::<u64>().ok() {
5765                    return kb;
5766                }
5767            }
5768        }
5769        // Linux fallback: /proc/self/statm
5770        if let Ok(statm) = std::fs::read_to_string("/proc/self/statm") {
5771            let parts: Vec<&str> = statm.split_whitespace().collect();
5772            if let Some(rss_pages) = parts.get(1).and_then(|s| s.parse::<u64>().ok()) {
5773                return rss_pages * 4; // pages (4KB) → KB
5774            }
5775        }
5776        0
5777    }
5778}