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