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