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