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