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