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 any_to_yaml_and_from_yaml_round_trip() -> anyhow::Result<()> {
1689        let vm = Vm::with_all()?;
1690        vm.import_code(
1691            "vm_any_yaml",
1692            br#"
1693            pub fn render(value) {
1694                value.to_yaml()
1695            }
1696
1697            pub fn parse(text) {
1698                text.from_yaml()
1699            }
1700            "#
1701            .to_vec(),
1702        )?;
1703
1704        let compiled = vm.get_fn("vm_any_yaml::render", &[Type::Any])?;
1705        let render: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1706
1707        // 嵌套结构走完整的 round-trip:
1708        // - to_yaml 在脚本侧得到 yaml 字符串
1709        // - from_yaml 在脚本侧把字符串解回 Dynamic
1710        // 二者一起验证 Any::to_yaml / Any::from_yaml 都已正确注册。
1711        let items = Dynamic::list(vec![Dynamic::String("rust".into()), Dynamic::String("zust".into())]);
1712        let inner = Dynamic::map({
1713            let mut m = std::collections::BTreeMap::new();
1714            m.insert("name".into(), Dynamic::String("alice".into()));
1715            m.insert("age".into(), Dynamic::I64(30));
1716            m
1717        });
1718        let mut outer = Dynamic::map({
1719            let mut m = std::collections::BTreeMap::new();
1720            m.insert("user".into(), inner);
1721            m.insert("tags".into(), items);
1722            m.insert("active".into(), Dynamic::Bool(true));
1723            m
1724        });
1725        // 用户给出的 id 是字符串 "123",必须保留为字符串而不是解析成整数。
1726        outer.insert("id", Dynamic::String("123".into()));
1727
1728        let yaml_ptr = render(&outer);
1729        let yaml_text = unsafe { (&*yaml_ptr).as_str().to_string() };
1730        assert!(yaml_text.contains("user:"), "yaml missing user: {yaml_text}");
1731        assert!(yaml_text.contains("name: alice"), "{yaml_text}");
1732        assert!(yaml_text.contains("age: 30"), "{yaml_text}");
1733        assert!(yaml_text.contains("active: true"), "{yaml_text}");
1734        assert!(yaml_text.contains("id: \"123\""), "id 必须保留为字符串: {yaml_text}");
1735        assert!(yaml_text.contains("- rust"), "{yaml_text}");
1736
1737        // 把 to_yaml 的输出塞回 from_yaml,验证 round-trip。
1738        let parse_compiled = vm.get_fn("vm_any_yaml::parse", &[Type::Any])?;
1739        let parse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(parse_compiled.ptr()) };
1740        let yaml_dynamic = Dynamic::from(yaml_text);
1741        let parsed_ptr = parse(&yaml_dynamic);
1742        let parsed = unsafe { &*parsed_ptr };
1743        eprintln!("[debug] parsed={:?} yaml_text={:?}", parsed, yaml_dynamic.as_str());
1744        // as_str() 返回 &str 不能直接跨 Option 比较,转成 String。
1745        assert_eq!(parsed.get_dynamic("id").map(|v| v.as_str().to_string()), Some("123".to_string()));
1746        assert_eq!(parsed.get_dynamic("active").and_then(|v| v.as_bool()), Some(true));
1747        assert_eq!(parsed.get_dynamic("user").and_then(|u| u.get_dynamic("name")).map(|v| v.as_str().to_string()), Some("alice".to_string()));
1748        assert_eq!(parsed.get_dynamic("user").and_then(|u| u.get_dynamic("age")).and_then(|v| v.as_int()), Some(30));
1749        let tags = parsed.get_dynamic("tags").expect("tags");
1750        assert!(tags.is_list());
1751        assert_eq!(tags.get_idx(0).map(|v| v.as_str().to_string()), Some("rust".to_string()));
1752        assert_eq!(tags.get_idx(1).map(|v| v.as_str().to_string()), Some("zust".to_string()));
1753        Ok(())
1754    }
1755
1756    #[test]
1757    fn static_string_add_uses_direct_strcat() -> anyhow::Result<()> {
1758        let vm = Vm::with_all()?;
1759        vm.import_code(
1760            "vm_static_strcat",
1761            br#"
1762            pub fn join(left: string, right: string) {
1763                left + right
1764            }
1765
1766            pub fn suffix(left: string) {
1767                left + "-tail"
1768            }
1769
1770            pub fn append_local() {
1771                let text: string = "alpha";
1772                text += "-beta";
1773                text += "-tail";
1774                text
1775            }
1776
1777            pub fn append_local_assign() {
1778                let text: string = "alpha";
1779                text = text + "-beta";
1780                text = text + "-tail";
1781                text
1782            }
1783
1784            pub fn append_arg(text: string) {
1785                text += "-tail";
1786                text
1787            }
1788
1789            pub fn append_arg_assign(text: string) {
1790                text = text + "-tail";
1791                text
1792            }
1793
1794            pub fn append_any(value) {
1795                value += "-tail";
1796                value
1797            }
1798
1799            pub fn add_sub_assign_form() {
1800                let x = 10i64;
1801                x = x + 1i64;
1802                x = x - 2i64;
1803                x
1804            }
1805            "#
1806            .to_vec(),
1807        )?;
1808
1809        let compiled = vm.get_fn("vm_static_strcat::join", &[Type::Str, Type::Str])?;
1810        assert_eq!(compiled.ret_ty(), &Type::Str);
1811        let join: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1812        let left = Dynamic::from("alpha");
1813        let right = Dynamic::from("-beta");
1814        let result = unsafe { &*join(&left, &right) };
1815        assert!(matches!(result, Dynamic::StringBuf(_)));
1816        assert_eq!(result.as_str(), "alpha-beta");
1817
1818        let compiled = vm.get_fn("vm_static_strcat::suffix", &[Type::Str])?;
1819        assert_eq!(compiled.ret_ty(), &Type::Str);
1820        let suffix: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1821        let result = unsafe { &*suffix(&left) };
1822        assert!(matches!(result, Dynamic::StringBuf(_)));
1823        assert_eq!(result.as_str(), "alpha-tail");
1824
1825        let compiled = vm.get_fn("vm_static_strcat::append_local", &[])?;
1826        assert_eq!(compiled.ret_ty(), &Type::Str);
1827        let append_local: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1828        let result = unsafe { &*append_local() };
1829        assert!(matches!(result, Dynamic::StringBuf(_)));
1830        assert_eq!(result.as_str(), "alpha-beta-tail");
1831
1832        let compiled = vm.get_fn("vm_static_strcat::append_local_assign", &[])?;
1833        assert_eq!(compiled.ret_ty(), &Type::Str);
1834        let append_local_assign: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1835        let result = unsafe { &*append_local_assign() };
1836        assert!(matches!(result, Dynamic::StringBuf(_)));
1837        assert_eq!(result.as_str(), "alpha-beta-tail");
1838
1839        let compiled = vm.get_fn("vm_static_strcat::append_arg", &[Type::Str])?;
1840        assert_eq!(compiled.ret_ty(), &Type::Str);
1841        let append_arg: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1842        let input = Dynamic::from("alpha");
1843        let result = unsafe { &*append_arg(&input) };
1844        assert_eq!(result.as_str(), "alpha-tail");
1845        assert_eq!(input.as_str(), "alpha");
1846
1847        let compiled = vm.get_fn("vm_static_strcat::append_arg_assign", &[Type::Str])?;
1848        assert_eq!(compiled.ret_ty(), &Type::Str);
1849        let append_arg_assign: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1850        let input = Dynamic::from("alpha");
1851        let result = unsafe { &*append_arg_assign(&input) };
1852        assert_eq!(result.as_str(), "alpha-tail");
1853        assert_eq!(input.as_str(), "alpha");
1854
1855        let compiled = vm.get_fn("vm_static_strcat::append_any", &[Type::Any])?;
1856        assert_eq!(compiled.ret_ty(), &Type::Str);
1857        let append_any: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1858        let input = Dynamic::from("alpha");
1859        let result = unsafe { &*append_any(&input) };
1860        assert_eq!(result.as_str(), "alpha-tail");
1861        assert_eq!(input.as_str(), "alpha");
1862
1863        let compiled = vm.get_fn("vm_static_strcat::add_sub_assign_form", &[])?;
1864        assert_eq!(compiled.ret_ty(), &Type::I64);
1865        let add_sub_assign_form: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1866        assert_eq!(add_sub_assign_form(), 9);
1867        Ok(())
1868    }
1869
1870    #[test]
1871    fn primitive_type_check_methods_call_any_runtime() -> anyhow::Result<()> {
1872        let vm = Vm::with_all()?;
1873        vm.import_code(
1874            "vm_primitive_type_check_methods",
1875            br#"
1876            pub fn int_checks() {
1877                !42i64.is_list()
1878                    && !42i64.is_map()
1879                    && !42i64.is_string()
1880                    && !42i64.is_null()
1881            }
1882
1883            pub fn bool_checks() {
1884                !true.is_list() && !true.is_map() && !true.is_null()
1885            }
1886            "#
1887            .to_vec(),
1888        )?;
1889
1890        let compiled = vm.get_fn("vm_primitive_type_check_methods::int_checks", &[])?;
1891        assert_eq!(compiled.ret_ty(), &Type::Bool);
1892        let int_checks: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1893        assert!(int_checks());
1894
1895        let compiled = vm.get_fn("vm_primitive_type_check_methods::bool_checks", &[])?;
1896        assert_eq!(compiled.ret_ty(), &Type::Bool);
1897        let bool_checks: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1898        assert!(bool_checks());
1899        Ok(())
1900    }
1901
1902    #[test]
1903    fn for_loop_iterates_any_list_and_map_values() -> anyhow::Result<()> {
1904        let vm = Vm::with_all()?;
1905        vm.import_code(
1906            "vm_for_any_collections",
1907            br#"
1908            pub fn list_sum(items) {
1909                let total = 0i64;
1910                for item in items {
1911                    total += item;
1912                }
1913                total
1914            }
1915
1916            pub fn map_sum(data) {
1917                let total = 0i64;
1918                for (key, value) in data {
1919                    total += value;
1920                }
1921                total
1922            }
1923            "#
1924            .to_vec(),
1925        )?;
1926
1927        let compiled = vm.get_fn("vm_for_any_collections::list_sum", &[Type::Any])?;
1928        assert_eq!(compiled.ret_ty(), &Type::I64);
1929        let list_sum: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1930        let items = Dynamic::list(vec![1i64.into(), 2i64.into(), 3i64.into()]);
1931        assert_eq!(list_sum(&items), 6);
1932
1933        let compiled = vm.get_fn("vm_for_any_collections::map_sum", &[Type::Any])?;
1934        assert_eq!(compiled.ret_ty(), &Type::I64);
1935        let map_sum: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1936        let data = dynamic::map!("a"=> 4i64, "b"=> 5i64);
1937        assert_eq!(map_sum(&data), 9);
1938        Ok(())
1939    }
1940
1941    #[test]
1942    fn compares_concrete_value_with_string_literal_as_string() -> anyhow::Result<()> {
1943        let vm = Vm::with_all()?;
1944        vm.import_code(
1945            "vm_string_compare_imm",
1946            br#"
1947            pub fn int_eq_str(value: i64) {
1948                value == "42"
1949            }
1950
1951            pub fn int_to_str(value: i64) {
1952                value + ""
1953            }
1954            "#
1955            .to_vec(),
1956        )?;
1957
1958        let compiled = vm.get_fn("vm_string_compare_imm::int_eq_str", &[Type::I64])?;
1959        assert_eq!(compiled.ret_ty(), &Type::Bool);
1960
1961        let int_eq_str: extern "C" fn(i64) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1962
1963        let compiled = vm.get_fn("vm_string_compare_imm::int_to_str", &[Type::I64])?;
1964        assert_eq!(compiled.ret_ty(), &Type::Str);
1965        let int_to_str: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1966        let text = int_to_str(42);
1967        assert_eq!(unsafe { &*text }.as_str(), "42");
1968
1969        assert!(int_eq_str(42));
1970        assert!(!int_eq_str(7));
1971        Ok(())
1972    }
1973
1974    #[test]
1975    fn concatenates_string_with_integer_values() -> anyhow::Result<()> {
1976        let vm = Vm::with_all()?;
1977        vm.import_code(
1978            "vm_string_concat_integer",
1979            br#"
1980            pub fn idx_key(idx: i64) {
1981                "" + idx
1982            }
1983
1984            pub fn level_text(level: i64) {
1985                "" + level + " level"
1986            }
1987
1988            pub fn gold_text(currency) {
1989                "" + currency.gold
1990            }
1991            "#
1992            .to_vec(),
1993        )?;
1994
1995        let compiled = vm.get_fn("vm_string_concat_integer::idx_key", &[Type::I64])?;
1996        let idx_key: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1997        let result = unsafe { &*idx_key(7) };
1998        assert!(matches!(result, Dynamic::StringBuf(_)));
1999        assert_eq!(result.as_str(), "7");
2000
2001        let compiled = vm.get_fn("vm_string_concat_integer::level_text", &[Type::I64])?;
2002        let level_text: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2003        let result = unsafe { &*level_text(12) };
2004        assert_eq!(result.as_str(), "12 level");
2005
2006        let compiled = vm.get_fn("vm_string_concat_integer::gold_text", &[Type::Any])?;
2007        let gold_text: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2008        let currency = dynamic::map!("gold"=> 345i64);
2009        let result = unsafe { &*gold_text(&currency) };
2010        assert_eq!(result.as_str(), "345");
2011        Ok(())
2012    }
2013
2014    #[test]
2015    fn coerces_string_concat_to_i64_without_unimplemented_log() -> anyhow::Result<()> {
2016        let vm = Vm::with_all()?;
2017        vm.import_code(
2018            "vm_string_concat_to_i64",
2019            br#"
2020            pub fn run(idx: i64) {
2021                ("" + idx) as i64
2022            }
2023            "#
2024            .to_vec(),
2025        )?;
2026
2027        let compiled = vm.get_fn("vm_string_concat_to_i64::run", &[Type::I64])?;
2028        assert_eq!(compiled.ret_ty(), &Type::I64);
2029        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2030        assert_eq!(run(7), 7);
2031        Ok(())
2032    }
2033
2034    #[test]
2035    fn casts_dynamic_string_numbers_to_ints_and_floats() -> anyhow::Result<()> {
2036        let vm = Vm::with_all()?;
2037        vm.import_code(
2038            "vm_string_number_casts",
2039            br#"
2040            pub fn limit_i64(req) {
2041                req["@query"].limit as i64
2042            }
2043
2044            pub fn limit_i32(req) {
2045                req["@query"].limit as i32
2046            }
2047
2048            pub fn price_f64(req) {
2049                req["@query"].price as f64
2050            }
2051
2052            pub fn price_f32(req) {
2053                req["@query"].price as f32
2054            }
2055
2056            pub fn literal_i64() {
2057                "42" as i64
2058            }
2059
2060            pub fn literal_f64() {
2061                "3.5" as f64
2062            }
2063
2064            pub fn bad_number(req) {
2065                req["@query"].bad as i64
2066            }
2067            "#
2068            .to_vec(),
2069        )?;
2070
2071        let req = dynamic::map!("@query"=> dynamic::map!("limit"=> "50", "price"=> "3.5", "bad"=> "nope"));
2072
2073        let limit_i64 = vm.get_fn("vm_string_number_casts::limit_i64", &[Type::Any])?;
2074        assert_eq!(limit_i64.ret_ty(), &Type::I64);
2075        let limit_i64: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(limit_i64.ptr()) };
2076        assert_eq!(limit_i64(&req), 50);
2077
2078        let limit_i32 = vm.get_fn("vm_string_number_casts::limit_i32", &[Type::Any])?;
2079        assert_eq!(limit_i32.ret_ty(), &Type::I32);
2080        let limit_i32: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(limit_i32.ptr()) };
2081        assert_eq!(limit_i32(&req), 50);
2082
2083        let price_f64 = vm.get_fn("vm_string_number_casts::price_f64", &[Type::Any])?;
2084        assert_eq!(price_f64.ret_ty(), &Type::F64);
2085        let price_f64: extern "C" fn(*const Dynamic) -> f64 = unsafe { std::mem::transmute(price_f64.ptr()) };
2086        assert_eq!(price_f64(&req), 3.5);
2087
2088        let price_f32 = vm.get_fn("vm_string_number_casts::price_f32", &[Type::Any])?;
2089        assert_eq!(price_f32.ret_ty(), &Type::F32);
2090        let price_f32: extern "C" fn(*const Dynamic) -> f32 = unsafe { std::mem::transmute(price_f32.ptr()) };
2091        assert_eq!(price_f32(&req), 3.5);
2092
2093        let literal_i64 = vm.get_fn("vm_string_number_casts::literal_i64", &[])?;
2094        assert_eq!(literal_i64.ret_ty(), &Type::I64);
2095        let literal_i64: extern "C" fn() -> i64 = unsafe { std::mem::transmute(literal_i64.ptr()) };
2096        assert_eq!(literal_i64(), 42);
2097
2098        let literal_f64 = vm.get_fn("vm_string_number_casts::literal_f64", &[])?;
2099        assert_eq!(literal_f64.ret_ty(), &Type::F64);
2100        let literal_f64: extern "C" fn() -> f64 = unsafe { std::mem::transmute(literal_f64.ptr()) };
2101        assert_eq!(literal_f64(), 3.5);
2102
2103        let bad_number = vm.get_fn("vm_string_number_casts::bad_number", &[Type::Any])?;
2104        assert_eq!(bad_number.ret_ty(), &Type::I64);
2105        let bad_number: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(bad_number.ptr()) };
2106        assert_eq!(bad_number(&req), 0);
2107        Ok(())
2108    }
2109
2110    #[test]
2111    fn unifies_explicit_return_and_tail_integer_widths() -> anyhow::Result<()> {
2112        let vm = Vm::with_all()?;
2113        vm.import_code(
2114            "vm_return_integer_widths",
2115            br#"
2116            pub fn selected(flag, slot) {
2117                if flag {
2118                    return slot;
2119                }
2120                0
2121            }
2122            "#
2123            .to_vec(),
2124        )?;
2125
2126        let compiled = vm.get_fn("vm_return_integer_widths::selected", &[Type::Bool, Type::I64])?;
2127        assert_eq!(compiled.ret_ty(), &Type::I64);
2128        let selected: extern "C" fn(bool, i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2129
2130        assert_eq!(selected(true, 7), 7);
2131        assert_eq!(selected(false, 7), 0);
2132        Ok(())
2133    }
2134
2135    #[test]
2136    fn root_contains_string_concat_is_bool_condition() -> anyhow::Result<()> {
2137        let vm = Vm::with_all()?;
2138        vm.import_code(
2139            "vm_root_contains_condition",
2140            br#"
2141            pub fn exists(user_id) {
2142                if root::contains("redis/user/" + user_id) {
2143                    return 1;
2144                }
2145                0
2146            }
2147            "#
2148            .to_vec(),
2149        )?;
2150
2151        assert_eq!(vm.infer("root::contains", &[Type::Any])?, Type::Bool);
2152        let compiled = vm.get_fn("vm_root_contains_condition::exists", &[Type::Any])?;
2153        assert_eq!(compiled.ret_ty(), &Type::I64);
2154        Ok(())
2155    }
2156
2157    #[test]
2158    fn root_add_map_can_be_printed() -> anyhow::Result<()> {
2159        let vm = Vm::with_all()?;
2160        assert_eq!(vm.infer("root::add_map", &[Type::Any])?, Type::Bool);
2161        vm.import_code(
2162            "vm_root_add_map_print",
2163            br#"
2164            pub fn run() {
2165                print(root::add_map("local/world_handlers/til_map_novicevillage"));
2166            }
2167            "#
2168            .to_vec(),
2169        )?;
2170
2171        let compiled = vm.get_fn("vm_root_add_map_print::run", &[])?;
2172        assert!(compiled.ret_ty().is_void());
2173        Ok(())
2174    }
2175
2176    #[test]
2177    fn root_keys_returns_map_key_list() -> anyhow::Result<()> {
2178        let vm = Vm::with_all()?;
2179        assert_eq!(vm.infer("root::keys", &[Type::Any])?, Type::Any);
2180        vm.import_code(
2181            "vm_root_keys",
2182            br#"
2183            pub fn run() {
2184                root::add_map("local/test/vm_root_keys");
2185                root::insert("local/test/vm_root_keys", "0", "zero");
2186                root::insert("local/test/vm_root_keys", "1", "one");
2187                root::keys("local/test/vm_root_keys").len()
2188            }
2189            "#
2190            .to_vec(),
2191        )?;
2192
2193        let compiled = vm.get_fn("vm_root_keys::run", &[])?;
2194        assert_eq!(compiled.ret_ty(), &Type::I32);
2195        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2196        assert_eq!(run(), 2);
2197        Ok(())
2198    }
2199
2200    #[test]
2201    fn root_mount_fjall_accepts_mount_name() -> anyhow::Result<()> {
2202        let vm = Vm::with_all()?;
2203        assert_eq!(vm.infer("root::mount_fjall", &[Type::Any, Type::Any])?, Type::Void);
2204        vm.import_code(
2205            "vm_root_mount_fjall_named",
2206            br#"
2207            pub fn run(name, data_dir) {
2208                root::mount_fjall(name, data_dir);
2209            }
2210            "#
2211            .to_vec(),
2212        )?;
2213
2214        let compiled = vm.get_fn("vm_root_mount_fjall_named::run", &[Type::Any, Type::Any])?;
2215        assert!(compiled.ret_ty().is_void());
2216        Ok(())
2217    }
2218
2219    #[test]
2220    fn std_log_accepts_any_and_returns_void() -> anyhow::Result<()> {
2221        let vm = Vm::with_all()?;
2222        vm.import_code(
2223            "vm_std_log",
2224            br#"
2225            pub fn run(value) {
2226                log({ ok: true, value: value });
2227            }
2228            "#
2229            .to_vec(),
2230        )?;
2231
2232        let compiled = vm.get_fn("vm_std_log::run", &[Type::Any])?;
2233        assert!(compiled.ret_ty().is_void());
2234        let run: extern "C" fn(*const Dynamic) = unsafe { std::mem::transmute(compiled.ptr()) };
2235        let value = Dynamic::from(7i64);
2236        run(&value);
2237        Ok(())
2238    }
2239
2240    #[test]
2241    fn unary_not_any_loop_var_is_bool_condition() -> anyhow::Result<()> {
2242        let vm = Vm::with_all()?;
2243        vm.import_code(
2244            "vm_unary_not_any_loop_var",
2245            br#"
2246            pub fn count_missing(flags) {
2247                let missing = 0;
2248                for exists in flags {
2249                    if !exists {
2250                        missing = missing + 1;
2251                    }
2252                }
2253                missing
2254            }
2255            "#
2256            .to_vec(),
2257        )?;
2258
2259        let compiled = vm.get_fn("vm_unary_not_any_loop_var::count_missing", &[Type::Any])?;
2260        assert_eq!(compiled.ret_ty(), &Type::I64);
2261        Ok(())
2262    }
2263
2264    #[test]
2265    fn closure_literal_can_be_called_immediately() -> anyhow::Result<()> {
2266        let vm = Vm::with_all()?;
2267        vm.import_code(
2268            "vm_closure_immediate_call",
2269            br#"
2270            pub fn no_args() {
2271                let r = || { 1i32 }();
2272                r
2273            }
2274
2275            pub fn with_arg() {
2276                |value: i32| { value + 1i32 }(2i32)
2277            }
2278            "#
2279            .to_vec(),
2280        )?;
2281
2282        let compiled = vm.get_fn("vm_closure_immediate_call::no_args", &[])?;
2283        assert_eq!(compiled.ret_ty(), &Type::I32);
2284        let no_args: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2285        assert_eq!(no_args(), 1);
2286
2287        let compiled = vm.get_fn("vm_closure_immediate_call::with_arg", &[])?;
2288        assert_eq!(compiled.ret_ty(), &Type::I32);
2289        let with_arg: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2290        assert_eq!(with_arg(), 3);
2291        Ok(())
2292    }
2293
2294    #[test]
2295    fn returned_closure_can_be_called() -> anyhow::Result<()> {
2296        let vm = Vm::with_all()?;
2297        vm.import_code(
2298            "vm_returned_closure_call",
2299            br#"
2300            pub fn make_adder() {
2301                |value: i64| { value + 1i64 }
2302            }
2303
2304            pub fn make_offset_adder(offset: i64) {
2305                |value: i64| { value + offset }
2306            }
2307
2308            pub fn run() {
2309                make_adder()(41i64)
2310            }
2311
2312            pub fn run_captured() {
2313                make_offset_adder(2i64)(40i64)
2314            }
2315            "#
2316            .to_vec(),
2317        )?;
2318
2319        let compiled = vm.get_fn("vm_returned_closure_call::run", &[])?;
2320        assert_eq!(compiled.ret_ty(), &Type::Any);
2321        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2322        let result = unsafe { &*run() };
2323        assert_eq!(result.as_int(), Some(42));
2324
2325        let compiled = vm.get_fn("vm_returned_closure_call::run_captured", &[])?;
2326        assert_eq!(compiled.ret_ty(), &Type::Any);
2327        let run_captured: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2328        let result = unsafe { &*run_captured() };
2329        assert_eq!(result.as_int(), Some(42));
2330        Ok(())
2331    }
2332
2333    #[test]
2334    fn small_expression_calls_keep_direct_semantics() -> anyhow::Result<()> {
2335        let vm = Vm::with_all()?;
2336        vm.import_code(
2337            "vm_small_expression_inline",
2338            br#"
2339            pub fn add_i64(left: i64, right: i64) {
2340                left + right
2341            }
2342
2343            pub fn normal_caller() {
2344                add_i64(1i64, 2i64)
2345            }
2346
2347            pub fn closure_caller() {
2348                let add = |left: i64, right: i64| { left + right };
2349                add(add_i64(1i64, 2i64), 4i64)
2350            }
2351
2352            pub fn closure_assignment() {
2353                let acc = 0i64;
2354                let add = |left: i64, right: i64| { left + right };
2355                acc = add(acc, 4i64);
2356                acc
2357            }
2358            "#
2359            .to_vec(),
2360        )?;
2361
2362        let compiled = vm.get_fn("vm_small_expression_inline::normal_caller", &[])?;
2363        assert_eq!(compiled.ret_ty(), &Type::I64);
2364        let normal_caller: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2365        assert_eq!(normal_caller(), 3);
2366
2367        let compiled = vm.get_fn("vm_small_expression_inline::closure_caller", &[])?;
2368        assert_eq!(compiled.ret_ty(), &Type::Any);
2369        let closure_caller: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2370        let result = unsafe { &*closure_caller() };
2371        assert_eq!(result.as_int(), Some(7));
2372
2373        let compiled = vm.get_fn("vm_small_expression_inline::closure_assignment", &[])?;
2374        assert_eq!(compiled.ret_ty(), &Type::I64);
2375        let closure_assignment: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2376        assert_eq!(closure_assignment(), 4);
2377        Ok(())
2378    }
2379
2380    #[test]
2381    fn nested_closure_captures_outer_closure_arg() -> anyhow::Result<()> {
2382        let vm = Vm::with_all()?;
2383        vm.import_code(
2384            "vm_nested_closure_capture",
2385            br#"
2386            pub fn run() {
2387                let reference_label = "reference";
2388                |path: string| {
2389                    let upload_done = |uploaded: bool| {
2390                        if uploaded {
2391                            reference_label + ":" + path
2392                        } else {
2393                            "missing"
2394                        }
2395                    };
2396                    upload_done(true)
2397                }("reference.png")
2398            }
2399            "#
2400            .to_vec(),
2401        )?;
2402
2403        let compiled = vm.get_fn("vm_nested_closure_capture::run", &[])?;
2404        assert_eq!(compiled.ret_ty(), &Type::Any);
2405        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2406        let result = unsafe { &*run() };
2407        assert_eq!(result.as_str(), "reference:reference.png");
2408        Ok(())
2409    }
2410
2411    #[test]
2412    fn semicolon_tail_call_makes_function_void() -> anyhow::Result<()> {
2413        let vm = Vm::with_all()?;
2414        vm.import_code(
2415            "vm_semicolon_tail_void",
2416            br#"
2417            pub fn send_role_select(idx, account_id, selected_slot) {
2418                root::send("local/ui/send_dialog", {
2419                    idx: idx,
2420                    account_id: account_id,
2421                    selected_slot: selected_slot
2422                });
2423            }
2424            "#
2425            .to_vec(),
2426        )?;
2427
2428        let compiled = vm.get_fn("vm_semicolon_tail_void::send_role_select", &[Type::Any, Type::Any, Type::Any])?;
2429        assert_eq!(compiled.ret_ty(), &Type::Void);
2430        Ok(())
2431    }
2432
2433    #[test]
2434    fn bare_return_conflicts_with_non_void_return() -> anyhow::Result<()> {
2435        let vm = Vm::with_all()?;
2436        vm.import_code(
2437            "vm_bare_return_conflict",
2438            br#"
2439            pub fn run(flag) {
2440                if flag {
2441                    return;
2442                }
2443                1
2444            }
2445            "#
2446            .to_vec(),
2447        )?;
2448
2449        let err = match vm.get_fn("vm_bare_return_conflict::run", &[Type::Bool]) {
2450            Ok(_) => panic!("expected mismatched return types to fail"),
2451            Err(err) => err,
2452        };
2453        assert!(format!("{err:#}").contains("返回类型不一致"));
2454        Ok(())
2455    }
2456
2457    #[test]
2458    fn root_get_accepts_string_concat_with_dynamic_field() -> anyhow::Result<()> {
2459        let vm = Vm::with_all()?;
2460        vm.import_code(
2461            "vm_root_get_dynamic_concat",
2462            br#"
2463            pub fn get_action(req) {
2464                root::get("local/game/panel_actions/" + req.idx)
2465            }
2466            "#
2467            .to_vec(),
2468        )?;
2469
2470        root::add("local/game/panel_actions/7", dynamic::map!("id"=> "action-7").into())?;
2471        let compiled = vm.get_fn("vm_root_get_dynamic_concat::get_action", &[Type::Any])?;
2472        assert_eq!(compiled.ret_ty(), &Type::Any);
2473        let get_action: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2474        let req = dynamic::map!("idx"=> 7i64);
2475        let result = unsafe { &*get_action(&req) };
2476
2477        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("action-7".to_string()));
2478        Ok(())
2479    }
2480
2481    #[test]
2482    fn root_add_fn_registers_handler_with_dynamic_field_path_concat() -> anyhow::Result<()> {
2483        let vm = Vm::with_all()?;
2484        vm.import_code(
2485            "vm_registered_panel_action",
2486            br#"
2487            pub fn panel_action(req) {
2488                root::get("local/game/panel_actions/" + req.idx)
2489            }
2490
2491            pub fn register() {
2492                root::add_fn("local/ui/panel_action", "vm_registered_panel_action::panel_action")
2493            }
2494            "#
2495            .to_vec(),
2496        )?;
2497
2498        let compiled = vm.get_fn("vm_registered_panel_action::register", &[])?;
2499        assert_eq!(compiled.ret_ty(), &Type::Bool);
2500        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2501        assert!(register());
2502        Ok(())
2503    }
2504
2505    #[test]
2506    fn std_spawn_runs_named_function_with_tuple_args() -> anyhow::Result<()> {
2507        let zero_path = "local/vm_std_spawn/zero";
2508        let sum_path = "local/vm_std_spawn/sum";
2509        let closure_path = "local/vm_std_spawn/closure";
2510        let closure_vars_path = "local/vm_std_spawn/closure_vars";
2511        let _ = root::remove(zero_path);
2512        let _ = root::remove(sum_path);
2513        let _ = root::remove(closure_path);
2514        let _ = root::remove(closure_vars_path);
2515        let vm = Vm::with_all()?;
2516        vm.import_code(
2517            "vm_std_spawn",
2518            br#"
2519            pub fn zero() {
2520                root::add("local/vm_std_spawn/zero", 1);
2521            }
2522
2523            pub fn job(left, right) {
2524                root::add("local/vm_std_spawn/sum", left + right);
2525            }
2526
2527            pub fn start_zero() {
2528                spawn("vm_std_spawn::zero", ())
2529            }
2530
2531            pub fn start_sum() {
2532                spawn("vm_std_spawn::job", (10, 20))
2533            }
2534
2535            pub fn start_closure() {
2536                spawn(|x, y| {
2537                    root::add("local/vm_std_spawn/closure", x + y);
2538                }, (3, 4))
2539            }
2540
2541            pub fn start_closure_vars() {
2542                let x = 5;
2543                let y = 6;
2544                spawn(|left, right| {
2545                    root::add("local/vm_std_spawn/closure_vars", left + right);
2546                }, (x, y))
2547            }
2548            "#
2549            .to_vec(),
2550        )?;
2551
2552        let compiled = vm.get_fn("vm_std_spawn::start_zero", &[])?;
2553        assert_eq!(compiled.ret_ty(), &Type::Bool);
2554        let start_zero: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2555        assert!(start_zero());
2556
2557        let compiled = vm.get_fn("vm_std_spawn::start_sum", &[])?;
2558        assert_eq!(compiled.ret_ty(), &Type::Bool);
2559        let start_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2560        assert!(start_sum());
2561
2562        let compiled = vm.get_fn("vm_std_spawn::start_closure", &[])?;
2563        assert_eq!(compiled.ret_ty(), &Type::Bool);
2564        let start_closure: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2565        assert!(start_closure());
2566
2567        let compiled = vm.get_fn("vm_std_spawn::start_closure_vars", &[])?;
2568        assert_eq!(compiled.ret_ty(), &Type::Bool);
2569        let start_closure_vars: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2570        assert!(start_closure_vars());
2571
2572        for _ in 0..50 {
2573            let zero_done = root::get(zero_path).ok().and_then(|value| value.as_int()) == Some(1);
2574            let sum_done = root::get(sum_path).ok().and_then(|value| value.as_int()) == Some(30);
2575            let closure_done = root::get(closure_path).ok().and_then(|value| value.as_int()) == Some(7);
2576            let closure_vars_done = root::get(closure_vars_path).ok().and_then(|value| value.as_int()) == Some(11);
2577            if zero_done && sum_done && closure_done && closure_vars_done {
2578                return Ok(());
2579            }
2580            std::thread::sleep(std::time::Duration::from_millis(10));
2581        }
2582
2583        anyhow::bail!("spawned jobs did not write expected results");
2584    }
2585
2586    #[test]
2587    fn native_can_save_and_later_call_closure_callback() -> anyhow::Result<()> {
2588        static SAVED_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2589
2590        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2591            if callback.is_null() {
2592                return false;
2593            }
2594            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2595                return false;
2596            };
2597            *SAVED_CALLBACK.lock() = Some(callback);
2598            true
2599        }
2600
2601        let path = "local/vm_callback/result";
2602        let _ = root::remove(path);
2603        *SAVED_CALLBACK.lock() = None;
2604
2605        let vm = Vm::with_all()?;
2606        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2607        vm.import_code(
2608            "vm_callback",
2609            br#"
2610            pub fn register() {
2611                let n = 41;
2612                callback_test::save(|| {
2613                    root::add("local/vm_callback/result", n + 1);
2614                    true
2615                })
2616            }
2617            "#
2618            .to_vec(),
2619        )?;
2620
2621        let compiled = vm.get_fn("vm_callback::register", &[])?;
2622        assert_eq!(compiled.ret_ty(), &Type::Bool);
2623        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2624        assert!(register());
2625        assert!(root::get(path).is_err());
2626
2627        let callback = SAVED_CALLBACK.lock().clone().expect("callback should be saved");
2628        let result = callback.call0()?;
2629        assert_eq!(result.as_bool(), Some(true));
2630        assert_eq!(root::get(path)?.as_int(), Some(42));
2631        Ok(())
2632    }
2633
2634    #[test]
2635    fn closure_captures_share_state_between_callbacks() -> anyhow::Result<()> {
2636        static SAVED_CALLBACKS: parking_lot::Mutex<Vec<ZustCallback>> = parking_lot::Mutex::new(Vec::new());
2637
2638        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2639            if callback.is_null() {
2640                return false;
2641            }
2642            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2643                return false;
2644            };
2645            SAVED_CALLBACKS.lock().push(callback);
2646            true
2647        }
2648
2649        SAVED_CALLBACKS.lock().clear();
2650
2651        let vm = Vm::with_all()?;
2652        vm.add_native_module_ptr("capture_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2653        vm.import_code(
2654            "vm_shared_capture",
2655            br#"
2656            pub fn register() {
2657                let state = {};
2658                state.drag_kind = 0;
2659                capture_test::save(|| {
2660                    state.drag_kind = 2;
2661                    true
2662                });
2663                capture_test::save(|| {
2664                    state.drag_kind
2665                })
2666            }
2667            "#
2668            .to_vec(),
2669        )?;
2670
2671        let register = vm.get_fn("vm_shared_capture::register", &[])?;
2672        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2673        assert!(register());
2674
2675        let (writer, reader) = {
2676            let saved = SAVED_CALLBACKS.lock();
2677            assert_eq!(saved.len(), 2);
2678            (saved[0].clone(), saved[1].clone())
2679        };
2680        assert_eq!(reader.call0()?.as_int(), Some(0));
2681        assert_eq!(writer.call0()?.as_bool(), Some(true));
2682        assert_eq!(reader.call0()?.as_int(), Some(2));
2683        Ok(())
2684    }
2685
2686    #[test]
2687    fn native_can_save_and_later_call_named_function_callback() -> anyhow::Result<()> {
2688        static SAVED_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2689
2690        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2691            if callback.is_null() {
2692                return false;
2693            }
2694            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2695                return false;
2696            };
2697            *SAVED_CALLBACK.lock() = Some(callback);
2698            true
2699        }
2700
2701        let path = "local/vm_named_callback/result";
2702        let _ = root::remove(path);
2703        *SAVED_CALLBACK.lock() = None;
2704
2705        let vm = Vm::with_all()?;
2706        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2707        vm.import_code(
2708            "vm_named_callback",
2709            br#"
2710            pub fn on_result() {
2711                root::add("local/vm_named_callback/result", "done");
2712                true
2713            }
2714
2715            pub fn register() {
2716                callback_test::save(on_result)
2717            }
2718            "#
2719            .to_vec(),
2720        )?;
2721
2722        let register = vm.get_fn("vm_named_callback::register", &[])?;
2723        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2724        assert!(register());
2725        assert!(root::get(path).is_err());
2726
2727        let callback = SAVED_CALLBACK.lock().clone().expect("callback should be saved");
2728        assert_eq!(callback.call1(dynamic::map!("text"=> "done"))?.as_bool(), Some(true));
2729        assert_eq!(root::get(path)?.as_str(), "done");
2730        Ok(())
2731    }
2732
2733    #[test]
2734    fn native_callback_can_receive_later_dynamic_args() -> anyhow::Result<()> {
2735        static SAVED_PATH_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2736        static SAVED_SUM_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2737
2738        extern "C" fn save_path_callback(callback: *const Dynamic) -> bool {
2739            if callback.is_null() {
2740                return false;
2741            }
2742            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2743                return false;
2744            };
2745            *SAVED_PATH_CALLBACK.lock() = Some(callback);
2746            true
2747        }
2748
2749        extern "C" fn save_sum_callback(callback: *const Dynamic) -> bool {
2750            if callback.is_null() {
2751                return false;
2752            }
2753            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2754                return false;
2755            };
2756            *SAVED_SUM_CALLBACK.lock() = Some(callback);
2757            true
2758        }
2759
2760        let path_result = "local/vm_callback/path";
2761        let sum_result = "local/vm_callback/sum8";
2762        let _ = root::remove(path_result);
2763        let _ = root::remove(sum_result);
2764        *SAVED_PATH_CALLBACK.lock() = None;
2765        *SAVED_SUM_CALLBACK.lock() = None;
2766
2767        let vm = Vm::with_all()?;
2768        vm.add_native_module_ptr("callback_test", "save_path", &[Type::Any], Type::Bool, save_path_callback as *const u8)?;
2769        vm.add_native_module_ptr("callback_test", "save_sum", &[Type::Any], Type::Bool, save_sum_callback as *const u8)?;
2770        vm.import_code(
2771            "vm_callback_args",
2772            br#"
2773            pub fn register_path() {
2774                let key = "local/vm_callback/path";
2775                callback_test::save_path(|path| {
2776                    root::add(key, path);
2777                    true
2778                })
2779            }
2780
2781            pub fn register_sum() {
2782                callback_test::save_sum(|a, b, c, d, e, f, g, h| {
2783                    root::add("local/vm_callback/sum8", a + b + c + d + e + f + g + h);
2784                    true
2785                })
2786            }
2787            "#
2788            .to_vec(),
2789        )?;
2790
2791        let register_path = vm.get_fn("vm_callback_args::register_path", &[])?;
2792        let register_path: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_path.ptr()) };
2793        assert!(register_path());
2794
2795        let register_sum = vm.get_fn("vm_callback_args::register_sum", &[])?;
2796        let register_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_sum.ptr()) };
2797        assert!(register_sum());
2798
2799        let path_callback = SAVED_PATH_CALLBACK.lock().clone().expect("path callback should be saved");
2800        assert_eq!(path_callback.call1(Dynamic::from("picked.txt"))?.as_bool(), Some(true));
2801        assert_eq!(root::get(path_result)?.as_str(), "picked.txt");
2802
2803        let sum_callback = SAVED_SUM_CALLBACK.lock().clone().expect("sum callback should be saved");
2804        let sum_args = (1i64..=8).map(Dynamic::from).collect();
2805        assert_eq!(sum_callback.call(sum_args)?.as_bool(), Some(true));
2806        assert_eq!(root::get(sum_result)?.as_int(), Some(36));
2807        Ok(())
2808    }
2809
2810    #[test]
2811    fn callback_with_16_explicit_args_and_captures() -> anyhow::Result<()> {
2812        static SAVED_SUM16: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2813
2814        extern "C" fn save_sum16(callback: *const Dynamic) -> bool {
2815            if callback.is_null() {
2816                return false;
2817            }
2818            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2819                return false;
2820            };
2821            *SAVED_SUM16.lock() = Some(callback);
2822            true
2823        }
2824
2825        let sum16_path = "local/vm_callback/sum16";
2826        let _ = root::remove(sum16_path);
2827        *SAVED_SUM16.lock() = None;
2828
2829        let vm = Vm::with_all()?;
2830        vm.add_native_module_ptr("callback_test", "save_sum16", &[Type::Any], Type::Bool, save_sum16 as *const u8)?;
2831        vm.import_code(
2832            "vm_callback_16_args",
2833            br#"
2834            pub fn register_sum16() {
2835                let prefix = "sum=";
2836                callback_test::save_sum16(|a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p| {
2837                    let total = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p;
2838                    root::add("local/vm_callback/sum16", prefix + total);
2839                    true
2840                })
2841            }
2842            "#
2843            .to_vec(),
2844        )?;
2845
2846        let register = vm.get_fn("vm_callback_16_args::register_sum16", &[])?;
2847        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2848        assert!(register());
2849
2850        let callback = SAVED_SUM16.lock().clone().expect("sum16 callback saved");
2851        let args: Vec<Dynamic> = (1i64..=16).map(Dynamic::from).collect();
2852        assert_eq!(callback.call(args)?.as_bool(), Some(true));
2853        assert_eq!(root::get(sum16_path)?.as_str(), "sum=136");
2854        Ok(())
2855    }
2856
2857    #[test]
2858    fn spawn_closure_with_16_args() -> anyhow::Result<()> {
2859        let spawn16_path = "local/vm_spawn/spawn16";
2860        let _ = root::remove(spawn16_path);
2861
2862        let vm = Vm::with_all()?;
2863        vm.import_code(
2864            "vm_spawn_16_args",
2865            br#"
2866            pub fn start_spawn16() {
2867                spawn(|a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p| {
2868                    root::add("local/vm_spawn/spawn16", a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p);
2869                }, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
2870            }
2871            "#
2872            .to_vec(),
2873        )?;
2874
2875        let compiled = vm.get_fn("vm_spawn_16_args::start_spawn16", &[])?;
2876        assert_eq!(compiled.ret_ty(), &Type::Bool);
2877        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2878        assert!(start());
2879
2880        for _ in 0..50 {
2881            if root::get(spawn16_path).ok().and_then(|v| v.as_int()) == Some(136) {
2882                return Ok(());
2883            }
2884            std::thread::sleep(std::time::Duration::from_millis(10));
2885        }
2886        anyhow::bail!("spawned job did not write expected result");
2887    }
2888
2889    #[test]
2890    fn spawn_native_closure_avoids_any_boxing() -> anyhow::Result<()> {
2891        let nat_path = "local/vm_spawn_native/result";
2892        let _ = root::remove(nat_path);
2893        let vm = Vm::with_all()?;
2894        vm.import_code(
2895            "vm_spawn_native",
2896            br#"
2897            pub fn start() {
2898                spawn(|x: i64, y: i64| {
2899                    root::add("local/vm_spawn_native/result", x + y);
2900                }, (10i64, 20i64))
2901            }
2902            "#
2903            .to_vec(),
2904        )?;
2905        let compiled = vm.get_fn("vm_spawn_native::start", &[])?;
2906        assert_eq!(compiled.ret_ty(), &Type::Bool);
2907        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2908        assert!(start());
2909        for _ in 0..50 {
2910            if root::get(nat_path).ok().and_then(|v| v.as_int()) == Some(30) {
2911                return Ok(());
2912            }
2913            std::thread::sleep(std::time::Duration::from_millis(10));
2914        }
2915        anyhow::bail!("spawned native closure did not write expected result");
2916    }
2917
2918    #[test]
2919    fn multi_level_nested_closure_captures() -> anyhow::Result<()> {
2920        let vm = Vm::with_all()?;
2921        vm.import_code(
2922            "vm_multi_level_captures",
2923            br#"
2924            pub fn run() {
2925                let level1 = "L1";
2926                let level2 = "L2";
2927                |path: string| {
2928                    let level3 = "L3";
2929                    let inner = |suffix: string| {
2930                        let level4 = "L4";
2931                        |flag: bool| {
2932                            if flag {
2933                                level1 + "." + level2 + "." + level3 + "." + level4 + "." + path + suffix
2934                            } else {
2935                                "off"
2936                            }
2937                        }(true)
2938                    };
2939                    inner(".ext")
2940                }("file.txt")
2941            }
2942            "#
2943            .to_vec(),
2944        )?;
2945
2946        let compiled = vm.get_fn("vm_multi_level_captures::run", &[])?;
2947        assert_eq!(compiled.ret_ty(), &Type::Any);
2948        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2949        let result = unsafe { &*run() };
2950        assert_eq!(result.as_str(), "L1.L2.L3.L4.file.txt.ext");
2951        Ok(())
2952    }
2953
2954    #[test]
2955    fn root_add_fn_accepts_string_concat_in_registered_handler() -> anyhow::Result<()> {
2956        let vm = Vm::with_all()?;
2957        vm.import_code(
2958            "vm_registered_string_concat",
2959            br#"
2960            pub fn send_panel(idx: i64) {
2961                let idx_key = "" + idx;
2962                idx_key
2963            }
2964            "#
2965            .to_vec(),
2966        )?;
2967
2968        assert!(vm.get_fn_ptr("vm_registered_string_concat::send_panel", &[Type::Any]).is_ok());
2969        Ok(())
2970    }
2971
2972    #[test]
2973    fn dynamic_method_error_reports_source_location() -> anyhow::Result<()> {
2974        let vm = Vm::with_all()?;
2975        vm.import_code(
2976            "vm_bad_dynamic_method",
2977            br#"
2978            pub fn main(value) {
2979                let out = "";
2980                out = out + value.fetch("name");
2981            }
2982            "#
2983            .to_vec(),
2984        )?;
2985
2986        let err = vm.get_fn_ptr("vm_bad_dynamic_method::main", &[Type::Any]).expect_err("bad dynamic method should fail to compile");
2987        let msg = format!("{err:#}");
2988        assert!(msg.contains("vm_bad_dynamic_method:4:"), "{msg}");
2989        assert!(msg.contains("`Any.fetch` 不是成员函数"), "{msg}");
2990        assert!(msg.contains(r#"out = out + value.fetch("name");"#), "{msg}");
2991        Ok(())
2992    }
2993
2994    #[test]
2995    fn root_send_idx_returns_handler_value() -> anyhow::Result<()> {
2996        fn echo_handler(msg: Dynamic) -> Dynamic {
2997            dynamic::map!("type"=> "echo", "id"=> msg.get_dynamic("id").unwrap_or(Dynamic::Null))
2998        }
2999
3000        let vm = Vm::with_all()?;
3001        vm.import_code(
3002            "vm_root_send_idx_return",
3003            br#"
3004            pub fn call(req) {
3005                root::send_idx("local/send_idx_return_handlers", 0, req)
3006            }
3007            "#
3008            .to_vec(),
3009        )?;
3010
3011        root::add_list("local/send_idx_return_handlers")?;
3012        let (mount, name) = root::get_mount("local/send_idx_return_handlers")?;
3013        mount.push(name, root::Object::Native(root::NativeHandler::from_fn(echo_handler)))?;
3014
3015        assert_eq!(vm.infer("root::send_idx", &[Type::Any, Type::I64, Type::Any])?, Type::Any);
3016        let compiled = vm.get_fn("vm_root_send_idx_return::call", &[Type::Any])?;
3017        assert_eq!(compiled.ret_ty(), &Type::Any);
3018        let call: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3019        let req = dynamic::map!("id"=> 42i64);
3020        let result = unsafe { &*call(&req) };
3021
3022        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("echo".to_string()));
3023        assert_eq!(result.get_dynamic("id").and_then(|value| value.as_int()), Some(42));
3024        Ok(())
3025    }
3026
3027    #[test]
3028    fn compiles_public_hotspots_with_string_paths_and_keys() -> anyhow::Result<()> {
3029        let vm = Vm::with_all()?;
3030        vm.import_code(
3031            "vm_public_hotspots",
3032            br#"
3033            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
3034                {
3035                    path: action_map_path,
3036                    panel_id: panel_id,
3037                    action_id: action_id,
3038                    id: hotspot.id
3039                }
3040            }
3041
3042            pub fn public_hotspots(idx, panel_id, hotspots) {
3043                let idx_key = "" + idx;
3044                let action_map_path = "local/game/panel_actions/" + idx_key;
3045
3046                let existing_action_map = root::get(action_map_path);
3047                if !existing_action_map.is_map() {
3048                    root::add_map(action_map_path);
3049                }
3050
3051                if hotspots.is_map() {
3052                    let public_items = {};
3053                    for action_id in hotspots.keys() {
3054                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
3055                    }
3056                    return public_items;
3057                }
3058
3059                let public_items = [];
3060                let i = 0;
3061                while i < hotspots.len() {
3062                    let hotspot = hotspots.get_idx(i);
3063                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
3064                    public_items.push(item);
3065                    i = i + 1;
3066                }
3067
3068                public_items
3069            }
3070            "#
3071            .to_vec(),
3072        )?;
3073
3074        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::I64, Type::Any, Type::Any]).is_ok());
3075        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::Any, Type::Any, Type::Any]).is_ok());
3076        Ok(())
3077    }
3078
3079    #[test]
3080    fn send_panel_calls_public_hotspots_with_dynamic_request() -> anyhow::Result<()> {
3081        let vm = Vm::with_all()?;
3082        vm.import_code(
3083            "vm_send_panel_public_hotspots",
3084            br#"
3085            pub fn ok(value) {
3086                value
3087            }
3088
3089            pub fn panel_from_node(req) {
3090                {
3091                    panel_id: req.panel_id,
3092                    hotspots: req.hotspots
3093                }
3094            }
3095
3096            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
3097                {
3098                    path: action_map_path,
3099                    panel_id: panel_id,
3100                    action_id: action_id,
3101                    id: hotspot.id
3102                }
3103            }
3104
3105            pub fn public_hotspots(idx, panel_id, hotspots) {
3106                let idx_key = "" + idx;
3107                let action_map_path = "local/game/panel_actions/" + idx_key;
3108
3109                let existing_action_map = root::get(action_map_path);
3110                if !existing_action_map.is_map() {
3111                    root::add_map(action_map_path);
3112                }
3113
3114                if hotspots.is_map() {
3115                    let public_items = {};
3116                    for action_id in hotspots.keys() {
3117                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
3118                    }
3119                    return public_items;
3120                }
3121
3122                let public_items = [];
3123                let i = 0;
3124                while i < hotspots.len() {
3125                    let hotspot = hotspots.get_idx(i);
3126                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
3127                    public_items.push(item);
3128                    i = i + 1;
3129                }
3130
3131                public_items
3132            }
3133
3134            pub fn send_panel(req) {
3135                let panel = req.panel;
3136                if !panel.is_map() {
3137                    panel = panel_from_node(req);
3138                }
3139                if !panel.is_map() {
3140                    return ok({
3141                        id: 4,
3142                        type: "panel_rejected",
3143                        reason: "invalid panel"
3144                    });
3145                }
3146                panel.id = 4;
3147                panel.idx = req.idx;
3148                if !panel.contains("type") {
3149                    panel.type = "panel";
3150                }
3151                if panel.contains("hotspots") {
3152                    panel.hotspots = public_hotspots(req.idx, panel.panel_id, panel.hotspots);
3153                }
3154                root::send_idx("local/ws", req.idx, panel);
3155                ok({
3156                    id: 4,
3157                    type: "panel",
3158                    panel_id: panel.panel_id
3159                })
3160            }
3161            "#
3162            .to_vec(),
3163        )?;
3164
3165        let compiled = vm.get_fn("vm_send_panel_public_hotspots::send_panel", &[Type::Any])?;
3166        assert_eq!(compiled.ret_ty(), &Type::Any);
3167        let send_panel: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3168        let req = dynamic::map!(
3169            "idx"=> 7i64,
3170            "panel"=> dynamic::map!(
3171                "panel_id"=> "main",
3172                "hotspots"=> dynamic::map!(
3173                    "open"=> dynamic::map!("id"=> "open")
3174                )
3175            )
3176        );
3177        let result = unsafe { &*send_panel(&req) };
3178
3179        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("panel".to_string()));
3180        assert_eq!(result.get_dynamic("panel_id").map(|value| value.as_str().to_string()), Some("main".to_string()));
3181        Ok(())
3182    }
3183
3184    #[test]
3185    fn map_assignment_accepts_string_concat_key() -> anyhow::Result<()> {
3186        let vm = Vm::with_all()?;
3187        vm.import_code(
3188            "vm_string_concat_map_key",
3189            br##"
3190            pub fn write_action(action_map, panel_id, action_id, action) {
3191                action_map[panel_id + "#" + action_id] = action;
3192                action_map[panel_id + "#" + action_id]
3193            }
3194            "##
3195            .to_vec(),
3196        )?;
3197
3198        let compiled = vm.get_fn("vm_string_concat_map_key::write_action", &[Type::Any, Type::Any, Type::Any, Type::Any])?;
3199        let write_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3200        let action_map = dynamic::map!();
3201        let panel_id: Dynamic = "panel".into();
3202        let action_id: Dynamic = "open".into();
3203        let action = dynamic::map!("id"=> "open");
3204
3205        let result = unsafe { &*write_action(&action_map, &panel_id, &action_id, &action) };
3206
3207        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3208        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()));
3209        Ok(())
3210    }
3211
3212    #[test]
3213    fn map_get_key_accepts_string_concat_key_variable() -> anyhow::Result<()> {
3214        let vm = Vm::with_all()?;
3215        vm.import_code(
3216            "vm_get_key_string_concat_key",
3217            br##"
3218            pub fn read_action(action_map, panel_id, action_id) {
3219                let action_key = panel_id + "#" + action_id;
3220                action_map.get_key(action_key)
3221            }
3222            "##
3223            .to_vec(),
3224        )?;
3225
3226        let compiled = vm.get_fn("vm_get_key_string_concat_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
3227        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3228        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3229        let panel_id: Dynamic = "panel".into();
3230        let action_id: Dynamic = "open".into();
3231
3232        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
3233
3234        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3235        Ok(())
3236    }
3237
3238    #[test]
3239    fn const_map_bracket_accepts_dynamic_string_key() -> anyhow::Result<()> {
3240        let vm = Vm::with_all()?;
3241        vm.import_code(
3242            "vm_const_map_dynamic_key",
3243            r#"
3244            const DIRECTION_LABELS = {left: "左", right: "右", up: "上", down: "下"};
3245
3246            pub fn label(direction) {
3247                DIRECTION_LABELS[direction]
3248            }
3249            "#
3250            .as_bytes()
3251            .to_vec(),
3252        )?;
3253
3254        let compiled = vm.get_fn("vm_const_map_dynamic_key::label", &[Type::Any])?;
3255        assert_eq!(compiled.ret_ty(), &Type::Any);
3256        let label: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3257        let direction: Dynamic = "left".into();
3258        let result = unsafe { &*label(&direction) };
3259        assert_eq!(result.as_str(), "左");
3260        Ok(())
3261    }
3262
3263    #[test]
3264    fn map_get_alias_matches_get_key() -> anyhow::Result<()> {
3265        let vm = Vm::with_all()?;
3266        vm.import_code(
3267            "vm_map_get_alias",
3268            br#"
3269            pub fn read_name(data) {
3270                data.get("name")
3271            }
3272
3273            pub fn read_missing(data) {
3274                data.get("missing")
3275            }
3276            "#
3277            .to_vec(),
3278        )?;
3279
3280        let data = dynamic::map!("name"=> "zust");
3281
3282        let compiled = vm.get_fn("vm_map_get_alias::read_name", &[Type::Any])?;
3283        assert_eq!(compiled.ret_ty(), &Type::Any);
3284        let read_name: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3285        let result = unsafe { &*read_name(&data) };
3286        assert_eq!(result.as_str(), "zust");
3287
3288        let compiled = vm.get_fn("vm_map_get_alias::read_missing", &[Type::Any])?;
3289        assert_eq!(compiled.ret_ty(), &Type::Any);
3290        let read_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3291        let result = unsafe { &*read_missing(&data) };
3292        assert!(result.is_null());
3293        Ok(())
3294    }
3295
3296    #[test]
3297    fn map_get_key_accepts_helper_string_key() -> anyhow::Result<()> {
3298        let vm = Vm::with_all()?;
3299        vm.import_code(
3300            "vm_get_key_helper_string_key",
3301            br##"
3302            pub fn make_action_key(panel_id, action_id) {
3303                panel_id + "#" + action_id
3304            }
3305
3306            pub fn read_action(action_map, panel_id, action_id) {
3307                let action_key = make_action_key(panel_id, action_id);
3308                let action = action_map.get_key(action_key);
3309                action
3310            }
3311            "##
3312            .to_vec(),
3313        )?;
3314
3315        let compiled = vm.get_fn("vm_get_key_helper_string_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
3316        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3317        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3318        let panel_id: Dynamic = "panel".into();
3319        let action_id: Dynamic = "open".into();
3320
3321        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
3322
3323        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3324        Ok(())
3325    }
3326
3327    #[test]
3328    fn map_del_key_removes_string_key_and_returns_removed_value() -> anyhow::Result<()> {
3329        let vm = Vm::with_all()?;
3330        vm.import_code(
3331            "vm_del_key_string_key",
3332            br##"
3333            pub fn remove_action(action_map, panel_id, action_id) {
3334                let action_key = panel_id + "#" + action_id;
3335                let removed = action_map.del_key(action_key);
3336                [removed, action_map.get_key(action_key)]
3337            }
3338            "##
3339            .to_vec(),
3340        )?;
3341
3342        let compiled = vm.get_fn("vm_del_key_string_key::remove_action", &[Type::Any, Type::Any, Type::Any])?;
3343        let remove_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3344        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3345        let panel_id: Dynamic = "panel".into();
3346        let action_id: Dynamic = "open".into();
3347
3348        let result = unsafe { &*remove_action(&action_map, &panel_id, &action_id) };
3349
3350        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("id")).map(|value| value.as_str().to_string()), Some("open".to_string()));
3351        assert!(result.get_idx(1).is_some_and(|value| value.is_null()));
3352        assert!(action_map.get_dynamic("panel#open").is_none());
3353        Ok(())
3354    }
3355
3356    #[test]
3357    fn dynamic_field_value_participates_in_or_expression() -> anyhow::Result<()> {
3358        let vm = Vm::with_all()?;
3359        vm.import_code(
3360            "vm_dynamic_field_or",
3361            r#"
3362            pub fn direct_next() {
3363                let choice = {
3364                    label: "颜色",
3365                    next: "color"
3366                };
3367                choice.next
3368            }
3369
3370            pub fn bracket_next() {
3371                let choice = {
3372                    label: "颜色",
3373                    next: "color"
3374                };
3375                choice["next"]
3376            }
3377            "#
3378            .as_bytes()
3379            .to_vec(),
3380        )?;
3381
3382        let compiled = vm.get_fn("vm_dynamic_field_or::direct_next", &[])?;
3383        assert_eq!(compiled.ret_ty(), &Type::Any);
3384        let direct_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3385        assert_eq!(unsafe { &*direct_next() }.as_str(), "color");
3386
3387        let compiled = vm.get_fn("vm_dynamic_field_or::bracket_next", &[])?;
3388        assert_eq!(compiled.ret_ty(), &Type::Any);
3389        let bracket_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3390        assert_eq!(unsafe { &*bracket_next() }.as_str(), "color");
3391        Ok(())
3392    }
3393
3394    #[test]
3395    fn empty_object_literal_in_if_branch_stays_dynamic() -> anyhow::Result<()> {
3396        let vm = Vm::with_all()?;
3397        vm.import_code(
3398            "vm_if_empty_object_branch",
3399            r#"
3400            pub fn first_note(steps) {
3401                let first = if steps.len() > 0 { steps[0] } else { {} };
3402                let first_note = if first.contains("note") { first.note } else { "fallback" };
3403                first_note
3404            }
3405
3406            pub fn first_ja(steps) {
3407                let first = if steps.len() > 0 { steps[0] } else { {} };
3408                if first.contains("ja") { first.ja } else { "すみません" }
3409            }
3410
3411            pub fn assign_first_note(steps) {
3412                let first = {};
3413                first = if steps.len() > 0 { steps[0] } else { {} };
3414                if first.contains("note") { first.note } else { "fallback" }
3415            }
3416            "#
3417            .as_bytes()
3418            .to_vec(),
3419        )?;
3420
3421        let compiled = vm.get_fn("vm_if_empty_object_branch::first_note", &[Type::Any])?;
3422        assert_eq!(compiled.ret_ty(), &Type::Str);
3423        let first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3424
3425        let empty_steps = Dynamic::list(Vec::new());
3426        assert_eq!(unsafe { &*first_note(&empty_steps) }.as_str(), "fallback");
3427
3428        let mut step = std::collections::BTreeMap::new();
3429        step.insert("note".into(), "hello".into());
3430        let steps = Dynamic::list(vec![Dynamic::map(step)]);
3431        assert_eq!(unsafe { &*first_note(&steps) }.as_str(), "hello");
3432
3433        let compiled = vm.get_fn("vm_if_empty_object_branch::first_ja", &[Type::Any])?;
3434        assert_eq!(compiled.ret_ty(), &Type::Any);
3435        let first_ja: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3436        assert_eq!(unsafe { &*first_ja(&empty_steps) }.as_str(), "すみません");
3437
3438        let compiled = vm.get_fn("vm_if_empty_object_branch::assign_first_note", &[Type::Any])?;
3439        assert_eq!(compiled.ret_ty(), &Type::Any);
3440        let assign_first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3441        assert_eq!(unsafe { &*assign_first_note(&empty_steps) }.as_str(), "fallback");
3442        assert_eq!(unsafe { &*assign_first_note(&steps) }.as_str(), "hello");
3443        Ok(())
3444    }
3445
3446    #[test]
3447    fn list_literal_can_be_function_tail_expression() -> anyhow::Result<()> {
3448        let vm = Vm::with_all()?;
3449        vm.import_code(
3450            "vm_tail_list_literal",
3451            r#"
3452            pub fn numbers() {
3453                [1, 2, 3]
3454            }
3455
3456            pub fn maps() {
3457                [
3458                    {note: "first"},
3459                    {note: "second"}
3460                ]
3461            }
3462
3463            pub fn object_with_maps() {
3464                {
3465                    steps: [
3466                        {note: "first"},
3467                        {note: "second"}
3468                    ]
3469                }
3470            }
3471
3472            pub fn return_maps() {
3473                return [
3474                    {note: "first"},
3475                    {note: "second"}
3476                ];
3477            }
3478
3479            pub fn return_maps_without_semicolon() {
3480                return [
3481                    {note: "first"},
3482                    {note: "second"}
3483                ]
3484            }
3485
3486            pub fn tail_bare_variable() {
3487                let value = [
3488                    {note: "first"},
3489                    {note: "second"}
3490                ];
3491                value
3492            }
3493
3494            pub fn return_bare_variable_without_semicolon() {
3495                let value = [
3496                    {note: "first"},
3497                    {note: "second"}
3498                ];
3499                return value
3500            }
3501
3502            pub fn tail_object_variable() {
3503                let result = {
3504                    steps: [
3505                        {note: "first"},
3506                        {note: "second"}
3507                    ]
3508                };
3509                result
3510            }
3511            "#
3512            .as_bytes()
3513            .to_vec(),
3514        )?;
3515
3516        let compiled = vm.get_fn("vm_tail_list_literal::numbers", &[])?;
3517        assert_eq!(compiled.ret_ty(), &Type::Any);
3518        let numbers: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3519        let result = unsafe { &*numbers() };
3520        assert_eq!(result.len(), 3);
3521        assert_eq!(result.get_idx(1).and_then(|value| value.as_int()), Some(2));
3522
3523        let compiled = vm.get_fn("vm_tail_list_literal::maps", &[])?;
3524        assert_eq!(compiled.ret_ty(), &Type::Any);
3525        let maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3526        let result = unsafe { &*maps() };
3527        assert_eq!(result.len(), 2);
3528        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3529
3530        let compiled = vm.get_fn("vm_tail_list_literal::object_with_maps", &[])?;
3531        assert_eq!(compiled.ret_ty(), &Type::Any);
3532        let object_with_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3533        let result = unsafe { &*object_with_maps() };
3534        let steps = result.get_dynamic("steps").expect("steps");
3535        assert_eq!(steps.len(), 2);
3536        assert_eq!(steps.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3537
3538        let compiled = vm.get_fn("vm_tail_list_literal::return_maps", &[])?;
3539        assert_eq!(compiled.ret_ty(), &Type::Any);
3540        let return_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3541        let result = unsafe { &*return_maps() };
3542        assert_eq!(result.len(), 2);
3543        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3544
3545        let compiled = vm.get_fn("vm_tail_list_literal::return_maps_without_semicolon", &[])?;
3546        assert_eq!(compiled.ret_ty(), &Type::Any);
3547        let return_maps_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3548        let result = unsafe { &*return_maps_without_semicolon() };
3549        assert_eq!(result.len(), 2);
3550        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3551
3552        let compiled = vm.get_fn("vm_tail_list_literal::tail_bare_variable", &[])?;
3553        assert_eq!(compiled.ret_ty(), &Type::Any);
3554        let tail_bare_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3555        let result = unsafe { &*tail_bare_variable() };
3556        assert_eq!(result.len(), 2);
3557        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3558
3559        let compiled = vm.get_fn("vm_tail_list_literal::return_bare_variable_without_semicolon", &[])?;
3560        assert_eq!(compiled.ret_ty(), &Type::Any);
3561        let return_bare_variable_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3562        let result = unsafe { &*return_bare_variable_without_semicolon() };
3563        assert_eq!(result.len(), 2);
3564        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3565
3566        let compiled = vm.get_fn("vm_tail_list_literal::tail_object_variable", &[])?;
3567        assert_eq!(compiled.ret_ty(), &Type::Any);
3568        let tail_object_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3569        let result = unsafe { &*tail_object_variable() };
3570        let steps = result.get_dynamic("steps").expect("steps");
3571        assert_eq!(steps.len(), 2);
3572        assert_eq!(steps.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3573        Ok(())
3574    }
3575
3576    #[test]
3577    fn match_literals_or_guard_order_and_block_body() -> anyhow::Result<()> {
3578        let vm = Vm::with_all()?;
3579        vm.import_code(
3580            "vm_match_scalar",
3581            r#"
3582            pub fn classify(value: i64) {
3583                match value {
3584                    0i64 => 10i64,
3585                    1i64 | 2i64 => 20i64,
3586                    x if x > 10i64 => x + 100i64,
3587                    _ => -1i64,
3588                }
3589            }
3590
3591            pub fn first_arm_wins() {
3592                match 1i64 {
3593                    _ => 7i64,
3594                    1i64 => 9i64,
3595                }
3596            }
3597
3598            pub fn block_body(value: i64) {
3599                match value {
3600                    3i64 => {
3601                        let base = 4i64;
3602                        base + 5i64
3603                    },
3604                    _ => 1i64,
3605                }
3606            }
3607            "#
3608            .as_bytes()
3609            .to_vec(),
3610        )?;
3611
3612        let classify = vm.get_fn("vm_match_scalar::classify", &[Type::I64])?;
3613        assert_eq!(call_i64_1(&classify, 0), 10);
3614        assert_eq!(call_i64_1(&classify, 1), 20);
3615        assert_eq!(call_i64_1(&classify, 2), 20);
3616        assert_eq!(call_i64_1(&classify, 12), 112);
3617        assert_eq!(call_i64_1(&classify, 5), -1);
3618
3619        let first_arm_wins = vm.get_fn("vm_match_scalar::first_arm_wins", &[])?;
3620        assert_eq!(call_i64_0(&first_arm_wins), 7);
3621
3622        let block_body = vm.get_fn("vm_match_scalar::block_body", &[Type::I64])?;
3623        assert_eq!(call_i64_1(&block_body, 3), 9);
3624        assert_eq!(call_i64_1(&block_body, 4), 1);
3625        Ok(())
3626    }
3627
3628    #[test]
3629    fn match_binds_tuple_list_rest_and_struct_fields() -> anyhow::Result<()> {
3630        let vm = Vm::with_all()?;
3631        vm.import_code(
3632            "vm_match_bindings",
3633            r#"
3634            pub fn tuple_sum() {
3635                match (3i64, 4i64) {
3636                    (a, b) => a + b,
3637                    _ => 0i64,
3638                }
3639            }
3640
3641            pub fn list_rest_score() {
3642                let items = [1i64, 2i64, 3i64, 4i64];
3643                match items {
3644                    [head, second, ..tail] if tail.len() == 2 => head * 100i64 + second * 10i64 + tail[1],
3645                    _ => -1i64,
3646                }
3647            }
3648
3649            pub fn struct_field_score() {
3650                let data = {
3651                    id: 7i64,
3652                    tags: ["a", "b", "c"],
3653                    nested: { value: 5i64 }
3654                };
3655                match data {
3656                    Data { id, tags: ["a", second, ..rest], nested: Data { value } } => {
3657                        id * 100i64 + value * 10i64 + rest.len()
3658                    },
3659                    _ => -1i64,
3660                }
3661            }
3662            "#
3663            .as_bytes()
3664            .to_vec(),
3665        )?;
3666
3667        let tuple_sum = vm.get_fn("vm_match_bindings::tuple_sum", &[])?;
3668        assert_eq!(call_i64_0(&tuple_sum), 7);
3669
3670        let list_rest_score = vm.get_fn("vm_match_bindings::list_rest_score", &[])?;
3671        assert_eq!(call_i64_0(&list_rest_score), 124);
3672
3673        let struct_field_score = vm.get_fn("vm_match_bindings::struct_field_score", &[])?;
3674        assert_eq!(call_i64_0(&struct_field_score), 751);
3675        Ok(())
3676    }
3677
3678    #[test]
3679    fn match_supports_nested_expressions_and_null_miss() -> anyhow::Result<()> {
3680        let vm = Vm::with_all()?;
3681        vm.import_code(
3682            "vm_match_nested",
3683            r#"
3684            pub fn nested(value: i64) {
3685                match value {
3686                    1i64 => match "a" {
3687                        "a" => 11i64,
3688                        _ => 12i64,
3689                    },
3690                    2i64 => match [1i64, 2i64] {
3691                        [_, tail] => tail + 20i64,
3692                        _ => 0i64,
3693                    },
3694                    _ => 0i64,
3695                }
3696            }
3697
3698            pub fn no_arm(value: i64) {
3699                match value {
3700                    1i64 => 10i64,
3701                }
3702            }
3703            "#
3704            .as_bytes()
3705            .to_vec(),
3706        )?;
3707
3708        let nested = vm.get_fn("vm_match_nested::nested", &[Type::I64])?;
3709        assert_eq!(call_i64_1(&nested, 1), 11);
3710        assert_eq!(call_i64_1(&nested, 2), 22);
3711        assert_eq!(call_i64_1(&nested, 3), 0);
3712
3713        let no_arm = vm.get_fn("vm_match_nested::no_arm", &[Type::I64])?;
3714        assert_eq!(no_arm.ret_ty(), &Type::Any);
3715        let no_arm: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(no_arm.ptr()) };
3716        assert_eq!(unsafe { &*no_arm(1) }.as_int(), Some(10));
3717        assert!(unsafe { &*no_arm(2) }.is_null());
3718        Ok(())
3719    }
3720
3721    #[test]
3722    fn match_allows_any_pattern_in_or_pattern_alternatives() -> anyhow::Result<()> {
3723        // P10 放宽后:or-pattern 第二及之后的 alt 不再限制为 Literal/Wildcard。
3724        // 验证解析通过(原先会报 "or-pattern 中除第一个外只支持字面量" 错误)。
3725        // 运行时绑定语义:只取第一个 alt 的绑定,动态语言宽松规则。
3726        let vm = Vm::with_all()?;
3727        vm.import_code(
3728            "vm_match_or_any",
3729            r#"
3730            pub fn ok(value) {
3731                match value {
3732                    (a, 1i32) | (a, 2i32) => a,
3733                    _ => 0i64,
3734                }
3735            }
3736            "#
3737            .as_bytes()
3738            .to_vec(),
3739        )?;
3740        // 能编译通过即说明 P10 放宽生效(原先此代码会被 parser 拒绝)。
3741        Ok(())
3742    }
3743
3744    #[test]
3745    fn list_return_value_supports_get_idx_method_call() -> anyhow::Result<()> {
3746        let vm = Vm::with_all()?;
3747        vm.import_code(
3748            "vm_returned_list_get_idx",
3749            r#"
3750            pub fn ids() {
3751                [
3752                    "base",
3753                    "2",
3754                    "3"
3755                ]
3756            }
3757
3758            pub fn combinations() {
3759                let result = [];
3760                let values = ids();
3761                let idx = 0;
3762                while idx < values.len() {
3763                    result.push(values.get_idx(idx));
3764                    idx = idx + 1;
3765                }
3766                result
3767            }
3768            "#
3769            .as_bytes()
3770            .to_vec(),
3771        )?;
3772
3773        let compiled = vm.get_fn("vm_returned_list_get_idx::combinations", &[])?;
3774        assert_eq!(compiled.ret_ty(), &Type::Any);
3775        let combinations: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3776        let result = unsafe { &*combinations() };
3777
3778        assert_eq!(result.len(), 3);
3779        assert_eq!(result.get_idx(0).map(|value| value.as_str().to_string()), Some("base".to_string()));
3780        assert_eq!(result.get_idx(2).map(|value| value.as_str().to_string()), Some("3".to_string()));
3781        Ok(())
3782    }
3783
3784    #[test]
3785    fn repeated_deep_step_literals_import_successfully() -> anyhow::Result<()> {
3786        fn extra_page_literal(depth: usize) -> String {
3787            let mut value = "{leaf: \"done\"}".to_string();
3788            for idx in 0..depth {
3789                value = format!("{{kind: \"page\", idx: {idx}, children: [{value}], meta: {{title: \"extra\", visible: true}}}}");
3790            }
3791            value
3792        }
3793
3794        let extra = extra_page_literal(48);
3795        let code = format!(
3796            r#"
3797            pub fn script() {{
3798                return [
3799                    {{ja: "一つ目", note: "first", extra: {extra}}},
3800                    {{ja: "二つ目", note: "second", extra: {extra}}},
3801                    {{ja: "三つ目", note: "third", extra: {extra}}}
3802                ]
3803            }}
3804            "#
3805        );
3806
3807        let vm = Vm::with_all()?;
3808        vm.import_code("vm_repeated_deep_step_literals", code.into_bytes())?;
3809        let compiled = vm.get_fn("vm_repeated_deep_step_literals::script", &[])?;
3810        assert_eq!(compiled.ret_ty(), &Type::Any);
3811        let script: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3812        let result = unsafe { &*script() };
3813        assert_eq!(result.len(), 3);
3814        assert_eq!(result.get_idx(2).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("third".to_string()));
3815        Ok(())
3816    }
3817
3818    #[test]
3819    fn native_import_uses_owning_vm() -> anyhow::Result<()> {
3820        let module_path = std::env::temp_dir().join(format!("zust_vm_import_owner_{}.zs", std::process::id()));
3821        std::fs::write(&module_path, "pub fn value() { 41 }")?;
3822        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
3823
3824        let vm1 = Vm::with_all()?;
3825        vm1.import_code(
3826            "vm_import_owner",
3827            format!(
3828                r#"
3829                pub fn run() {{
3830                    import("vm_imported_owner", "{module_path}");
3831                }}
3832                "#
3833            )
3834            .into_bytes(),
3835        )?;
3836        let compiled = vm1.get_fn("vm_import_owner::run", &[])?;
3837
3838        let vm2 = Vm::with_all()?;
3839        vm2.import_code("vm_import_other", b"pub fn run() { 0 }".to_vec())?;
3840        let _ = vm2.get_fn("vm_import_other::run", &[])?;
3841
3842        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
3843        run();
3844
3845        assert!(vm1.get_fn("vm_imported_owner::value", &[]).is_ok());
3846        assert!(vm2.get_fn("vm_imported_owner::value", &[]).is_err());
3847        Ok(())
3848    }
3849
3850    #[test]
3851    fn object_last_field_call_does_not_need_trailing_comma() -> anyhow::Result<()> {
3852        let vm = Vm::with_all()?;
3853        vm.import_code(
3854            "vm_object_last_call_field",
3855            r#"
3856            pub fn extra_page() {
3857                {
3858                    title: "extra",
3859                    pages: [
3860                        {note: "nested"}
3861                    ]
3862                }
3863            }
3864
3865            pub fn data() {
3866                return [
3867                    {
3868                        note: "first",
3869                        choices: ["a", "b"],
3870                        extras: extra_page()
3871                    },
3872                    {
3873                        note: "second",
3874                        choices: ["c"],
3875                        extras: extra_page()
3876                    }
3877                ]
3878            }
3879            "#
3880            .as_bytes()
3881            .to_vec(),
3882        )?;
3883
3884        let compiled = vm.get_fn("vm_object_last_call_field::data", &[])?;
3885        assert_eq!(compiled.ret_ty(), &Type::Any);
3886        let data: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3887        let result = unsafe { &*data() };
3888        assert_eq!(result.len(), 2);
3889        let first = result.get_idx(0).expect("first step");
3890        assert_eq!(first.get_dynamic("extras").and_then(|extras| extras.get_dynamic("title")).map(|title| title.as_str().to_string()), Some("extra".to_string()));
3891        Ok(())
3892    }
3893
3894    #[test]
3895    fn string_return_survives_scope_exit() -> anyhow::Result<()> {
3896        let vm = Vm::with_all()?;
3897        vm.import_code(
3898            "vm_string_return_scope",
3899            r#"
3900            pub fn source_root() {
3901                "../assets/character/男主角换装"
3902            }
3903
3904            pub fn binary_root() {
3905                "character_binary/男主角换装"
3906            }
3907
3908            pub fn runtime_binary_url() {
3909                "/" + binary_root()
3910            }
3911
3912            pub fn action_groups() {
3913                let root = source_root();
3914                let binary_url = runtime_binary_url();
3915                let binary_root = binary_root();
3916                [
3917                    {
3918                        id: "field_bottom",
3919                        source_spine: root + "/战斗外/boy_b.spine",
3920                        skeleton: binary_url + "/战斗外/boy_b/boy_b.skel.bytes",
3921                        export_skeleton: binary_root + "/战斗外/boy_b/boy_b.skel.bytes"
3922                    }
3923                ]
3924            }
3925            "#
3926            .as_bytes()
3927            .to_vec(),
3928        )?;
3929
3930        let compiled = vm.get_fn("vm_string_return_scope::source_root", &[])?;
3931        assert_eq!(compiled.ret_ty(), &Type::Str);
3932        let source_root: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3933        let source_root = unsafe { &*source_root() };
3934        assert_eq!(source_root.as_str(), "../assets/character/男主角换装");
3935
3936        let compiled = vm.get_fn("vm_string_return_scope::action_groups", &[])?;
3937        assert_eq!(compiled.ret_ty(), &Type::Any);
3938        let action_groups: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3939        let groups = unsafe { &*action_groups() };
3940        let first = groups.get_idx(0).expect("first action group");
3941        assert_eq!(first.get_dynamic("source_spine").map(|value| value.as_str().to_string()), Some("../assets/character/男主角换装/战斗外/boy_b.spine".to_string()));
3942        assert_eq!(first.get_dynamic("skeleton").map(|value| value.as_str().to_string()), Some("/character_binary/男主角换装/战斗外/boy_b/boy_b.skel.bytes".to_string()));
3943        Ok(())
3944    }
3945
3946    #[test]
3947    fn dynamic_string_add_uses_any_binary_fast_path() -> anyhow::Result<()> {
3948        let vm = Vm::with_all()?;
3949        vm.import_code(
3950            "vm_dynamic_string_add",
3951            br#"
3952            pub fn concat(left, right) {
3953                left + right
3954            }
3955            "#
3956            .to_vec(),
3957        )?;
3958
3959        let compiled = vm.get_fn("vm_dynamic_string_add::concat", &[Type::Any, Type::Any])?;
3960        assert_eq!(compiled.ret_ty(), &Type::Any);
3961        let concat: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3962        let left = Dynamic::from("hello");
3963        let right = Dynamic::from(" world");
3964        let result = unsafe { &*concat(&left, &right) };
3965        assert_eq!(result.as_str(), "hello world");
3966        Ok(())
3967    }
3968
3969    #[test]
3970    fn large_dynamic_object_accepts_inline_call_fields() -> anyhow::Result<()> {
3971        let vm = Vm::with_all()?;
3972        let model_count = 180;
3973        let combination_count = 90;
3974        let models = (0..model_count)
3975            .map(|idx| {
3976                format!(
3977                    r#"{{id: "model_{idx}", name: "模型_{idx}", source: "/美术资源/角色/少年/套装_{idx}/模型_{idx}.model.json", parts: [
3978                        {{slot: "hair", path: "/模型/头发/颜色_{idx}/默认.png", z: 10}},
3979                        {{slot: "body", path: "/模型/身体/套装_{idx}/默认.png", z: 1}},
3980                        {{slot: "face", path: "/模型/表情/表情_{idx}/默认.png", z: 20}}
3981                    ]}}"#
3982                )
3983            })
3984            .collect::<Vec<_>>()
3985            .join(",\n");
3986        let combinations = (0..combination_count).map(|idx| format!(r#"{{hair: "color_{idx}", body: "set_{idx}", face: "face_{idx}"}}"#)).collect::<Vec<_>>().join(",\n");
3987        let code = format!(
3988            r#"
3989            pub fn source_root() {{
3990                "/美术资源/角色/少年/默认"
3991            }}
3992
3993            pub fn runtime_boy_url() {{
3994                "/cdn/runtime/角色/少年/少年.model.json"
3995            }}
3996
3997            pub fn parts() {{
3998                [
3999                    {{id: "hair", path: "/模型/头发/黑色/默认.png", z: 10}},
4000                    {{id: "body", path: "/模型/身体/校服/默认.png", z: 1}},
4001                    {{id: "face", path: "/模型/表情/微笑/默认.png", z: 20}}
4002                ]
4003            }}
4004
4005            pub fn action_groups() {{
4006                {{
4007                    idle: [
4008                        {{id: "stand", name: "站立", frames: ["待机/0001.png", "待机/0002.png"]}},
4009                        {{id: "blink", name: "眨眼", frames: ["表情/眨眼/0001.png", "表情/眨眼/0002.png"]}}
4010                    ],
4011                    move: [
4012                        {{id: "walk", name: "行走", frames: ["行走/0001.png", "行走/0002.png"]}},
4013                        {{id: "run", name: "奔跑", frames: ["奔跑/0001.png", "奔跑/0002.png"]}}
4014                    ]
4015                }}
4016            }}
4017
4018            pub fn default_model() {{
4019                {{
4020                    id: "runtime_boy",
4021                    name: "运行时少年",
4022                    skins: [
4023                        {{id: "school", title: "校服", source: "/套装/校服/model.json"}},
4024                        {{id: "casual", title: "便服", source: "/套装/便服/model.json"}}
4025                    ],
4026                    models: [
4027                        {models}
4028                    ]
4029                }}
4030            }}
4031
4032            pub fn first_nine_combinations() {{
4033                [
4034                    {combinations}
4035                ]
4036            }}
4037
4038            pub fn config() {{
4039                {{
4040                    source_root: source_root(),
4041                    runtime_boy_url: runtime_boy_url(),
4042                    parts: parts(),
4043                    action_groups: action_groups(),
4044                    default_model: default_model(),
4045                    first_nine_combinations: first_nine_combinations()
4046                }}
4047            }}
4048
4049            pub fn start() {{
4050                root::add("local/vm_large_inline_call_object/config", {{
4051                    source_root: source_root(),
4052                    runtime_boy_url: runtime_boy_url(),
4053                    parts: parts(),
4054                    action_groups: action_groups(),
4055                    default_model: default_model(),
4056                    first_nine_combinations: first_nine_combinations()
4057                }})
4058            }}
4059            "#
4060        );
4061        vm.import_code("vm_large_inline_call_object", code.into_bytes())?;
4062
4063        let compiled = vm.get_fn("vm_large_inline_call_object::config", &[])?;
4064        assert_eq!(compiled.ret_ty(), &Type::Any);
4065        let config: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4066        let result = unsafe { &*config() };
4067        assert_eq!(result.get_dynamic("source_root").map(|value| value.as_str().to_string()), Some("/美术资源/角色/少年/默认".to_string()));
4068        assert_eq!(result.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
4069
4070        let compiled = vm.get_fn("vm_large_inline_call_object::start", &[])?;
4071        assert_eq!(compiled.ret_ty(), &Type::Bool);
4072        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4073        assert!(start());
4074        let saved = root::get("local/vm_large_inline_call_object/config")?;
4075        assert_eq!(saved.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
4076        Ok(())
4077    }
4078
4079    #[cfg(feature = "http")]
4080    #[test]
4081    fn http_serve_accepts_inline_config_map() -> anyhow::Result<()> {
4082        let vm = Vm::with_all()?;
4083        vm.import_code(
4084            "vm_http_serve_inline_config",
4085            br#"
4086            pub fn start() {
4087                let server = http::serve({host: "127.0.0.1:5192"});
4088                server
4089            }
4090            "#
4091            .to_vec(),
4092        )?;
4093
4094        let compiled = vm.get_fn("vm_http_serve_inline_config::start", &[])?;
4095        assert_eq!(compiled.ret_ty(), &Type::Any);
4096        Ok(())
4097    }
4098
4099    #[cfg(feature = "http")]
4100    #[test]
4101    fn http_serve_accepts_variable_and_quoted_static_key() -> anyhow::Result<()> {
4102        let vm = Vm::with_all()?;
4103        vm.import_code(
4104            "vm_http_serve_quoted_static",
4105            br#"
4106            pub fn start(server_addr) {
4107                let http_server = http::serve({
4108                    host: server_addr,
4109                    ws: true,
4110                    upload: "upload",
4111                    "static": {
4112                        path: "/",
4113                        dir: "public/local"
4114                    }
4115                });
4116                http_server
4117            }
4118            "#
4119            .to_vec(),
4120        )?;
4121
4122        let compiled = vm.get_fn("vm_http_serve_quoted_static::start", &[Type::Any])?;
4123        assert_eq!(compiled.ret_ty(), &Type::Any);
4124        Ok(())
4125    }
4126
4127    #[cfg(all(feature = "http", feature = "llm"))]
4128    #[test]
4129    fn oss_helpers_accept_explicit_config() -> anyhow::Result<()> {
4130        let vm = Vm::with_all()?;
4131        vm.import_code(
4132            "vm_oss_explicit_config",
4133            br#"
4134            pub fn upload(oss, bytes) {
4135                oss::upload(oss, "llm/input/audio.wav", bytes)
4136            }
4137
4138            pub fn http_upload(oss, bytes) {
4139                http::upload(oss, "uploads/input.bin", bytes)
4140            }
4141
4142            pub fn link(oss, uploaded) {
4143                oss::signed_url(oss, {oss_url: uploaded, expires: 3600})
4144            }
4145            "#
4146            .to_vec(),
4147        )?;
4148
4149        assert_eq!(vm.get_fn("vm_oss_explicit_config::upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
4150        assert_eq!(vm.get_fn("vm_oss_explicit_config::http_upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
4151        assert_eq!(vm.get_fn("vm_oss_explicit_config::link", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
4152        Ok(())
4153    }
4154
4155    #[cfg(feature = "http")]
4156    #[test]
4157    fn load_script_accepts_http_serve_inline_config() -> anyhow::Result<()> {
4158        let vm = Vm::with_all()?;
4159        let (_fn_ptr, ty) = vm.load(
4160            br#"
4161            let server_addr = "127.0.0.1:5192";
4162            let http_server = http::serve({
4163                host: server_addr,
4164                ws: true,
4165                upload: "upload",
4166                "static": {
4167                    path: "/",
4168                    dir: "public/local"
4169                }
4170            });
4171            http_server
4172            "#
4173            .to_vec(),
4174            "arg".into(),
4175        )?;
4176
4177        assert_eq!(ty, Type::Any);
4178        Ok(())
4179    }
4180
4181    #[test]
4182    fn load_script_resolves_import_before_compile() -> anyhow::Result<()> {
4183        let module_path = std::env::temp_dir().join(format!("zust_vm_load_import_{}.zs", std::process::id()));
4184        std::fs::write(&module_path, "pub fn init() { return {ok: true}; }")?;
4185        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
4186
4187        let vm = Vm::with_all()?;
4188        let (_fn_ptr, ty) = vm.load(
4189            format!(
4190                r#"
4191                import("create_scene", "{module_path}");
4192                create_scene::init();
4193                "#
4194            )
4195            .into_bytes(),
4196            "req".into(),
4197        )?;
4198
4199        assert_eq!(ty, Type::Void);
4200        Ok(())
4201    }
4202
4203    #[test]
4204    fn gpu_struct_layout_packs_and_unpacks_dynamic_maps() -> anyhow::Result<()> {
4205        let vm = Vm::with_all()?;
4206        vm.import_code(
4207            "vm_gpu_layout",
4208            br#"
4209            pub struct Params {
4210                a: u32,
4211                b: u32,
4212                c: u32,
4213            }
4214            "#
4215            .to_vec(),
4216        )?;
4217
4218        let layout = vm.gpu_struct_layout("vm_gpu_layout::Params", &[])?;
4219        assert_eq!(layout.size, 16);
4220        assert_eq!(layout.fields.iter().map(|field| (field.name.as_str(), field.offset)).collect::<Vec<_>>(), vec![("a", 0), ("b", 4), ("c", 8)]);
4221
4222        let value = dynamic::map!("a"=> 1u32, "b"=> 2u32, "c"=> 3u32);
4223        let bytes = layout.pack_map(&value)?;
4224        assert_eq!(bytes.len(), 16);
4225        assert_eq!(&bytes[0..4], &1u32.to_ne_bytes());
4226        assert_eq!(&bytes[4..8], &2u32.to_ne_bytes());
4227        assert_eq!(&bytes[8..12], &3u32.to_ne_bytes());
4228
4229        let read = layout.unpack_map(&bytes)?;
4230        assert_eq!(read.get_dynamic("a").and_then(|value| value.as_uint()), Some(1));
4231        assert_eq!(read.get_dynamic("b").and_then(|value| value.as_uint()), Some(2));
4232        assert_eq!(read.get_dynamic("c").and_then(|value| value.as_uint()), Some(3));
4233        Ok(())
4234    }
4235
4236    #[test]
4237    fn root_native_calls_do_not_take_ownership_of_dynamic_args() -> anyhow::Result<()> {
4238        let vm = Vm::with_all()?;
4239        vm.import_code(
4240            "vm_root_clone_bridge",
4241            br#"
4242            pub fn add_then_reuse(arg) {
4243                let user = {
4244                    address: "test-wallet",
4245                    points: 20
4246                };
4247                root::add("local/root-clone-bridge-user", user);
4248                user.points = user.points - 7;
4249                root::add("local/root-clone-bridge-user", user);
4250                {
4251                    user: user,
4252                    points: user.points
4253                }
4254            }
4255
4256            pub fn clone_then_mutate(arg) {
4257                let user = {
4258                    profile: {
4259                        points: 20
4260                    }
4261                };
4262                let copied = user.clone();
4263                copied.profile.points = 13;
4264                user
4265            }
4266            "#
4267            .to_vec(),
4268        )?;
4269
4270        let compiled = vm.get_fn("vm_root_clone_bridge::add_then_reuse", &[Type::Any])?;
4271        assert_eq!(compiled.ret_ty(), &Type::Any);
4272        let add_then_reuse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4273        let arg = Dynamic::Null;
4274        let result = add_then_reuse(&arg);
4275        let result = unsafe { &*result };
4276
4277        assert_eq!(result.get_dynamic("points").and_then(|value| value.as_int()), Some(13));
4278        let mut json = String::new();
4279        result.to_json(&mut json);
4280        assert!(json.contains("\"points\": 13"));
4281
4282        let clone_then_mutate = vm.get_fn("vm_root_clone_bridge::clone_then_mutate", &[Type::Any])?;
4283        let clone_then_mutate: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(clone_then_mutate.ptr()) };
4284        let result = clone_then_mutate(&arg);
4285        let result = unsafe { &*result };
4286        assert_eq!(result.get_dynamic("profile").unwrap().get_dynamic("points").and_then(|value| value.as_int()), Some(20));
4287        Ok(())
4288    }
4289
4290    struct CounterForTypedReceiver {
4291        value: i64,
4292    }
4293
4294    extern "C" fn counter_for_typed_receiver_get(value: *const Dynamic) -> i64 {
4295        unsafe { &*value }.as_custom::<CounterForTypedReceiver>().map(|counter| counter.value).unwrap_or(-1)
4296    }
4297
4298    struct NavMapForFunctionArg;
4299
4300    extern "C" fn nav_map_for_function_arg_new() -> *const Dynamic {
4301        Box::into_raw(Box::new(Dynamic::custom(NavMapForFunctionArg)))
4302    }
4303
4304    #[derive(Debug, Default)]
4305    struct PropertyForwardingObject {
4306        values: parking_lot::RwLock<BTreeMap<String, Dynamic>>,
4307    }
4308
4309    impl CustomProperty for PropertyForwardingObject {
4310        fn get_key(&self, key: &str) -> Option<Dynamic> {
4311            self.values.read().get(key).cloned()
4312        }
4313
4314        fn set_key(&self, key: &str, value: Dynamic) -> bool {
4315            self.values.write().insert(key.to_string(), value);
4316            true
4317        }
4318    }
4319
4320    extern "C" fn property_forwarding_object_new() -> *const Dynamic {
4321        Box::into_raw(Box::new(Dynamic::custom_with_properties(PropertyForwardingObject::default())))
4322    }
4323
4324    #[test]
4325    fn typed_receiver_method_call_dispatches_with_type_hint() -> anyhow::Result<()> {
4326        let vm = Vm::with_all()?;
4327        vm.add_empty_type("Counter")?;
4328        let counter_ty = vm.get_symbol("Counter", Vec::new())?;
4329        vm.add_native_method_ptr("Counter", "get", &[counter_ty], Type::I64, counter_for_typed_receiver_get as *const u8)?;
4330        vm.import_code(
4331            "vm_typed_receiver_method",
4332            br#"
4333            pub fn run(value) {
4334                value::<Counter>::get()
4335            }
4336            "#
4337            .to_vec(),
4338        )?;
4339
4340        let compiled = vm.get_fn("vm_typed_receiver_method::run", &[Type::Any])?;
4341        assert_eq!(compiled.ret_ty(), &Type::I64);
4342        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4343        let value = Dynamic::custom(CounterForTypedReceiver { value: 42 });
4344
4345        assert_eq!(run(&value), 42);
4346        Ok(())
4347    }
4348
4349    #[test]
4350    fn native_custom_object_can_be_passed_to_zs_function() -> anyhow::Result<()> {
4351        let vm = Vm::with_all()?;
4352        vm.add_empty_type("NavMap")?;
4353        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
4354        vm.import_code(
4355            "vm_native_custom_arg",
4356            br#"
4357            pub fn add_nav_spawns(world, navmap) {
4358                navmap
4359            }
4360
4361            pub fn run(world) {
4362                let navmap = NavMap::new();
4363                let with_spawns = add_nav_spawns(world, navmap);
4364                with_spawns
4365            }
4366            "#
4367            .to_vec(),
4368        )?;
4369
4370        let compiled = vm.get_fn("vm_native_custom_arg::run", &[Type::Any])?;
4371        assert_eq!(compiled.ret_ty(), &Type::Any);
4372        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4373        let world = Dynamic::Null;
4374        let result = run(&world);
4375        let result = unsafe { &*result };
4376
4377        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
4378        Ok(())
4379    }
4380
4381    #[test]
4382    fn any_field_assignment_forwards_to_custom_properties() -> anyhow::Result<()> {
4383        let vm = Vm::with_all()?;
4384        vm.add_empty_type("Dialog")?;
4385        vm.add_native_method_ptr("Dialog", "new", &[], Type::Any, property_forwarding_object_new as *const u8)?;
4386        vm.import_code(
4387            "vm_custom_property_forwarding",
4388            br#"
4389            pub fn run() {
4390                let dialog = Dialog::new();
4391                dialog.file_mode = 3;
4392                dialog.file_mode
4393            }
4394            "#
4395            .to_vec(),
4396        )?;
4397
4398        let compiled = vm.get_fn("vm_custom_property_forwarding::run", &[])?;
4399        assert_eq!(compiled.ret_ty(), &Type::Any);
4400        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4401        let result = unsafe { &*run() };
4402
4403        assert_eq!(result.as_int(), Some(3));
4404        Ok(())
4405    }
4406
4407    #[test]
4408    fn native_custom_object_typed_local_can_be_passed_to_zs_function() -> anyhow::Result<()> {
4409        let vm = Vm::with_all()?;
4410        vm.add_empty_type("NavMap")?;
4411        let _nav_map_ty = vm.get_symbol("NavMap", Vec::new())?;
4412        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
4413        vm.import_code(
4414            "vm_native_custom_typed_arg",
4415            br#"
4416            pub fn add_nav_spawns(world, navmap) {
4417                navmap
4418            }
4419
4420            pub fn run(world) {
4421                let navmap: NavMap = NavMap::new();
4422                let with_spawns = add_nav_spawns(world, navmap);
4423                with_spawns
4424            }
4425            "#
4426            .to_vec(),
4427        )?;
4428
4429        let compiled = vm.get_fn("vm_native_custom_typed_arg::run", &[Type::Any])?;
4430        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4431        let world = Dynamic::Null;
4432        let result = run(&world);
4433        let result = unsafe { &*result };
4434
4435        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
4436        Ok(())
4437    }
4438
4439    // ---- 新增边界条件测试 ----
4440
4441    #[test]
4442    fn dynamic_type_checks_on_null_and_primitive_values() -> anyhow::Result<()> {
4443        let vm = Vm::with_all()?;
4444        vm.import_code(
4445            "vm_dynamic_type_checks",
4446            br#"
4447            pub fn is_list_on_int() {
4448                let x = 42i64;
4449                x.is_list()
4450            }
4451
4452            pub fn is_map_on_int() {
4453                let x = 42i64;
4454                x.is_map()
4455            }
4456
4457            pub fn is_null_on_int() {
4458                let x = 42i64;
4459                x.is_null()
4460            }
4461            "#
4462            .to_vec(),
4463        )?;
4464
4465        let compiled = vm.get_fn("vm_dynamic_type_checks::is_list_on_int", &[])?;
4466        assert_eq!(compiled.ret_ty(), &Type::Bool);
4467        let is_list_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4468        assert!(!is_list_on_int());
4469
4470        let compiled = vm.get_fn("vm_dynamic_type_checks::is_map_on_int", &[])?;
4471        assert_eq!(compiled.ret_ty(), &Type::Bool);
4472        let is_map_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4473        assert!(!is_map_on_int());
4474
4475        let compiled = vm.get_fn("vm_dynamic_type_checks::is_null_on_int", &[])?;
4476        assert_eq!(compiled.ret_ty(), &Type::Bool);
4477        let is_null_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4478        assert!(!is_null_on_int());
4479        Ok(())
4480    }
4481
4482    #[test]
4483    fn void_and_null_are_false_in_boolean_context() -> anyhow::Result<()> {
4484        let vm = Vm::with_all()?;
4485        vm.import_code(
4486            "vm_void_bool_context",
4487            br#"
4488            pub fn run() {
4489                let items = [1i32, 2i32];
4490                let ok1 = !(items.push(3i32) && false);
4491                let ok2 = !(true && items.push(4i32));
4492                let ok3 = null || true;
4493                let ok4 = null || items.len() == 4;
4494                ok1 && ok2 && ok3 && ok4
4495            }
4496            "#
4497            .to_vec(),
4498        )?;
4499
4500        let compiled = vm.get_fn("vm_void_bool_context::run", &[])?;
4501        assert_eq!(compiled.ret_ty(), &Type::Bool);
4502        let run: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4503        assert!(run());
4504        Ok(())
4505    }
4506
4507    #[test]
4508    fn empty_for_loop_range_has_zero_iterations() -> anyhow::Result<()> {
4509        let vm = Vm::with_all()?;
4510        vm.import_code(
4511            "vm_empty_for_range",
4512            br#"
4513            pub fn empty_exclusive() {
4514                let count = 0i32;
4515                for i in 0..0 {
4516                    count += i;
4517                }
4518                count
4519            }
4520
4521            pub fn single_inclusive_iteration() {
4522                let count = 0i32;
4523                for i in 5..=5 {
4524                    count += i;
4525                }
4526                count
4527            }
4528            "#
4529            .to_vec(),
4530        )?;
4531
4532        // 无后缀 range 字面量(0..0 / 5..=5)默认 I64,累加器随复合赋值提升为 I64
4533        let compiled = vm.get_fn("vm_empty_for_range::empty_exclusive", &[])?;
4534        assert_eq!(compiled.ret_ty(), &Type::I64);
4535        let empty_exclusive: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4536        assert_eq!(empty_exclusive(), 0);
4537
4538        let compiled = vm.get_fn("vm_empty_for_range::single_inclusive_iteration", &[])?;
4539        assert_eq!(compiled.ret_ty(), &Type::I64);
4540        let single_inclusive: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4541        assert_eq!(single_inclusive(), 5);
4542        Ok(())
4543    }
4544
4545    #[test]
4546    fn for_loop_range_accepts_dynamic_i64_bounds() -> anyhow::Result<()> {
4547        let vm = Vm::with_all()?;
4548        vm.import_code(
4549            "vm_dynamic_for_range",
4550            br#"
4551            pub fn main() {
4552                let view = {};
4553                view.grid_min_x = -2i64;
4554                view.grid_max_x = 2i64;
4555
4556                let end_x = view.grid_max_x + 1i64;
4557                let count = 0i64;
4558
4559                for x in view.grid_min_x..end_x {
4560                    count += 1i64;
4561                }
4562
4563                count
4564            }
4565            "#
4566            .to_vec(),
4567        )?;
4568
4569        let compiled = vm.get_fn("vm_dynamic_for_range::main", &[])?;
4570        assert_eq!(compiled.ret_ty(), &Type::I64);
4571        let main: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4572        assert_eq!(main(), 5);
4573        Ok(())
4574    }
4575
4576    #[test]
4577    fn map_contains_key_on_non_existent_and_nested_keys() -> anyhow::Result<()> {
4578        let vm = Vm::with_all()?;
4579        vm.import_code(
4580            "vm_map_contains",
4581            br#"
4582            pub fn contains_existing(data) {
4583                data.contains("name")
4584            }
4585
4586            pub fn contains_missing(data) {
4587                data.contains("nothing")
4588            }
4589            "#
4590            .to_vec(),
4591        )?;
4592
4593        let compiled = vm.get_fn("vm_map_contains::contains_existing", &[Type::Any])?;
4594        assert_eq!(compiled.ret_ty(), &Type::Bool);
4595        let contains_existing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4596        let data = dynamic::map!("name"=> "test");
4597        assert!(contains_existing(&data));
4598
4599        let compiled = vm.get_fn("vm_map_contains::contains_missing", &[Type::Any])?;
4600        assert_eq!(compiled.ret_ty(), &Type::Bool);
4601        let contains_missing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4602        assert!(!contains_missing(&data));
4603        Ok(())
4604    }
4605
4606    #[test]
4607    fn list_pop_on_empty_list_returns_null() -> anyhow::Result<()> {
4608        let vm = Vm::with_all()?;
4609        vm.import_code(
4610            "vm_pop_empty",
4611            br#"
4612            pub fn pop_new_list() {
4613                let items = [];
4614                let value = items.pop();
4615                let still_empty = items.len() == 0;
4616                {value: value, empty: still_empty}
4617            }
4618
4619            pub fn pop_until_empty() {
4620                let items = [1i64, 2i64];
4621                items.pop();
4622                let last = items.pop();
4623                let drained = items.pop();
4624                {last: last, drained: drained}
4625            }
4626            "#
4627            .to_vec(),
4628        )?;
4629
4630        let compiled = vm.get_fn("vm_pop_empty::pop_new_list", &[])?;
4631        assert_eq!(compiled.ret_ty(), &Type::Any);
4632        let pop_new_list: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4633        let result = unsafe { &*pop_new_list() };
4634        assert!(result.get_dynamic("value").is_some_and(|v| v.is_null()));
4635        assert_eq!(result.get_dynamic("empty").and_then(|v| v.as_bool()), Some(true));
4636
4637        let compiled = vm.get_fn("vm_pop_empty::pop_until_empty", &[])?;
4638        assert_eq!(compiled.ret_ty(), &Type::Any);
4639        let pop_until_empty: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4640        let result = unsafe { &*pop_until_empty() };
4641        assert_eq!(result.get_dynamic("last").and_then(|v| v.as_int()), Some(1));
4642        assert!(result.get_dynamic("drained").is_some_and(|v| v.is_null()));
4643        Ok(())
4644    }
4645
4646    #[test]
4647    fn void_function_with_multiple_code_paths() -> anyhow::Result<()> {
4648        let vm = Vm::with_all()?;
4649        vm.import_code(
4650            "vm_void_multi_path",
4651            br#"
4652            pub fn log_if_positive(value: i64) {
4653                if value > 0 {
4654                    print(value);
4655                    return;
4656                }
4657                if value < 0 {
4658                    print(-value);
4659                    return;
4660                }
4661                print(0);
4662            }
4663            "#
4664            .to_vec(),
4665        )?;
4666
4667        let compiled = vm.get_fn("vm_void_multi_path::log_if_positive", &[Type::I64])?;
4668        assert!(compiled.ret_ty().is_void());
4669        Ok(())
4670    }
4671
4672    #[test]
4673    fn any_method_call_chain_on_returned_dynamic_value() -> anyhow::Result<()> {
4674        let vm = Vm::with_all()?;
4675        vm.import_code(
4676            "vm_any_method_chain",
4677            br#"
4678            pub fn get_tags(data) {
4679                let tags = data.tags;
4680                if tags.is_list() {
4681                    return tags.len();
4682                }
4683                0
4684            }
4685            "#
4686            .to_vec(),
4687        )?;
4688
4689        let compiled = vm.get_fn("vm_any_method_chain::get_tags", &[Type::Any])?;
4690        assert_eq!(compiled.ret_ty(), &Type::I64);
4691        let get_tags: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4692        let data = dynamic::map!("tags"=> Dynamic::list(vec!["a".into(), "b".into(), "c".into()]));
4693        assert_eq!(get_tags(&data), 3);
4694
4695        let empty_data = Dynamic::Null;
4696        assert_eq!(get_tags(&empty_data), 0);
4697        Ok(())
4698    }
4699
4700    #[test]
4701    fn infers_any_arg_function_return_before_body_compile() -> anyhow::Result<()> {
4702        let vm = Vm::with_all()?;
4703        vm.import_code(
4704            "vm_infer_any_arg_return",
4705            br#"
4706            pub fn caller(candidate) {
4707                let center = polygon_center(candidate.visualPolygon);
4708                center[0]
4709            }
4710
4711            pub fn polygon_center(point_list) {
4712                let total_x = 0;
4713                let total_y = 0;
4714                let count = 0;
4715                if point_list.is_list() {
4716                    for point in point_list {
4717                        if point.is_list() && point.len() >= 2 {
4718                            total_x += point[0];
4719                            total_y += point[1];
4720                            count += 1;
4721                        }
4722                    }
4723                }
4724                if count == 0 {
4725                    return [0, 0];
4726                }
4727                [total_x / count, total_y / count]
4728            }
4729            "#
4730            .to_vec(),
4731        )?;
4732
4733        let compiled = vm.get_fn("vm_infer_any_arg_return::caller", &[Type::Any])?;
4734        assert_eq!(compiled.ret_ty(), &Type::Any);
4735        let caller: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4736        let candidate = dynamic::map!(
4737            "visualPolygon"=> Dynamic::list(vec![
4738                Dynamic::list(vec![2i64.into(), 4i64.into()]),
4739                Dynamic::list(vec![6i64.into(), 8i64.into()]),
4740            ])
4741        );
4742        let result = unsafe { &*caller(&candidate) };
4743        assert_eq!(result.as_int(), Some(4));
4744        Ok(())
4745    }
4746
4747    #[test]
4748    fn recursive_factorial_keeps_static_return_type() -> anyhow::Result<()> {
4749        let vm = Vm::with_all()?;
4750        vm.import_code(
4751            "vm_recursive_factorial",
4752            br#"
4753            fn factorial(n: i64) {
4754                if n <= 1 {
4755                    return 1;
4756                }
4757                n * factorial(n - 1)
4758            }
4759
4760            pub fn run(n: i64) {
4761                factorial(n)
4762            }
4763            "#
4764            .to_vec(),
4765        )?;
4766
4767        let compiled = vm.get_fn("vm_recursive_factorial::run", &[Type::I64])?;
4768        assert_eq!(compiled.ret_ty(), &Type::I64);
4769        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4770        assert_eq!(run(5), 120);
4771        Ok(())
4772    }
4773
4774    #[test]
4775    fn explicit_const_generic_function_calls_generate_distinct_variants() -> anyhow::Result<()> {
4776        let vm = Vm::with_all()?;
4777        vm.import_code(
4778            "vm_generic_const_variants",
4779            br#"
4780            fn value<N>() {
4781                N
4782            }
4783
4784            pub fn two() {
4785                value::<2>()
4786            }
4787
4788            pub fn three() {
4789                value::<3>()
4790            }
4791            "#
4792            .to_vec(),
4793        )?;
4794
4795        let compiled = vm.get_fn("vm_generic_const_variants::two", &[])?;
4796        assert_eq!(compiled.ret_ty(), &Type::I32);
4797        let two: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4798        assert_eq!(two(), 2);
4799
4800        let compiled = vm.get_fn("vm_generic_const_variants::three", &[])?;
4801        assert_eq!(compiled.ret_ty(), &Type::I32);
4802        let three: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4803        assert_eq!(three(), 3);
4804        Ok(())
4805    }
4806
4807    #[test]
4808    fn generic_function_body_resolves_private_generic_helper_after_import() -> anyhow::Result<()> {
4809        let vm = Vm::with_all()?;
4810        vm.import_code(
4811            "vm_generic_private_helper",
4812            br#"
4813            fn helper<N>() {
4814                N
4815            }
4816
4817            pub fn bench<N>() {
4818                helper::<N>()
4819            }
4820            "#
4821            .to_vec(),
4822        )?;
4823
4824        let compiled = vm.get_fn_with_params("vm_generic_private_helper::bench", &[], &[Type::ConstInt(7)])?;
4825        assert_eq!(compiled.ret_ty(), &Type::I32);
4826        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4827        assert_eq!(run(), 7);
4828        Ok(())
4829    }
4830
4831    #[test]
4832    fn const_generic_repeat_array_initializes_all_items() -> anyhow::Result<()> {
4833        let vm = Vm::with_all()?;
4834        vm.import_code(
4835            "vm_generic_repeat_array",
4836            br#"
4837            fn bench<N>() {
4838                let is_prime = [true; N];
4839                is_prime[0] = false;
4840                is_prime[1] = false;
4841                let count = 0i64;
4842                for p in 2i64..N {
4843                    if is_prime[p] == true {
4844                        count = count + 1;
4845                        let step = p;
4846                        let j = p * p;
4847                        while j < N {
4848                            is_prime[j] = false;
4849                            j = j + step;
4850                        }
4851                    }
4852                }
4853                count
4854            }
4855
4856            pub fn run() {
4857                bench::<10>()
4858            }
4859
4860            pub fn run_1000() {
4861                bench::<1000>()
4862            }
4863
4864            pub fn run_100000() {
4865                bench::<100000>()
4866            }
4867            "#
4868            .to_vec(),
4869        )?;
4870
4871        let compiled = vm.get_fn("vm_generic_repeat_array::run", &[])?;
4872        assert_eq!(compiled.ret_ty(), &Type::I64);
4873        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4874        assert_eq!(run(), 4);
4875
4876        let compiled = vm.get_fn("vm_generic_repeat_array::run_1000", &[])?;
4877        assert_eq!(compiled.ret_ty(), &Type::I64);
4878        let run_1000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4879        assert_eq!(run_1000(), 168);
4880
4881        let compiled = vm.get_fn("vm_generic_repeat_array::run_100000", &[])?;
4882        assert_eq!(compiled.ret_ty(), &Type::I64);
4883        let run_100000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4884        assert_eq!(run_100000(), 9592);
4885        Ok(())
4886    }
4887
4888    #[test]
4889    fn repeat_array_initializes_scalar_patterns() -> anyhow::Result<()> {
4890        let vm = Vm::with_all()?;
4891        vm.import_code(
4892            "vm_repeat_scalar_patterns",
4893            br#"
4894            pub fn count_true() {
4895                let items = [true; 100000];
4896                let count = 0i64;
4897                for idx in 0i64..100000 {
4898                    if items[idx] == true {
4899                        count = count + 1;
4900                    }
4901                }
4902                count
4903            }
4904
4905            pub fn i32_pair() {
4906                let items = [-7i32; 1000];
4907                items[0i64] + items[999i64]
4908            }
4909
4910            pub fn i64_pair() {
4911                let items = [1234567890123i64; 1000];
4912                items[0i64] + items[999i64]
4913            }
4914
4915            pub fn f64_pair() {
4916                let items = [1.5f64; 1000];
4917                items[0i64] + items[999i64]
4918            }
4919            "#
4920            .to_vec(),
4921        )?;
4922
4923        let compiled = vm.get_fn("vm_repeat_scalar_patterns::count_true", &[])?;
4924        assert_eq!(compiled.ret_ty(), &Type::I64);
4925        let count_true: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4926        assert_eq!(count_true(), 100000);
4927
4928        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i32_pair", &[])?;
4929        assert_eq!(compiled.ret_ty(), &Type::I32);
4930        let i32_pair: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4931        assert_eq!(i32_pair(), -14);
4932
4933        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i64_pair", &[])?;
4934        assert_eq!(compiled.ret_ty(), &Type::I64);
4935        let i64_pair: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4936        assert_eq!(i64_pair(), 2469135780246);
4937
4938        let compiled = vm.get_fn("vm_repeat_scalar_patterns::f64_pair", &[])?;
4939        assert_eq!(compiled.ret_ty(), &Type::F64);
4940        let f64_pair: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
4941        assert_eq!(f64_pair(), 3.0);
4942        Ok(())
4943    }
4944
4945    #[test]
4946    fn bool_array_store_normalizes_condition_values() -> anyhow::Result<()> {
4947        let vm = Vm::with_all()?;
4948        vm.import_code(
4949            "vm_bool_array_store",
4950            br#"
4951            pub fn run() {
4952                let items = [false; 4];
4953                items[1] = 3i64 > 2i64;
4954                items[2] = 3i64 < 2i64;
4955                if items[1] == true && items[2] == false {
4956                    1i64
4957                } else {
4958                    0i64
4959                }
4960            }
4961            "#
4962            .to_vec(),
4963        )?;
4964
4965        let compiled = vm.get_fn("vm_bool_array_store::run", &[])?;
4966        assert_eq!(compiled.ret_ty(), &Type::I64);
4967        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4968        assert_eq!(run(), 1);
4969        Ok(())
4970    }
4971
4972    #[test]
4973    fn bool_array_large_sequential_writes() -> anyhow::Result<()> {
4974        let vm = Vm::with_all()?;
4975        vm.import_code(
4976            "vm_bool_array_large_writes",
4977            br#"
4978            pub fn run() {
4979                let items = [true; 100000];
4980                for idx in 0i64..100000 {
4981                    items[idx] = false;
4982                }
4983                let count = 0i64;
4984                for idx in 0i64..100000 {
4985                    if items[idx] == false {
4986                        count = count + 1;
4987                    }
4988                }
4989                count
4990            }
4991            "#
4992            .to_vec(),
4993        )?;
4994
4995        let compiled = vm.get_fn("vm_bool_array_large_writes::run", &[])?;
4996        assert_eq!(compiled.ret_ty(), &Type::I64);
4997        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4998        assert_eq!(run(), 100000);
4999        Ok(())
5000    }
5001
5002    #[test]
5003    fn bool_array_sieve_style_indices_stay_in_bounds() -> anyhow::Result<()> {
5004        let vm = Vm::with_all()?;
5005        vm.import_code(
5006            "vm_bool_array_sieve_indices",
5007            br#"
5008            pub fn run() {
5009                let items = [true; 100000];
5010                let writes = 0i64;
5011                for p in 2i64..100000 {
5012                    let step = p;
5013                    let j = p * p;
5014                    while j < 100000 {
5015                        items[j] = false;
5016                        writes = writes + 1;
5017                        j = j + step;
5018                    }
5019                }
5020                writes
5021            }
5022            "#
5023            .to_vec(),
5024        )?;
5025
5026        let compiled = vm.get_fn("vm_bool_array_sieve_indices::run", &[])?;
5027        assert_eq!(compiled.ret_ty(), &Type::I64);
5028        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5029        assert!(run() > 0);
5030        Ok(())
5031    }
5032
5033    #[test]
5034    fn sieve_style_indices_compute_in_bounds_without_array_write() -> anyhow::Result<()> {
5035        let vm = Vm::with_all()?;
5036        vm.import_code(
5037            "vm_sieve_indices_no_write",
5038            br#"
5039            pub fn run() {
5040                let max_j = 0i64;
5041                for p in 2i64..100000 {
5042                    let step = p;
5043                    let j = p * p;
5044                    while j < 100000 {
5045                        if j < 0i64 {
5046                            return -1i64;
5047                        }
5048                        if j > max_j {
5049                            max_j = j;
5050                        }
5051                        j = j + step;
5052                    }
5053                }
5054                max_j
5055            }
5056            "#
5057            .to_vec(),
5058        )?;
5059
5060        let compiled = vm.get_fn("vm_sieve_indices_no_write::run", &[])?;
5061        assert_eq!(compiled.ret_ty(), &Type::I64);
5062        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5063        assert_eq!(run(), 99999);
5064        Ok(())
5065    }
5066
5067    #[test]
5068    fn dynamic_list_index_sum_uses_static_accumulator_type() -> anyhow::Result<()> {
5069        let vm = Vm::with_all()?;
5070        vm.import_code(
5071            "vm_dynamic_index_sum",
5072            br#"
5073            pub fn sum_list(n: i64) {
5074                let l = [];
5075                for i in 0..n {
5076                    l.push(i);
5077                }
5078                let sum = 0i64;
5079                for j in 0..n {
5080                    sum = sum + l[j];
5081                }
5082                sum
5083            }
5084            "#
5085            .to_vec(),
5086        )?;
5087
5088        let compiled = vm.get_fn("vm_dynamic_index_sum::sum_list", &[Type::I64])?;
5089        let sum_list_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_dynamic_index_sum::sum_list")?;
5090        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_list_id, &[], &[Type::I64]);
5091        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I64)), "local type hints: {:?}", hints);
5092        assert_eq!(compiled.ret_ty(), &Type::I64);
5093        let sum_list: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5094        assert_eq!(sum_list(1000), 499500);
5095        Ok(())
5096    }
5097
5098    #[test]
5099    fn loop_pushed_list_is_typed_vector() -> anyhow::Result<()> {
5100        let vm = Vm::with_all()?;
5101        vm.import_code(
5102            "vm_loop_pushed_list",
5103            br#"
5104            pub fn make(n: i64) {
5105                let l = [];
5106                for i in 0..n {
5107                    l.push(i);
5108                }
5109                l
5110            }
5111            "#
5112            .to_vec(),
5113        )?;
5114        let compiled = vm.get_fn("vm_loop_pushed_list::make", &[Type::I64])?;
5115        let make: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5116        let result = unsafe { &*make(3) };
5117        assert!(matches!(result, Dynamic::VecI64(v) if v == &vec![0, 1, 2]), "expected flat VecI64, got: {:?}", result);
5118        Ok(())
5119    }
5120
5121    #[test]
5122    fn inferred_empty_list_uses_typed_dynamic_vector() -> anyhow::Result<()> {
5123        let vm = Vm::with_all()?;
5124        vm.import_code(
5125            "vm_inferred_typed_list",
5126            br#"
5127            pub fn make() {
5128                let l = [];
5129                l.push(1i64);
5130                l
5131            }
5132            "#
5133            .to_vec(),
5134        )?;
5135
5136        let compiled = vm.get_fn("vm_inferred_typed_list::make", &[])?;
5137        assert_eq!(compiled.ret_ty(), &Type::Any);
5138        let make: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5139        let result = unsafe { &*make() };
5140        assert!(matches!(result, Dynamic::VecI64(values) if values == &vec![1]), "result: {:?}", result);
5141        Ok(())
5142    }
5143
5144    #[test]
5145    fn for_in_iterates_list_filled_in_same_function() -> anyhow::Result<()> {
5146        let vm = Vm::with_all()?;
5147        vm.import_code(
5148            "vm_for_in_local_pushed_list",
5149            br#"
5150            pub fn sum_i32_items() {
5151                let items = [];
5152                items.push(6000i32);
5153                items.push(4000i32);
5154                let total = 0i32;
5155                for item in items {
5156                    total += item;
5157                }
5158                total
5159            }
5160
5161            pub fn sum_split_bps() {
5162                let splits = [];
5163                splits.push({ bps: "6000" });
5164                splits.push({ bps: 4000 });
5165                let total = 0i32;
5166                let count = 0i32;
5167                for split in splits {
5168                    total += split.bps as i32;
5169                    count += 1i32;
5170                }
5171                total + count
5172            }
5173            "#
5174            .to_vec(),
5175        )?;
5176
5177        let compiled = vm.get_fn("vm_for_in_local_pushed_list::sum_i32_items", &[])?;
5178        assert_eq!(compiled.ret_ty(), &Type::I32);
5179        let sum_i32_items: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5180        assert_eq!(sum_i32_items(), 10000);
5181
5182        let compiled = vm.get_fn("vm_for_in_local_pushed_list::sum_split_bps", &[])?;
5183        assert_eq!(compiled.ret_ty(), &Type::I32);
5184        let sum_split_bps: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5185        assert_eq!(sum_split_bps(), 10002);
5186        Ok(())
5187    }
5188
5189    #[test]
5190    fn inferred_list_shortcuts_cover_scalar_types() -> anyhow::Result<()> {
5191        let vm = Vm::with_all()?;
5192        vm.import_code(
5193            "vm_inferred_list_shortcuts",
5194            br#"
5195            pub fn second_bool() {
5196                let l = [];
5197                l.push(true);
5198                l.push(false);
5199                l[1]
5200            }
5201
5202            pub fn first_u8() {
5203                let l = [];
5204                l.push(7u8);
5205                l[0]
5206            }
5207
5208            pub fn sum_u8_for_in() {
5209                let l = [];
5210                l.push(7u8);
5211                l.push(8u8);
5212                let sum = 0i64;
5213                for item in l {
5214                    sum = sum + item as i64;
5215                }
5216                sum
5217            }
5218
5219            pub fn count_bool_for_in() {
5220                let l = [];
5221                l.push(true);
5222                l.push(false);
5223                l.push(true);
5224                let count = 0i64;
5225                for item in l {
5226                    if item {
5227                        count += 1i64;
5228                    }
5229                }
5230                count
5231            }
5232
5233            pub fn sum_i32(n: i64) {
5234                let l = [];
5235                for i in 0..n {
5236                    l.push(i as i32);
5237                }
5238                let sum = 0i32;
5239                for j in 0..n {
5240                    sum = sum + l[j];
5241                }
5242                sum
5243            }
5244
5245            pub fn sum_f32(n: i64) {
5246                let l = [];
5247                for i in 0..n {
5248                    l.push(i as f32);
5249                }
5250                let sum = 0f32;
5251                for j in 0..n {
5252                    sum = sum + l[j];
5253                }
5254                sum
5255            }
5256
5257            pub fn second_str() {
5258                let l = [];
5259                l.push("first");
5260                l.push("second");
5261                l[1]
5262            }
5263            "#
5264            .to_vec(),
5265        )?;
5266
5267        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_bool", &[])?;
5268        let second_bool_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::second_bool")?;
5269        let hints = vm.jit.write().compiler.inferred_local_type_hints(second_bool_id, &[], &[]);
5270        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Bool)), "bool local type hints: {:?}", hints);
5271        assert_eq!(compiled.ret_ty(), &Type::Bool);
5272        let second_bool: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5273        assert!(!second_bool());
5274
5275        let compiled = vm.get_fn("vm_inferred_list_shortcuts::first_u8", &[])?;
5276        let first_u8_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::first_u8")?;
5277        let hints = vm.jit.write().compiler.inferred_local_type_hints(first_u8_id, &[], &[]);
5278        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::U8)), "u8 local type hints: {:?}", hints);
5279        assert_eq!(compiled.ret_ty(), &Type::U8);
5280        let first_u8: extern "C" fn() -> u8 = unsafe { std::mem::transmute(compiled.ptr()) };
5281        assert_eq!(first_u8(), 7);
5282
5283        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_u8_for_in", &[])?;
5284        assert_eq!(compiled.ret_ty(), &Type::I64);
5285        let sum_u8_for_in: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5286        assert_eq!(sum_u8_for_in(), 15);
5287
5288        let compiled = vm.get_fn("vm_inferred_list_shortcuts::count_bool_for_in", &[])?;
5289        assert_eq!(compiled.ret_ty(), &Type::I64);
5290        let count_bool_for_in: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5291        assert_eq!(count_bool_for_in(), 2);
5292
5293        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_i32", &[Type::I64])?;
5294        let sum_i32_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::sum_i32")?;
5295        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_i32_id, &[], &[Type::I64]);
5296        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I32)), "i32 local type hints: {:?}", hints);
5297        assert_eq!(compiled.ret_ty(), &Type::I32);
5298        let sum_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5299        assert_eq!(sum_i32(100), 4950);
5300
5301        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_f32", &[Type::I64])?;
5302        let sum_f32_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::sum_f32")?;
5303        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_f32_id, &[], &[Type::I64]);
5304        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::F32)), "f32 local type hints: {:?}", hints);
5305        assert_eq!(compiled.ret_ty(), &Type::F32);
5306        let sum_f32: extern "C" fn(i64) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
5307        assert_eq!(sum_f32(10), 45.0);
5308
5309        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_str", &[])?;
5310        let second_str_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::second_str")?;
5311        let hints = vm.jit.write().compiler.inferred_local_type_hints(second_str_id, &[], &[]);
5312        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Str)), "str local type hints: {:?}", hints);
5313        assert_eq!(compiled.ret_ty(), &Type::Str);
5314        let second_str: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5315        let result = unsafe { &*second_str() };
5316        assert_eq!(result.as_str(), "second");
5317        Ok(())
5318    }
5319
5320    #[test]
5321    fn inferred_list_supports_bracket_set_idx() -> anyhow::Result<()> {
5322        let vm = Vm::with_all()?;
5323        vm.import_code(
5324            "vm_inferred_list_set_idx",
5325            br#"
5326            pub fn swap_first_two() {
5327                let items = [];
5328                items.push(1i64);
5329                items.push(2i64);
5330                let j = 0i64;
5331                let a = items[j];
5332                let b = items[j + 1];
5333                items[j] = b;
5334                items[j + 1] = a;
5335                items[0] * 10i64 + items[1]
5336            }
5337
5338            pub fn replace_string() {
5339                let items = [];
5340                items.push("old");
5341                items[0] = "new";
5342                items[0]
5343            }
5344            "#
5345            .to_vec(),
5346        )?;
5347
5348        let compiled = vm.get_fn("vm_inferred_list_set_idx::swap_first_two", &[])?;
5349        assert_eq!(compiled.ret_ty(), &Type::I64);
5350        let swap_first_two: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5351        assert_eq!(swap_first_two(), 21);
5352
5353        let compiled = vm.get_fn("vm_inferred_list_set_idx::replace_string", &[])?;
5354        assert_eq!(compiled.ret_ty(), &Type::Str);
5355        let replace_string: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5356        let result = unsafe { &*replace_string() };
5357        assert_eq!(result.as_str(), "new");
5358        Ok(())
5359    }
5360
5361    #[test]
5362    fn root_get_returns_null_for_missing_key_which_compares_correctly() -> anyhow::Result<()> {
5363        let vm = Vm::with_all()?;
5364        vm.import_code(
5365            "vm_root_get_missing",
5366            br#"
5367            pub fn check_missing() {
5368                let existing = root::get("local/vm_root_get_missing_test");
5369                if existing.is_map() {
5370                    return false;
5371                }
5372                true
5373            }
5374            "#
5375            .to_vec(),
5376        )?;
5377
5378        let compiled = vm.get_fn("vm_root_get_missing::check_missing", &[])?;
5379        assert_eq!(compiled.ret_ty(), &Type::Bool);
5380        let check_missing: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5381        assert!(check_missing());
5382        Ok(())
5383    }
5384
5385    #[test]
5386    fn map_get_key_on_null_map_returns_null() -> anyhow::Result<()> {
5387        let vm = Vm::with_all()?;
5388        vm.import_code(
5389            "vm_get_key_null_map",
5390            br#"
5391            pub fn get_key_null(data) {
5392                data.get_key("missing")
5393            }
5394            "#
5395            .to_vec(),
5396        )?;
5397
5398        let compiled = vm.get_fn("vm_get_key_null_map::get_key_null", &[Type::Any])?;
5399        assert_eq!(compiled.ret_ty(), &Type::Any);
5400        let get_key_null: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5401
5402        let data_map = dynamic::map!("exists"=> 1i64);
5403        let missing = unsafe { &*get_key_null(&data_map) };
5404        assert!(missing.is_null());
5405
5406        let null = Dynamic::Null;
5407        let result = unsafe { &*get_key_null(&null) };
5408        assert!(result.is_null());
5409        Ok(())
5410    }
5411
5412    #[test]
5413    fn keys_on_empty_map_returns_empty_list() -> anyhow::Result<()> {
5414        let vm = Vm::with_all()?;
5415        vm.import_code(
5416            "vm_keys_empty_map",
5417            br#"
5418            pub fn empty_map_keys() {
5419                let data = {};
5420                data.keys().len()
5421            }
5422            "#
5423            .to_vec(),
5424        )?;
5425
5426        let compiled = vm.get_fn("vm_keys_empty_map::empty_map_keys", &[])?;
5427        assert_eq!(compiled.ret_ty(), &Type::I32);
5428        let empty_map_keys: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5429        assert_eq!(empty_map_keys(), 0);
5430        Ok(())
5431    }
5432
5433    #[test]
5434    fn cast_between_all_integer_widths() -> anyhow::Result<()> {
5435        let vm = Vm::with_all()?;
5436        vm.import_code(
5437            "vm_cast_integer_widths",
5438            br#"
5439            pub fn i64_to_i32(value: i64) {
5440                value as i32
5441            }
5442
5443            pub fn i32_to_i64(value: i32) {
5444                value as i64
5445            }
5446
5447            pub fn u32_to_i64(value: u32) {
5448                value as i64
5449            }
5450            "#
5451            .to_vec(),
5452        )?;
5453
5454        let compiled = vm.get_fn("vm_cast_integer_widths::i64_to_i32", &[Type::I64])?;
5455        assert_eq!(compiled.ret_ty(), &Type::I32);
5456        let i64_to_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5457        assert_eq!(i64_to_i32(42), 42);
5458
5459        let compiled = vm.get_fn("vm_cast_integer_widths::i32_to_i64", &[Type::I32])?;
5460        assert_eq!(compiled.ret_ty(), &Type::I64);
5461        let i32_to_i64: extern "C" fn(i32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5462        assert_eq!(i32_to_i64(-1), -1);
5463
5464        let compiled = vm.get_fn("vm_cast_integer_widths::u32_to_i64", &[Type::U32])?;
5465        assert_eq!(compiled.ret_ty(), &Type::I64);
5466        let u32_to_i64: extern "C" fn(u32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5467        assert_eq!(u32_to_i64(42), 42);
5468        Ok(())
5469    }
5470
5471    #[test]
5472    fn boolean_literals_in_complex_expression_trees() -> anyhow::Result<()> {
5473        let vm = Vm::with_all()?;
5474        vm.import_code(
5475            "vm_complex_boolean",
5476            br#"
5477            pub fn exclusive_or(a: bool, b: bool) {
5478                (a && !b) || (!a && b)
5479            }
5480
5481            pub fn implies(a: bool, b: bool) {
5482                !a || b
5483            }
5484            "#
5485            .to_vec(),
5486        )?;
5487
5488        let compiled = vm.get_fn("vm_complex_boolean::exclusive_or", &[Type::Bool, Type::Bool])?;
5489        assert_eq!(compiled.ret_ty(), &Type::Bool);
5490        let exclusive_or: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5491        assert!(exclusive_or(true, false));
5492        assert!(exclusive_or(false, true));
5493        assert!(!exclusive_or(true, true));
5494        assert!(!exclusive_or(false, false));
5495
5496        let compiled = vm.get_fn("vm_complex_boolean::implies", &[Type::Bool, Type::Bool])?;
5497        assert_eq!(compiled.ret_ty(), &Type::Bool);
5498        let implies: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5499        assert!(implies(false, true));
5500        assert!(implies(false, false));
5501        assert!(implies(true, true));
5502        assert!(!implies(true, false));
5503        Ok(())
5504    }
5505
5506    #[test]
5507    fn concrete_struct_method_returning_self_type() -> anyhow::Result<()> {
5508        let vm = Vm::with_all()?;
5509        vm.import_code(
5510            "vm_struct_method_self",
5511            br#"
5512            pub struct Vec3 {
5513                x: f64,
5514                y: f64,
5515                z: f64,
5516            }
5517
5518            impl Vec3 {
5519                pub fn add(self: Vec3, other: Vec3) {
5520                    Vec3{x: self.x + other.x, y: self.y + other.y, z: self.z + other.z}
5521                }
5522            }
5523
5524            pub fn run() {
5525                let v1 = Vec3{x: 1.0f64, y: 2.0f64, z: 3.0f64};
5526                let v2 = Vec3{x: 4.0f64, y: 5.0f64, z: 6.0f64};
5527                let sum = v1.add(v2);
5528                sum.x + sum.y + sum.z
5529            }
5530            "#
5531            .to_vec(),
5532        )?;
5533
5534        let compiled = vm.get_fn("vm_struct_method_self::run", &[])?;
5535        assert_eq!(compiled.ret_ty(), &Type::F64);
5536        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
5537        assert_eq!(run(), 21.0);
5538        Ok(())
5539    }
5540
5541    #[test]
5542    fn deep_nested_struct_access_with_multiple_field_levels() -> anyhow::Result<()> {
5543        let vm = Vm::with_all()?;
5544        vm.import_code(
5545            "vm_deep_nested_struct",
5546            br#"
5547            pub struct A {
5548                value: i64,
5549            }
5550
5551            pub struct B {
5552                a: A,
5553            }
5554
5555            pub struct C {
5556                b: B,
5557            }
5558
5559            pub fn direct_access() {
5560                let c = C{b: B{a: A{value: 99}}};
5561                c.b.a.value
5562            }
5563
5564            pub fn via_variable() {
5565                let c = C{b: B{a: A{value: 77}}};
5566                let b = c.b;
5567                let a = b.a;
5568                a.value
5569            }
5570            "#
5571            .to_vec(),
5572        )?;
5573
5574        let compiled = vm.get_fn("vm_deep_nested_struct::direct_access", &[])?;
5575        assert_eq!(compiled.ret_ty(), &Type::I64);
5576        let direct_access: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5577        assert_eq!(direct_access(), 99);
5578
5579        let compiled = vm.get_fn("vm_deep_nested_struct::via_variable", &[])?;
5580        assert_eq!(compiled.ret_ty(), &Type::I64);
5581        let via_variable: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5582        assert_eq!(via_variable(), 77);
5583        Ok(())
5584    }
5585
5586    #[test]
5587    fn array_index_with_dynamic_value_via_method() -> anyhow::Result<()> {
5588        let vm = Vm::with_all()?;
5589        vm.import_code(
5590            "vm_array_idx_dynamic",
5591            br#"
5592            pub fn get_by_idx(list, idx) {
5593                list.get_idx(idx)
5594            }
5595            "#
5596            .to_vec(),
5597        )?;
5598
5599        let compiled = vm.get_fn("vm_array_idx_dynamic::get_by_idx", &[Type::Any, Type::I64])?;
5600        assert_eq!(compiled.ret_ty(), &Type::Any);
5601        let get_by_idx: extern "C" fn(*const Dynamic, i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5602
5603        let list = Dynamic::list(vec!["a".into(), "b".into()]);
5604        let first = unsafe { &*get_by_idx(&list, 0) };
5605        assert_eq!(first.as_str(), "a");
5606
5607        let out = unsafe { &*get_by_idx(&list, 10) };
5608        assert!(out.is_null());
5609        Ok(())
5610    }
5611
5612    #[test]
5613    fn dynamic_field_access_with_optional_or_fallback() -> anyhow::Result<()> {
5614        let vm = Vm::with_all()?;
5615        vm.import_code(
5616            "vm_dynamic_or_fallback",
5617            br#"
5618            pub fn with_fallback(data) {
5619                if data.contains("name") { data.name } else { "unknown" }
5620            }
5621
5622            pub fn with_fallback_missing(data) {
5623                if data.contains("nickname") { data.nickname } else { "unnamed" }
5624            }
5625            "#
5626            .to_vec(),
5627        )?;
5628
5629        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback", &[Type::Any])?;
5630        assert_eq!(compiled.ret_ty(), &Type::Any);
5631        let with_fallback: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5632        let data = dynamic::map!("name"=> "Alice");
5633        let result = unsafe { &*with_fallback(&data) };
5634        assert_eq!(result.as_str(), "Alice");
5635
5636        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback_missing", &[Type::Any])?;
5637        let with_fallback_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5638        let result = unsafe { &*with_fallback_missing(&data) };
5639        assert_eq!(result.as_str(), "unnamed");
5640        Ok(())
5641    }
5642
5643    #[test]
5644    fn for_in_loop_iterates_over_list_and_map_directly() -> anyhow::Result<()> {
5645        let vm = Vm::with_all()?;
5646        vm.import_code(
5647            "vm_for_in_collection",
5648            br#"
5649            pub fn sum_list(items) {
5650                let total = 0i64;
5651                for item in items {
5652                    total = total + 1;
5653                }
5654                total
5655            }
5656
5657            pub fn count_map_keys(data) {
5658                let count = 0i64;
5659                for key in data.keys() {
5660                    count = count + 1;
5661                }
5662                count
5663            }
5664
5665            pub fn for_in_list_works(items) {
5666                let exists = false;
5667                for item in items {
5668                    exists = true;
5669                }
5670                exists
5671            }
5672
5673            pub fn for_in_map_values_works(data) {
5674                let exists = false;
5675                for value in data {
5676                    exists = true;
5677                }
5678                exists
5679            }
5680            "#
5681            .to_vec(),
5682        )?;
5683
5684        let compiled = vm.get_fn("vm_for_in_collection::sum_list", &[Type::Any])?;
5685        assert_eq!(compiled.ret_ty(), &Type::I64);
5686        let sum_list: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5687        let items = Dynamic::list(vec![Dynamic::from(1i64), Dynamic::from(2i64), Dynamic::from(3i64)]);
5688        assert_eq!(sum_list(&items), 3);
5689
5690        let data = dynamic::map!("x"=> 1i64, "y"=> 2i64);
5691        let compiled = vm.get_fn("vm_for_in_collection::count_map_keys", &[Type::Any])?;
5692        assert_eq!(compiled.ret_ty(), &Type::I64);
5693        let count_map_keys: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5694        assert_eq!(count_map_keys(&data), 2);
5695
5696        let compiled = vm.get_fn("vm_for_in_collection::for_in_list_works", &[Type::Any])?;
5697        assert_eq!(compiled.ret_ty(), &Type::Bool);
5698        let for_in_list_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5699        let empty = Dynamic::list(Vec::new());
5700        assert!(!for_in_list_works(&empty));
5701        assert!(for_in_list_works(&items));
5702
5703        let compiled = vm.get_fn("vm_for_in_collection::for_in_map_values_works", &[Type::Any])?;
5704        assert_eq!(compiled.ret_ty(), &Type::Bool);
5705        let for_in_map_values_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5706        let empty_map = dynamic::map!();
5707        assert!(!for_in_map_values_works(&empty_map));
5708        assert!(for_in_map_values_works(&data));
5709
5710        Ok(())
5711    }
5712
5713    #[test]
5714    fn concurrent_100_threads_no_memory_leak() -> anyhow::Result<()> {
5715        let vm = Vm::with_all()?;
5716        vm.import_code(
5717            "vm_stress",
5718            br#"
5719            pub fn heavy_alloc(idx: i64) {
5720                let items = [];
5721                let i = 0;
5722                while i < 50 {
5723                    items.push({
5724                        id: i + idx,
5725                        name: "item-" + i,
5726                        tags: ["tag-a", "tag-b", "tag-c"],
5727                        meta: {
5728                            created: 1234567890i64,
5729                            score: (i * 3.14f64) as i64,
5730                            extra: "prefix/" + i + "/" + idx
5731                        }
5732                    });
5733                    i = i + 1;
5734                }
5735                items
5736            }
5737
5738            pub fn string_concat_stress() {
5739                let i = 0;
5740                let result = "";
5741                while i < 200 {
5742                    result = result + "data-" + i + ",";
5743                    i = i + 1;
5744                }
5745                result
5746            }
5747            "#
5748            .to_vec(),
5749        )?;
5750
5751        let (heavy_ptr, _) = vm.get_fn_ptr("vm_stress::heavy_alloc", &[Type::I64])?;
5752        let (concat_ptr, _) = vm.get_fn_ptr("vm_stress::string_concat_stress", &[])?;
5753
5754        let threads: usize = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).max(100);
5755        let iters_per_thread = 200;
5756        let total_calls = threads * iters_per_thread * 2;
5757
5758        let before = current_rss_kb();
5759        eprintln!("threads={threads} iters_per_thread={iters_per_thread} total_calls={total_calls} rss_before={before}KB");
5760
5761        // Round 1: first concurrent execution (arena warm-up)
5762        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5763        let r1 = current_rss_kb();
5764        eprintln!("rss_after_round1={r1}KB");
5765
5766        // Round 2: should stabilize (no unbounded growth)
5767        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5768        let r2 = current_rss_kb();
5769        eprintln!("rss_after_round2={r2}KB");
5770
5771        // Round 3: final check
5772        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5773        let r3 = current_rss_kb();
5774        eprintln!("rss_after_round3={r3}KB");
5775
5776        // Round 4: confirm that any one-time allocator growth has settled.
5777        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5778        let r4 = current_rss_kb();
5779        eprintln!("rss_after_round4={r4}KB");
5780
5781        // Allocator/arena growth is allowed during warm-up, but it must settle.
5782        let d12 = r2.saturating_sub(r1);
5783        let d23 = r3.saturating_sub(r2);
5784        let d34 = r4.saturating_sub(r3);
5785        eprintln!("delta_r1→r2={d12}KB delta_r2→r3={d23}KB delta_r3→r4={d34}KB");
5786
5787        // The last interval must be small to prove the growth is not continuing.
5788        let max_growth_kb = 20 * 1024;
5789        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)");
5790
5791        Ok(())
5792    }
5793
5794    fn run_stress_round(threads: usize, iters: usize, heavy_ptr: usize, concat_ptr: usize) {
5795        std::thread::scope(|scope| {
5796            let mut handles = Vec::with_capacity(threads);
5797            for t in 0..threads {
5798                let heavy_ptr = heavy_ptr;
5799                let concat_ptr = concat_ptr;
5800                handles.push(scope.spawn(move || {
5801                    let heavy_fn: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(heavy_ptr as *const u8) };
5802                    let concat_fn: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(concat_ptr as *const u8) };
5803                    for i in 0..iters {
5804                        // heavy_alloc: drop returned value to free heap allocation
5805                        let r_ptr = heavy_fn((t * iters + i) as i64);
5806                        assert!(!r_ptr.is_null());
5807                        unsafe {
5808                            let r = &*r_ptr;
5809                            assert!(r.len() > 0, "heavy_alloc returned empty list");
5810                            drop(Box::from_raw(r_ptr as *mut Dynamic));
5811                        }
5812
5813                        // concat: same, drop returned value
5814                        let s_ptr = concat_fn();
5815                        assert!(!s_ptr.is_null());
5816                        unsafe {
5817                            let s = &*s_ptr;
5818                            assert!(s.len() > 0, "string_concat_stress returned empty");
5819                            drop(Box::from_raw(s_ptr as *mut Dynamic));
5820                        }
5821                    }
5822                }));
5823            }
5824            for h in handles {
5825                h.join().unwrap();
5826            }
5827        });
5828    }
5829
5830    fn current_rss_kb() -> u64 {
5831        // macOS: use ps
5832        let pid = std::process::id();
5833        if let Ok(output) = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "rss="]).output() {
5834            if let Ok(s) = String::from_utf8(output.stdout) {
5835                if let Some(kb) = s.trim().parse::<u64>().ok() {
5836                    return kb;
5837                }
5838            }
5839        }
5840        // Linux fallback: /proc/self/statm
5841        if let Ok(statm) = std::fs::read_to_string("/proc/self/statm") {
5842            let parts: Vec<&str> = statm.split_whitespace().collect();
5843            if let Some(rss_pages) = parts.get(1).and_then(|s| s.parse::<u64>().ok()) {
5844                return rss_pages * 4; // pages (4KB) → KB
5845            }
5846        }
5847        0
5848    }
5849}