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::{BuiltinFn, BuiltinFnRegistry, 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.sym_tab.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.builtin_fns.register(BuiltinFn::ScopeEnter, self.module.declare_function("__vm_scope_enter", cranelift_module::Linkage::Import, &void_sig)?);
125        self.builtin_fns.register(BuiltinFn::ScopeExitVoid, 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.builtin_fns.register(BuiltinFn::ScopeExitDynamic, 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.builtin_fns.register(BuiltinFn::ScopeExitBytes, 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.builtin_fns.register(BuiltinFn::StructAlloc, 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.builtin_fns.register(BuiltinFn::RepeatFill, 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.builtin_fns.register(BuiltinFn::Strcat, 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.builtin_fns.register(BuiltinFn::StrcatI64, 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.builtin_fns.register(BuiltinFn::StrcatAssign, 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.builtin_fns.register(BuiltinFn::CallbackNew, 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.builtin_fns.register(BuiltinFn::SpawnPtr, 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.builtin_fns.register(BuiltinFn::StructFromPtr, self.module.declare_function("__vm_struct_from_ptr", cranelift_module::Linkage::Import, &struct_from_ptr_sig)?);
156        self.builtin_fns.register(BuiltinFn::ArrayFromPtr, 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.builtin_fns.register(BuiltinFn::ArrayToPtr, self.module.declare_function("__vm_array_to_ptr", cranelift_module::Linkage::Import, &array_to_ptr_sig)?);
159
160        self.builtin_fns.register(BuiltinFn::ArithFault, 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.sym_tab.symbols.add_module(name.into());
166    }
167
168    pub fn pop_module(&mut self) {
169        self.compiler.sym_tab.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.sym_tab.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.sym_tab.symbols.get_id("Any").is_ok() && self.compiler.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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.sym_tab.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 root_keys_returns_map_key_list() -> anyhow::Result<()> {
1969        let vm = Vm::with_all()?;
1970        assert_eq!(vm.infer("root::keys", &[Type::Any])?, Type::Any);
1971        vm.import_code(
1972            "vm_root_keys",
1973            br#"
1974            pub fn run() {
1975                root::add_map("local/test/vm_root_keys");
1976                root::insert("local/test/vm_root_keys", "0", "zero");
1977                root::insert("local/test/vm_root_keys", "1", "one");
1978                root::keys("local/test/vm_root_keys").len()
1979            }
1980            "#
1981            .to_vec(),
1982        )?;
1983
1984        let compiled = vm.get_fn("vm_root_keys::run", &[])?;
1985        assert_eq!(compiled.ret_ty(), &Type::I32);
1986        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
1987        assert_eq!(run(), 2);
1988        Ok(())
1989    }
1990
1991    #[test]
1992    fn root_mount_fjall_accepts_mount_name() -> anyhow::Result<()> {
1993        let vm = Vm::with_all()?;
1994        assert_eq!(vm.infer("root::mount_fjall", &[Type::Any, Type::Any])?, Type::Void);
1995        vm.import_code(
1996            "vm_root_mount_fjall_named",
1997            br#"
1998            pub fn run(name, data_dir) {
1999                root::mount_fjall(name, data_dir);
2000            }
2001            "#
2002            .to_vec(),
2003        )?;
2004
2005        let compiled = vm.get_fn("vm_root_mount_fjall_named::run", &[Type::Any, Type::Any])?;
2006        assert!(compiled.ret_ty().is_void());
2007        Ok(())
2008    }
2009
2010    #[test]
2011    fn std_log_accepts_any_and_returns_void() -> anyhow::Result<()> {
2012        let vm = Vm::with_all()?;
2013        vm.import_code(
2014            "vm_std_log",
2015            br#"
2016            pub fn run(value) {
2017                log({ ok: true, value: value });
2018            }
2019            "#
2020            .to_vec(),
2021        )?;
2022
2023        let compiled = vm.get_fn("vm_std_log::run", &[Type::Any])?;
2024        assert!(compiled.ret_ty().is_void());
2025        let run: extern "C" fn(*const Dynamic) = unsafe { std::mem::transmute(compiled.ptr()) };
2026        let value = Dynamic::from(7i64);
2027        run(&value);
2028        Ok(())
2029    }
2030
2031    #[test]
2032    fn unary_not_any_loop_var_is_bool_condition() -> anyhow::Result<()> {
2033        let vm = Vm::with_all()?;
2034        vm.import_code(
2035            "vm_unary_not_any_loop_var",
2036            br#"
2037            pub fn count_missing(flags) {
2038                let missing = 0;
2039                for exists in flags {
2040                    if !exists {
2041                        missing = missing + 1;
2042                    }
2043                }
2044                missing
2045            }
2046            "#
2047            .to_vec(),
2048        )?;
2049
2050        let compiled = vm.get_fn("vm_unary_not_any_loop_var::count_missing", &[Type::Any])?;
2051        assert_eq!(compiled.ret_ty(), &Type::I64);
2052        Ok(())
2053    }
2054
2055    #[test]
2056    fn closure_literal_can_be_called_immediately() -> anyhow::Result<()> {
2057        let vm = Vm::with_all()?;
2058        vm.import_code(
2059            "vm_closure_immediate_call",
2060            br#"
2061            pub fn no_args() {
2062                let r = || { 1i32 }();
2063                r
2064            }
2065
2066            pub fn with_arg() {
2067                |value: i32| { value + 1i32 }(2i32)
2068            }
2069            "#
2070            .to_vec(),
2071        )?;
2072
2073        let compiled = vm.get_fn("vm_closure_immediate_call::no_args", &[])?;
2074        assert_eq!(compiled.ret_ty(), &Type::I32);
2075        let no_args: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2076        assert_eq!(no_args(), 1);
2077
2078        let compiled = vm.get_fn("vm_closure_immediate_call::with_arg", &[])?;
2079        assert_eq!(compiled.ret_ty(), &Type::I32);
2080        let with_arg: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
2081        assert_eq!(with_arg(), 3);
2082        Ok(())
2083    }
2084
2085    #[test]
2086    fn small_expression_calls_keep_direct_semantics() -> anyhow::Result<()> {
2087        let vm = Vm::with_all()?;
2088        vm.import_code(
2089            "vm_small_expression_inline",
2090            br#"
2091            pub fn add_i64(left: i64, right: i64) {
2092                left + right
2093            }
2094
2095            pub fn normal_caller() {
2096                add_i64(1i64, 2i64)
2097            }
2098
2099            pub fn closure_caller() {
2100                let add = |left: i64, right: i64| { left + right };
2101                add(add_i64(1i64, 2i64), 4i64)
2102            }
2103
2104            pub fn closure_assignment() {
2105                let acc = 0i64;
2106                let add = |left: i64, right: i64| { left + right };
2107                acc = add(acc, 4i64);
2108                acc
2109            }
2110            "#
2111            .to_vec(),
2112        )?;
2113
2114        let compiled = vm.get_fn("vm_small_expression_inline::normal_caller", &[])?;
2115        assert_eq!(compiled.ret_ty(), &Type::I64);
2116        let normal_caller: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2117        assert_eq!(normal_caller(), 3);
2118
2119        let compiled = vm.get_fn("vm_small_expression_inline::closure_caller", &[])?;
2120        assert_eq!(compiled.ret_ty(), &Type::Any);
2121        let closure_caller: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2122        let result = unsafe { &*closure_caller() };
2123        assert_eq!(result.as_int(), Some(7));
2124
2125        let compiled = vm.get_fn("vm_small_expression_inline::closure_assignment", &[])?;
2126        assert_eq!(compiled.ret_ty(), &Type::I64);
2127        let closure_assignment: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2128        assert_eq!(closure_assignment(), 4);
2129        Ok(())
2130    }
2131
2132    #[test]
2133    fn nested_closure_captures_outer_closure_arg() -> anyhow::Result<()> {
2134        let vm = Vm::with_all()?;
2135        vm.import_code(
2136            "vm_nested_closure_capture",
2137            br#"
2138            pub fn run() {
2139                let reference_label = "reference";
2140                |path: string| {
2141                    let upload_done = |uploaded: bool| {
2142                        if uploaded {
2143                            reference_label + ":" + path
2144                        } else {
2145                            "missing"
2146                        }
2147                    };
2148                    upload_done(true)
2149                }("reference.png")
2150            }
2151            "#
2152            .to_vec(),
2153        )?;
2154
2155        let compiled = vm.get_fn("vm_nested_closure_capture::run", &[])?;
2156        assert_eq!(compiled.ret_ty(), &Type::Any);
2157        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2158        let result = unsafe { &*run() };
2159        assert_eq!(result.as_str(), "reference:reference.png");
2160        Ok(())
2161    }
2162
2163    #[test]
2164    fn semicolon_tail_call_makes_function_void() -> anyhow::Result<()> {
2165        let vm = Vm::with_all()?;
2166        vm.import_code(
2167            "vm_semicolon_tail_void",
2168            br#"
2169            pub fn send_role_select(idx, account_id, selected_slot) {
2170                root::send("local/ui/send_dialog", {
2171                    idx: idx,
2172                    account_id: account_id,
2173                    selected_slot: selected_slot
2174                });
2175            }
2176            "#
2177            .to_vec(),
2178        )?;
2179
2180        let compiled = vm.get_fn("vm_semicolon_tail_void::send_role_select", &[Type::Any, Type::Any, Type::Any])?;
2181        assert_eq!(compiled.ret_ty(), &Type::Void);
2182        Ok(())
2183    }
2184
2185    #[test]
2186    fn bare_return_conflicts_with_non_void_return() -> anyhow::Result<()> {
2187        let vm = Vm::with_all()?;
2188        vm.import_code(
2189            "vm_bare_return_conflict",
2190            br#"
2191            pub fn run(flag) {
2192                if flag {
2193                    return;
2194                }
2195                1
2196            }
2197            "#
2198            .to_vec(),
2199        )?;
2200
2201        let err = match vm.get_fn("vm_bare_return_conflict::run", &[Type::Bool]) {
2202            Ok(_) => panic!("expected mismatched return types to fail"),
2203            Err(err) => err,
2204        };
2205        assert!(format!("{err:#}").contains("返回类型不一致"));
2206        Ok(())
2207    }
2208
2209    #[test]
2210    fn root_get_accepts_string_concat_with_dynamic_field() -> anyhow::Result<()> {
2211        let vm = Vm::with_all()?;
2212        vm.import_code(
2213            "vm_root_get_dynamic_concat",
2214            br#"
2215            pub fn get_action(req) {
2216                root::get("local/game/panel_actions/" + req.idx)
2217            }
2218            "#
2219            .to_vec(),
2220        )?;
2221
2222        root::add("local/game/panel_actions/7", dynamic::map!("id"=> "action-7").into())?;
2223        let compiled = vm.get_fn("vm_root_get_dynamic_concat::get_action", &[Type::Any])?;
2224        assert_eq!(compiled.ret_ty(), &Type::Any);
2225        let get_action: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2226        let req = dynamic::map!("idx"=> 7i64);
2227        let result = unsafe { &*get_action(&req) };
2228
2229        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("action-7".to_string()));
2230        Ok(())
2231    }
2232
2233    #[test]
2234    fn root_add_fn_registers_handler_with_dynamic_field_path_concat() -> anyhow::Result<()> {
2235        let vm = Vm::with_all()?;
2236        vm.import_code(
2237            "vm_registered_panel_action",
2238            br#"
2239            pub fn panel_action(req) {
2240                root::get("local/game/panel_actions/" + req.idx)
2241            }
2242
2243            pub fn register() {
2244                root::add_fn("local/ui/panel_action", "vm_registered_panel_action::panel_action")
2245            }
2246            "#
2247            .to_vec(),
2248        )?;
2249
2250        let compiled = vm.get_fn("vm_registered_panel_action::register", &[])?;
2251        assert_eq!(compiled.ret_ty(), &Type::Bool);
2252        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2253        assert!(register());
2254        Ok(())
2255    }
2256
2257    #[test]
2258    fn std_spawn_runs_named_function_with_tuple_args() -> anyhow::Result<()> {
2259        let zero_path = "local/vm_std_spawn/zero";
2260        let sum_path = "local/vm_std_spawn/sum";
2261        let closure_path = "local/vm_std_spawn/closure";
2262        let closure_vars_path = "local/vm_std_spawn/closure_vars";
2263        let _ = root::remove(zero_path);
2264        let _ = root::remove(sum_path);
2265        let _ = root::remove(closure_path);
2266        let _ = root::remove(closure_vars_path);
2267        let vm = Vm::with_all()?;
2268        vm.import_code(
2269            "vm_std_spawn",
2270            br#"
2271            pub fn zero() {
2272                root::add("local/vm_std_spawn/zero", 1);
2273            }
2274
2275            pub fn job(left, right) {
2276                root::add("local/vm_std_spawn/sum", left + right);
2277            }
2278
2279            pub fn start_zero() {
2280                spawn("vm_std_spawn::zero", ())
2281            }
2282
2283            pub fn start_sum() {
2284                spawn("vm_std_spawn::job", (10, 20))
2285            }
2286
2287            pub fn start_closure() {
2288                spawn(|x, y| {
2289                    root::add("local/vm_std_spawn/closure", x + y);
2290                }, (3, 4))
2291            }
2292
2293            pub fn start_closure_vars() {
2294                let x = 5;
2295                let y = 6;
2296                spawn(|left, right| {
2297                    root::add("local/vm_std_spawn/closure_vars", left + right);
2298                }, (x, y))
2299            }
2300            "#
2301            .to_vec(),
2302        )?;
2303
2304        let compiled = vm.get_fn("vm_std_spawn::start_zero", &[])?;
2305        assert_eq!(compiled.ret_ty(), &Type::Bool);
2306        let start_zero: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2307        assert!(start_zero());
2308
2309        let compiled = vm.get_fn("vm_std_spawn::start_sum", &[])?;
2310        assert_eq!(compiled.ret_ty(), &Type::Bool);
2311        let start_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2312        assert!(start_sum());
2313
2314        let compiled = vm.get_fn("vm_std_spawn::start_closure", &[])?;
2315        assert_eq!(compiled.ret_ty(), &Type::Bool);
2316        let start_closure: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2317        assert!(start_closure());
2318
2319        let compiled = vm.get_fn("vm_std_spawn::start_closure_vars", &[])?;
2320        assert_eq!(compiled.ret_ty(), &Type::Bool);
2321        let start_closure_vars: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2322        assert!(start_closure_vars());
2323
2324        for _ in 0..50 {
2325            let zero_done = root::get(zero_path).ok().and_then(|value| value.as_int()) == Some(1);
2326            let sum_done = root::get(sum_path).ok().and_then(|value| value.as_int()) == Some(30);
2327            let closure_done = root::get(closure_path).ok().and_then(|value| value.as_int()) == Some(7);
2328            let closure_vars_done = root::get(closure_vars_path).ok().and_then(|value| value.as_int()) == Some(11);
2329            if zero_done && sum_done && closure_done && closure_vars_done {
2330                return Ok(());
2331            }
2332            std::thread::sleep(std::time::Duration::from_millis(10));
2333        }
2334
2335        anyhow::bail!("spawned jobs did not write expected results");
2336    }
2337
2338    #[test]
2339    fn native_can_save_and_later_call_closure_callback() -> anyhow::Result<()> {
2340        static SAVED_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2341
2342        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2343            if callback.is_null() {
2344                return false;
2345            }
2346            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2347                return false;
2348            };
2349            *SAVED_CALLBACK.lock() = Some(callback);
2350            true
2351        }
2352
2353        let path = "local/vm_callback/result";
2354        let _ = root::remove(path);
2355        *SAVED_CALLBACK.lock() = None;
2356
2357        let vm = Vm::with_all()?;
2358        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2359        vm.import_code(
2360            "vm_callback",
2361            br#"
2362            pub fn register() {
2363                let n = 41;
2364                callback_test::save(|| {
2365                    root::add("local/vm_callback/result", n + 1);
2366                    true
2367                })
2368            }
2369            "#
2370            .to_vec(),
2371        )?;
2372
2373        let compiled = vm.get_fn("vm_callback::register", &[])?;
2374        assert_eq!(compiled.ret_ty(), &Type::Bool);
2375        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2376        assert!(register());
2377        assert!(root::get(path).is_err());
2378
2379        let callback = SAVED_CALLBACK.lock().clone().expect("callback should be saved");
2380        let result = callback.call0()?;
2381        assert_eq!(result.as_bool(), Some(true));
2382        assert_eq!(root::get(path)?.as_int(), Some(42));
2383        Ok(())
2384    }
2385
2386    #[test]
2387    fn closure_captures_share_state_between_callbacks() -> anyhow::Result<()> {
2388        static SAVED_CALLBACKS: parking_lot::Mutex<Vec<ZustCallback>> = parking_lot::Mutex::new(Vec::new());
2389
2390        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2391            if callback.is_null() {
2392                return false;
2393            }
2394            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2395                return false;
2396            };
2397            SAVED_CALLBACKS.lock().push(callback);
2398            true
2399        }
2400
2401        SAVED_CALLBACKS.lock().clear();
2402
2403        let vm = Vm::with_all()?;
2404        vm.add_native_module_ptr("capture_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2405        vm.import_code(
2406            "vm_shared_capture",
2407            br#"
2408            pub fn register() {
2409                let state = {};
2410                state.drag_kind = 0;
2411                capture_test::save(|| {
2412                    state.drag_kind = 2;
2413                    true
2414                });
2415                capture_test::save(|| {
2416                    state.drag_kind
2417                })
2418            }
2419            "#
2420            .to_vec(),
2421        )?;
2422
2423        let register = vm.get_fn("vm_shared_capture::register", &[])?;
2424        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2425        assert!(register());
2426
2427        let (writer, reader) = {
2428            let saved = SAVED_CALLBACKS.lock();
2429            assert_eq!(saved.len(), 2);
2430            (saved[0].clone(), saved[1].clone())
2431        };
2432        assert_eq!(reader.call0()?.as_int(), Some(0));
2433        assert_eq!(writer.call0()?.as_bool(), Some(true));
2434        assert_eq!(reader.call0()?.as_int(), Some(2));
2435        Ok(())
2436    }
2437
2438    #[test]
2439    fn native_can_save_and_later_call_named_function_callback() -> anyhow::Result<()> {
2440        static SAVED_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2441
2442        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
2443            if callback.is_null() {
2444                return false;
2445            }
2446            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2447                return false;
2448            };
2449            *SAVED_CALLBACK.lock() = Some(callback);
2450            true
2451        }
2452
2453        let path = "local/vm_named_callback/result";
2454        let _ = root::remove(path);
2455        *SAVED_CALLBACK.lock() = None;
2456
2457        let vm = Vm::with_all()?;
2458        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
2459        vm.import_code(
2460            "vm_named_callback",
2461            br#"
2462            pub fn on_result() {
2463                root::add("local/vm_named_callback/result", "done");
2464                true
2465            }
2466
2467            pub fn register() {
2468                callback_test::save(on_result)
2469            }
2470            "#
2471            .to_vec(),
2472        )?;
2473
2474        let register = vm.get_fn("vm_named_callback::register", &[])?;
2475        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2476        assert!(register());
2477        assert!(root::get(path).is_err());
2478
2479        let callback = SAVED_CALLBACK.lock().clone().expect("callback should be saved");
2480        assert_eq!(callback.call1(dynamic::map!("text"=> "done"))?.as_bool(), Some(true));
2481        assert_eq!(root::get(path)?.as_str(), "done");
2482        Ok(())
2483    }
2484
2485    #[test]
2486    fn native_callback_can_receive_later_dynamic_args() -> anyhow::Result<()> {
2487        static SAVED_PATH_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2488        static SAVED_SUM_CALLBACK: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2489
2490        extern "C" fn save_path_callback(callback: *const Dynamic) -> bool {
2491            if callback.is_null() {
2492                return false;
2493            }
2494            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2495                return false;
2496            };
2497            *SAVED_PATH_CALLBACK.lock() = Some(callback);
2498            true
2499        }
2500
2501        extern "C" fn save_sum_callback(callback: *const Dynamic) -> bool {
2502            if callback.is_null() {
2503                return false;
2504            }
2505            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2506                return false;
2507            };
2508            *SAVED_SUM_CALLBACK.lock() = Some(callback);
2509            true
2510        }
2511
2512        let path_result = "local/vm_callback/path";
2513        let sum_result = "local/vm_callback/sum8";
2514        let _ = root::remove(path_result);
2515        let _ = root::remove(sum_result);
2516        *SAVED_PATH_CALLBACK.lock() = None;
2517        *SAVED_SUM_CALLBACK.lock() = None;
2518
2519        let vm = Vm::with_all()?;
2520        vm.add_native_module_ptr("callback_test", "save_path", &[Type::Any], Type::Bool, save_path_callback as *const u8)?;
2521        vm.add_native_module_ptr("callback_test", "save_sum", &[Type::Any], Type::Bool, save_sum_callback as *const u8)?;
2522        vm.import_code(
2523            "vm_callback_args",
2524            br#"
2525            pub fn register_path() {
2526                let key = "local/vm_callback/path";
2527                callback_test::save_path(|path| {
2528                    root::add(key, path);
2529                    true
2530                })
2531            }
2532
2533            pub fn register_sum() {
2534                callback_test::save_sum(|a, b, c, d, e, f, g, h| {
2535                    root::add("local/vm_callback/sum8", a + b + c + d + e + f + g + h);
2536                    true
2537                })
2538            }
2539            "#
2540            .to_vec(),
2541        )?;
2542
2543        let register_path = vm.get_fn("vm_callback_args::register_path", &[])?;
2544        let register_path: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_path.ptr()) };
2545        assert!(register_path());
2546
2547        let register_sum = vm.get_fn("vm_callback_args::register_sum", &[])?;
2548        let register_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_sum.ptr()) };
2549        assert!(register_sum());
2550
2551        let path_callback = SAVED_PATH_CALLBACK.lock().clone().expect("path callback should be saved");
2552        assert_eq!(path_callback.call1(Dynamic::from("picked.txt"))?.as_bool(), Some(true));
2553        assert_eq!(root::get(path_result)?.as_str(), "picked.txt");
2554
2555        let sum_callback = SAVED_SUM_CALLBACK.lock().clone().expect("sum callback should be saved");
2556        let sum_args = (1i64..=8).map(Dynamic::from).collect();
2557        assert_eq!(sum_callback.call(sum_args)?.as_bool(), Some(true));
2558        assert_eq!(root::get(sum_result)?.as_int(), Some(36));
2559        Ok(())
2560    }
2561
2562    #[test]
2563    fn callback_with_16_explicit_args_and_captures() -> anyhow::Result<()> {
2564        static SAVED_SUM16: parking_lot::Mutex<Option<ZustCallback>> = parking_lot::Mutex::new(None);
2565
2566        extern "C" fn save_sum16(callback: *const Dynamic) -> bool {
2567            if callback.is_null() {
2568                return false;
2569            }
2570            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
2571                return false;
2572            };
2573            *SAVED_SUM16.lock() = Some(callback);
2574            true
2575        }
2576
2577        let sum16_path = "local/vm_callback/sum16";
2578        let _ = root::remove(sum16_path);
2579        *SAVED_SUM16.lock() = None;
2580
2581        let vm = Vm::with_all()?;
2582        vm.add_native_module_ptr("callback_test", "save_sum16", &[Type::Any], Type::Bool, save_sum16 as *const u8)?;
2583        vm.import_code(
2584            "vm_callback_16_args",
2585            br#"
2586            pub fn register_sum16() {
2587                let prefix = "sum=";
2588                callback_test::save_sum16(|a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p| {
2589                    let total = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p;
2590                    root::add("local/vm_callback/sum16", prefix + total);
2591                    true
2592                })
2593            }
2594            "#
2595            .to_vec(),
2596        )?;
2597
2598        let register = vm.get_fn("vm_callback_16_args::register_sum16", &[])?;
2599        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
2600        assert!(register());
2601
2602        let callback = SAVED_SUM16.lock().clone().expect("sum16 callback saved");
2603        let args: Vec<Dynamic> = (1i64..=16).map(Dynamic::from).collect();
2604        assert_eq!(callback.call(args)?.as_bool(), Some(true));
2605        assert_eq!(root::get(sum16_path)?.as_str(), "sum=136");
2606        Ok(())
2607    }
2608
2609    #[test]
2610    fn spawn_closure_with_16_args() -> anyhow::Result<()> {
2611        let spawn16_path = "local/vm_spawn/spawn16";
2612        let _ = root::remove(spawn16_path);
2613
2614        let vm = Vm::with_all()?;
2615        vm.import_code(
2616            "vm_spawn_16_args",
2617            br#"
2618            pub fn start_spawn16() {
2619                spawn(|a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p| {
2620                    root::add("local/vm_spawn/spawn16", a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p);
2621                }, (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))
2622            }
2623            "#
2624            .to_vec(),
2625        )?;
2626
2627        let compiled = vm.get_fn("vm_spawn_16_args::start_spawn16", &[])?;
2628        assert_eq!(compiled.ret_ty(), &Type::Bool);
2629        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2630        assert!(start());
2631
2632        for _ in 0..50 {
2633            if root::get(spawn16_path).ok().and_then(|v| v.as_int()) == Some(136) {
2634                return Ok(());
2635            }
2636            std::thread::sleep(std::time::Duration::from_millis(10));
2637        }
2638        anyhow::bail!("spawned job did not write expected result");
2639    }
2640
2641    #[test]
2642    fn spawn_native_closure_avoids_any_boxing() -> anyhow::Result<()> {
2643        let nat_path = "local/vm_spawn_native/result";
2644        let _ = root::remove(nat_path);
2645        let vm = Vm::with_all()?;
2646        vm.import_code(
2647            "vm_spawn_native",
2648            br#"
2649            pub fn start() {
2650                spawn(|x: i64, y: i64| {
2651                    root::add("local/vm_spawn_native/result", x + y);
2652                }, (10i64, 20i64))
2653            }
2654            "#
2655            .to_vec(),
2656        )?;
2657        let compiled = vm.get_fn("vm_spawn_native::start", &[])?;
2658        assert_eq!(compiled.ret_ty(), &Type::Bool);
2659        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2660        assert!(start());
2661        for _ in 0..50 {
2662            if root::get(nat_path).ok().and_then(|v| v.as_int()) == Some(30) {
2663                return Ok(());
2664            }
2665            std::thread::sleep(std::time::Duration::from_millis(10));
2666        }
2667        anyhow::bail!("spawned native closure did not write expected result");
2668    }
2669
2670    #[test]
2671    fn multi_level_nested_closure_captures() -> anyhow::Result<()> {
2672        let vm = Vm::with_all()?;
2673        vm.import_code(
2674            "vm_multi_level_captures",
2675            br#"
2676            pub fn run() {
2677                let level1 = "L1";
2678                let level2 = "L2";
2679                |path: string| {
2680                    let level3 = "L3";
2681                    let inner = |suffix: string| {
2682                        let level4 = "L4";
2683                        |flag: bool| {
2684                            if flag {
2685                                level1 + "." + level2 + "." + level3 + "." + level4 + "." + path + suffix
2686                            } else {
2687                                "off"
2688                            }
2689                        }(true)
2690                    };
2691                    inner(".ext")
2692                }("file.txt")
2693            }
2694            "#
2695            .to_vec(),
2696        )?;
2697
2698        let compiled = vm.get_fn("vm_multi_level_captures::run", &[])?;
2699        assert_eq!(compiled.ret_ty(), &Type::Any);
2700        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2701        let result = unsafe { &*run() };
2702        assert_eq!(result.as_str(), "L1.L2.L3.L4.file.txt.ext");
2703        Ok(())
2704    }
2705
2706    #[test]
2707    fn root_add_fn_accepts_string_concat_in_registered_handler() -> anyhow::Result<()> {
2708        let vm = Vm::with_all()?;
2709        vm.import_code(
2710            "vm_registered_string_concat",
2711            br#"
2712            pub fn send_panel(idx: i64) {
2713                let idx_key = "" + idx;
2714                idx_key
2715            }
2716            "#
2717            .to_vec(),
2718        )?;
2719
2720        assert!(vm.get_fn_ptr("vm_registered_string_concat::send_panel", &[Type::Any]).is_ok());
2721        Ok(())
2722    }
2723
2724    #[test]
2725    fn dynamic_method_error_reports_source_location() -> anyhow::Result<()> {
2726        let vm = Vm::with_all()?;
2727        vm.import_code(
2728            "vm_bad_dynamic_method",
2729            br#"
2730            pub fn main(value) {
2731                let out = "";
2732                out = out + value.fetch("name");
2733            }
2734            "#
2735            .to_vec(),
2736        )?;
2737
2738        let err = vm.get_fn_ptr("vm_bad_dynamic_method::main", &[Type::Any]).expect_err("bad dynamic method should fail to compile");
2739        let msg = format!("{err:#}");
2740        assert!(msg.contains("vm_bad_dynamic_method:4:"), "{msg}");
2741        assert!(msg.contains("`Any.fetch` 不是成员函数"), "{msg}");
2742        assert!(msg.contains(r#"out = out + value.fetch("name");"#), "{msg}");
2743        Ok(())
2744    }
2745
2746    #[test]
2747    fn root_send_idx_returns_handler_value() -> anyhow::Result<()> {
2748        fn echo_handler(msg: Dynamic) -> Dynamic {
2749            dynamic::map!("type"=> "echo", "id"=> msg.get_dynamic("id").unwrap_or(Dynamic::Null))
2750        }
2751
2752        let vm = Vm::with_all()?;
2753        vm.import_code(
2754            "vm_root_send_idx_return",
2755            br#"
2756            pub fn call(req) {
2757                root::send_idx("local/send_idx_return_handlers", 0, req)
2758            }
2759            "#
2760            .to_vec(),
2761        )?;
2762
2763        root::add_list("local/send_idx_return_handlers")?;
2764        let (mount, name) = root::get_mount("local/send_idx_return_handlers")?;
2765        mount.push(name, root::Object::Native(echo_handler))?;
2766
2767        assert_eq!(vm.infer("root::send_idx", &[Type::Any, Type::I64, Type::Any])?, Type::Any);
2768        let compiled = vm.get_fn("vm_root_send_idx_return::call", &[Type::Any])?;
2769        assert_eq!(compiled.ret_ty(), &Type::Any);
2770        let call: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2771        let req = dynamic::map!("id"=> 42i64);
2772        let result = unsafe { &*call(&req) };
2773
2774        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("echo".to_string()));
2775        assert_eq!(result.get_dynamic("id").and_then(|value| value.as_int()), Some(42));
2776        Ok(())
2777    }
2778
2779    #[test]
2780    fn compiles_public_hotspots_with_string_paths_and_keys() -> anyhow::Result<()> {
2781        let vm = Vm::with_all()?;
2782        vm.import_code(
2783            "vm_public_hotspots",
2784            br#"
2785            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
2786                {
2787                    path: action_map_path,
2788                    panel_id: panel_id,
2789                    action_id: action_id,
2790                    id: hotspot.id
2791                }
2792            }
2793
2794            pub fn public_hotspots(idx, panel_id, hotspots) {
2795                let idx_key = "" + idx;
2796                let action_map_path = "local/game/panel_actions/" + idx_key;
2797
2798                let existing_action_map = root::get(action_map_path);
2799                if !existing_action_map.is_map() {
2800                    root::add_map(action_map_path);
2801                }
2802
2803                if hotspots.is_map() {
2804                    let public_items = {};
2805                    for action_id in hotspots.keys() {
2806                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
2807                    }
2808                    return public_items;
2809                }
2810
2811                let public_items = [];
2812                let i = 0;
2813                while i < hotspots.len() {
2814                    let hotspot = hotspots.get_idx(i);
2815                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
2816                    public_items.push(item);
2817                    i = i + 1;
2818                }
2819
2820                public_items
2821            }
2822            "#
2823            .to_vec(),
2824        )?;
2825
2826        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::I64, Type::Any, Type::Any]).is_ok());
2827        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::Any, Type::Any, Type::Any]).is_ok());
2828        Ok(())
2829    }
2830
2831    #[test]
2832    fn send_panel_calls_public_hotspots_with_dynamic_request() -> anyhow::Result<()> {
2833        let vm = Vm::with_all()?;
2834        vm.import_code(
2835            "vm_send_panel_public_hotspots",
2836            br#"
2837            pub fn ok(value) {
2838                value
2839            }
2840
2841            pub fn panel_from_node(req) {
2842                {
2843                    panel_id: req.panel_id,
2844                    hotspots: req.hotspots
2845                }
2846            }
2847
2848            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
2849                {
2850                    path: action_map_path,
2851                    panel_id: panel_id,
2852                    action_id: action_id,
2853                    id: hotspot.id
2854                }
2855            }
2856
2857            pub fn public_hotspots(idx, panel_id, hotspots) {
2858                let idx_key = "" + idx;
2859                let action_map_path = "local/game/panel_actions/" + idx_key;
2860
2861                let existing_action_map = root::get(action_map_path);
2862                if !existing_action_map.is_map() {
2863                    root::add_map(action_map_path);
2864                }
2865
2866                if hotspots.is_map() {
2867                    let public_items = {};
2868                    for action_id in hotspots.keys() {
2869                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
2870                    }
2871                    return public_items;
2872                }
2873
2874                let public_items = [];
2875                let i = 0;
2876                while i < hotspots.len() {
2877                    let hotspot = hotspots.get_idx(i);
2878                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
2879                    public_items.push(item);
2880                    i = i + 1;
2881                }
2882
2883                public_items
2884            }
2885
2886            pub fn send_panel(req) {
2887                let panel = req.panel;
2888                if !panel.is_map() {
2889                    panel = panel_from_node(req);
2890                }
2891                if !panel.is_map() {
2892                    return ok({
2893                        id: 4,
2894                        type: "panel_rejected",
2895                        reason: "invalid panel"
2896                    });
2897                }
2898                panel.id = 4;
2899                panel.idx = req.idx;
2900                if !panel.contains("type") {
2901                    panel.type = "panel";
2902                }
2903                if panel.contains("hotspots") {
2904                    panel.hotspots = public_hotspots(req.idx, panel.panel_id, panel.hotspots);
2905                }
2906                root::send_idx("local/ws", req.idx, panel);
2907                ok({
2908                    id: 4,
2909                    type: "panel",
2910                    panel_id: panel.panel_id
2911                })
2912            }
2913            "#
2914            .to_vec(),
2915        )?;
2916
2917        let compiled = vm.get_fn("vm_send_panel_public_hotspots::send_panel", &[Type::Any])?;
2918        assert_eq!(compiled.ret_ty(), &Type::Any);
2919        let send_panel: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2920        let req = dynamic::map!(
2921            "idx"=> 7i64,
2922            "panel"=> dynamic::map!(
2923                "panel_id"=> "main",
2924                "hotspots"=> dynamic::map!(
2925                    "open"=> dynamic::map!("id"=> "open")
2926                )
2927            )
2928        );
2929        let result = unsafe { &*send_panel(&req) };
2930
2931        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("panel".to_string()));
2932        assert_eq!(result.get_dynamic("panel_id").map(|value| value.as_str().to_string()), Some("main".to_string()));
2933        Ok(())
2934    }
2935
2936    #[test]
2937    fn map_assignment_accepts_string_concat_key() -> anyhow::Result<()> {
2938        let vm = Vm::with_all()?;
2939        vm.import_code(
2940            "vm_string_concat_map_key",
2941            br##"
2942            pub fn write_action(action_map, panel_id, action_id, action) {
2943                action_map[panel_id + "#" + action_id] = action;
2944                action_map[panel_id + "#" + action_id]
2945            }
2946            "##
2947            .to_vec(),
2948        )?;
2949
2950        let compiled = vm.get_fn("vm_string_concat_map_key::write_action", &[Type::Any, Type::Any, Type::Any, Type::Any])?;
2951        let write_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2952        let action_map = dynamic::map!();
2953        let panel_id: Dynamic = "panel".into();
2954        let action_id: Dynamic = "open".into();
2955        let action = dynamic::map!("id"=> "open");
2956
2957        let result = unsafe { &*write_action(&action_map, &panel_id, &action_id, &action) };
2958
2959        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2960        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()));
2961        Ok(())
2962    }
2963
2964    #[test]
2965    fn map_get_key_accepts_string_concat_key_variable() -> anyhow::Result<()> {
2966        let vm = Vm::with_all()?;
2967        vm.import_code(
2968            "vm_get_key_string_concat_key",
2969            br##"
2970            pub fn read_action(action_map, panel_id, action_id) {
2971                let action_key = panel_id + "#" + action_id;
2972                action_map.get_key(action_key)
2973            }
2974            "##
2975            .to_vec(),
2976        )?;
2977
2978        let compiled = vm.get_fn("vm_get_key_string_concat_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
2979        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2980        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2981        let panel_id: Dynamic = "panel".into();
2982        let action_id: Dynamic = "open".into();
2983
2984        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
2985
2986        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2987        Ok(())
2988    }
2989
2990    #[test]
2991    fn const_map_bracket_accepts_dynamic_string_key() -> anyhow::Result<()> {
2992        let vm = Vm::with_all()?;
2993        vm.import_code(
2994            "vm_const_map_dynamic_key",
2995            r#"
2996            const DIRECTION_LABELS = {left: "左", right: "右", up: "上", down: "下"};
2997
2998            pub fn label(direction) {
2999                DIRECTION_LABELS[direction]
3000            }
3001            "#
3002            .as_bytes()
3003            .to_vec(),
3004        )?;
3005
3006        let compiled = vm.get_fn("vm_const_map_dynamic_key::label", &[Type::Any])?;
3007        assert_eq!(compiled.ret_ty(), &Type::Any);
3008        let label: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3009        let direction: Dynamic = "left".into();
3010        let result = unsafe { &*label(&direction) };
3011        assert_eq!(result.as_str(), "左");
3012        Ok(())
3013    }
3014
3015    #[test]
3016    fn map_get_alias_matches_get_key() -> anyhow::Result<()> {
3017        let vm = Vm::with_all()?;
3018        vm.import_code(
3019            "vm_map_get_alias",
3020            br#"
3021            pub fn read_name(data) {
3022                data.get("name")
3023            }
3024
3025            pub fn read_missing(data) {
3026                data.get("missing")
3027            }
3028            "#
3029            .to_vec(),
3030        )?;
3031
3032        let data = dynamic::map!("name"=> "zust");
3033
3034        let compiled = vm.get_fn("vm_map_get_alias::read_name", &[Type::Any])?;
3035        assert_eq!(compiled.ret_ty(), &Type::Any);
3036        let read_name: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3037        let result = unsafe { &*read_name(&data) };
3038        assert_eq!(result.as_str(), "zust");
3039
3040        let compiled = vm.get_fn("vm_map_get_alias::read_missing", &[Type::Any])?;
3041        assert_eq!(compiled.ret_ty(), &Type::Any);
3042        let read_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3043        let result = unsafe { &*read_missing(&data) };
3044        assert!(result.is_null());
3045        Ok(())
3046    }
3047
3048    #[test]
3049    fn map_get_key_accepts_helper_string_key() -> anyhow::Result<()> {
3050        let vm = Vm::with_all()?;
3051        vm.import_code(
3052            "vm_get_key_helper_string_key",
3053            br##"
3054            pub fn make_action_key(panel_id, action_id) {
3055                panel_id + "#" + action_id
3056            }
3057
3058            pub fn read_action(action_map, panel_id, action_id) {
3059                let action_key = make_action_key(panel_id, action_id);
3060                let action = action_map.get_key(action_key);
3061                action
3062            }
3063            "##
3064            .to_vec(),
3065        )?;
3066
3067        let compiled = vm.get_fn("vm_get_key_helper_string_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
3068        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3069        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3070        let panel_id: Dynamic = "panel".into();
3071        let action_id: Dynamic = "open".into();
3072
3073        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
3074
3075        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
3076        Ok(())
3077    }
3078
3079    #[test]
3080    fn map_del_key_removes_string_key_and_returns_removed_value() -> anyhow::Result<()> {
3081        let vm = Vm::with_all()?;
3082        vm.import_code(
3083            "vm_del_key_string_key",
3084            br##"
3085            pub fn remove_action(action_map, panel_id, action_id) {
3086                let action_key = panel_id + "#" + action_id;
3087                let removed = action_map.del_key(action_key);
3088                [removed, action_map.get_key(action_key)]
3089            }
3090            "##
3091            .to_vec(),
3092        )?;
3093
3094        let compiled = vm.get_fn("vm_del_key_string_key::remove_action", &[Type::Any, Type::Any, Type::Any])?;
3095        let remove_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3096        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
3097        let panel_id: Dynamic = "panel".into();
3098        let action_id: Dynamic = "open".into();
3099
3100        let result = unsafe { &*remove_action(&action_map, &panel_id, &action_id) };
3101
3102        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("id")).map(|value| value.as_str().to_string()), Some("open".to_string()));
3103        assert!(result.get_idx(1).is_some_and(|value| value.is_null()));
3104        assert!(action_map.get_dynamic("panel#open").is_none());
3105        Ok(())
3106    }
3107
3108    #[test]
3109    fn dynamic_field_value_participates_in_or_expression() -> anyhow::Result<()> {
3110        let vm = Vm::with_all()?;
3111        vm.import_code(
3112            "vm_dynamic_field_or",
3113            r#"
3114            pub fn direct_next() {
3115                let choice = {
3116                    label: "颜色",
3117                    next: "color"
3118                };
3119                choice.next
3120            }
3121
3122            pub fn bracket_next() {
3123                let choice = {
3124                    label: "颜色",
3125                    next: "color"
3126                };
3127                choice["next"]
3128            }
3129            "#
3130            .as_bytes()
3131            .to_vec(),
3132        )?;
3133
3134        let compiled = vm.get_fn("vm_dynamic_field_or::direct_next", &[])?;
3135        assert_eq!(compiled.ret_ty(), &Type::Any);
3136        let direct_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3137        assert_eq!(unsafe { &*direct_next() }.as_str(), "color");
3138
3139        let compiled = vm.get_fn("vm_dynamic_field_or::bracket_next", &[])?;
3140        assert_eq!(compiled.ret_ty(), &Type::Any);
3141        let bracket_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3142        assert_eq!(unsafe { &*bracket_next() }.as_str(), "color");
3143        Ok(())
3144    }
3145
3146    #[test]
3147    fn empty_object_literal_in_if_branch_stays_dynamic() -> anyhow::Result<()> {
3148        let vm = Vm::with_all()?;
3149        vm.import_code(
3150            "vm_if_empty_object_branch",
3151            r#"
3152            pub fn first_note(steps) {
3153                let first = if steps.len() > 0 { steps[0] } else { {} };
3154                let first_note = if first.contains("note") { first.note } else { "fallback" };
3155                first_note
3156            }
3157
3158            pub fn first_ja(steps) {
3159                let first = if steps.len() > 0 { steps[0] } else { {} };
3160                if first.contains("ja") { first.ja } else { "すみません" }
3161            }
3162
3163            pub fn assign_first_note(steps) {
3164                let first = {};
3165                first = if steps.len() > 0 { steps[0] } else { {} };
3166                if first.contains("note") { first.note } else { "fallback" }
3167            }
3168            "#
3169            .as_bytes()
3170            .to_vec(),
3171        )?;
3172
3173        let compiled = vm.get_fn("vm_if_empty_object_branch::first_note", &[Type::Any])?;
3174        assert_eq!(compiled.ret_ty(), &Type::Str);
3175        let first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3176
3177        let empty_steps = Dynamic::list(Vec::new());
3178        assert_eq!(unsafe { &*first_note(&empty_steps) }.as_str(), "fallback");
3179
3180        let mut step = std::collections::BTreeMap::new();
3181        step.insert("note".into(), "hello".into());
3182        let steps = Dynamic::list(vec![Dynamic::map(step)]);
3183        assert_eq!(unsafe { &*first_note(&steps) }.as_str(), "hello");
3184
3185        let compiled = vm.get_fn("vm_if_empty_object_branch::first_ja", &[Type::Any])?;
3186        assert_eq!(compiled.ret_ty(), &Type::Any);
3187        let first_ja: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3188        assert_eq!(unsafe { &*first_ja(&empty_steps) }.as_str(), "すみません");
3189
3190        let compiled = vm.get_fn("vm_if_empty_object_branch::assign_first_note", &[Type::Any])?;
3191        assert_eq!(compiled.ret_ty(), &Type::Any);
3192        let assign_first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3193        assert_eq!(unsafe { &*assign_first_note(&empty_steps) }.as_str(), "fallback");
3194        assert_eq!(unsafe { &*assign_first_note(&steps) }.as_str(), "hello");
3195        Ok(())
3196    }
3197
3198    #[test]
3199    fn list_literal_can_be_function_tail_expression() -> anyhow::Result<()> {
3200        let vm = Vm::with_all()?;
3201        vm.import_code(
3202            "vm_tail_list_literal",
3203            r#"
3204            pub fn numbers() {
3205                [1, 2, 3]
3206            }
3207
3208            pub fn maps() {
3209                [
3210                    {note: "first"},
3211                    {note: "second"}
3212                ]
3213            }
3214
3215            pub fn object_with_maps() {
3216                {
3217                    steps: [
3218                        {note: "first"},
3219                        {note: "second"}
3220                    ]
3221                }
3222            }
3223
3224            pub fn return_maps() {
3225                return [
3226                    {note: "first"},
3227                    {note: "second"}
3228                ];
3229            }
3230
3231            pub fn return_maps_without_semicolon() {
3232                return [
3233                    {note: "first"},
3234                    {note: "second"}
3235                ]
3236            }
3237
3238            pub fn tail_bare_variable() {
3239                let value = [
3240                    {note: "first"},
3241                    {note: "second"}
3242                ];
3243                value
3244            }
3245
3246            pub fn return_bare_variable_without_semicolon() {
3247                let value = [
3248                    {note: "first"},
3249                    {note: "second"}
3250                ];
3251                return value
3252            }
3253
3254            pub fn tail_object_variable() {
3255                let result = {
3256                    steps: [
3257                        {note: "first"},
3258                        {note: "second"}
3259                    ]
3260                };
3261                result
3262            }
3263            "#
3264            .as_bytes()
3265            .to_vec(),
3266        )?;
3267
3268        let compiled = vm.get_fn("vm_tail_list_literal::numbers", &[])?;
3269        assert_eq!(compiled.ret_ty(), &Type::Any);
3270        let numbers: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3271        let result = unsafe { &*numbers() };
3272        assert_eq!(result.len(), 3);
3273        assert_eq!(result.get_idx(1).and_then(|value| value.as_int()), Some(2));
3274
3275        let compiled = vm.get_fn("vm_tail_list_literal::maps", &[])?;
3276        assert_eq!(compiled.ret_ty(), &Type::Any);
3277        let maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3278        let result = unsafe { &*maps() };
3279        assert_eq!(result.len(), 2);
3280        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3281
3282        let compiled = vm.get_fn("vm_tail_list_literal::object_with_maps", &[])?;
3283        assert_eq!(compiled.ret_ty(), &Type::Any);
3284        let object_with_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3285        let result = unsafe { &*object_with_maps() };
3286        let steps = result.get_dynamic("steps").expect("steps");
3287        assert_eq!(steps.len(), 2);
3288        assert_eq!(steps.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3289
3290        let compiled = vm.get_fn("vm_tail_list_literal::return_maps", &[])?;
3291        assert_eq!(compiled.ret_ty(), &Type::Any);
3292        let return_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3293        let result = unsafe { &*return_maps() };
3294        assert_eq!(result.len(), 2);
3295        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3296
3297        let compiled = vm.get_fn("vm_tail_list_literal::return_maps_without_semicolon", &[])?;
3298        assert_eq!(compiled.ret_ty(), &Type::Any);
3299        let return_maps_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3300        let result = unsafe { &*return_maps_without_semicolon() };
3301        assert_eq!(result.len(), 2);
3302        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3303
3304        let compiled = vm.get_fn("vm_tail_list_literal::tail_bare_variable", &[])?;
3305        assert_eq!(compiled.ret_ty(), &Type::Any);
3306        let tail_bare_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3307        let result = unsafe { &*tail_bare_variable() };
3308        assert_eq!(result.len(), 2);
3309        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3310
3311        let compiled = vm.get_fn("vm_tail_list_literal::return_bare_variable_without_semicolon", &[])?;
3312        assert_eq!(compiled.ret_ty(), &Type::Any);
3313        let return_bare_variable_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3314        let result = unsafe { &*return_bare_variable_without_semicolon() };
3315        assert_eq!(result.len(), 2);
3316        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
3317
3318        let compiled = vm.get_fn("vm_tail_list_literal::tail_object_variable", &[])?;
3319        assert_eq!(compiled.ret_ty(), &Type::Any);
3320        let tail_object_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3321        let result = unsafe { &*tail_object_variable() };
3322        let steps = result.get_dynamic("steps").expect("steps");
3323        assert_eq!(steps.len(), 2);
3324        assert_eq!(steps.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
3325        Ok(())
3326    }
3327
3328    #[test]
3329    fn match_literals_or_guard_order_and_block_body() -> anyhow::Result<()> {
3330        let vm = Vm::with_all()?;
3331        vm.import_code(
3332            "vm_match_scalar",
3333            r#"
3334            pub fn classify(value: i64) {
3335                match value {
3336                    0i64 => 10i64,
3337                    1i64 | 2i64 => 20i64,
3338                    x if x > 10i64 => x + 100i64,
3339                    _ => -1i64,
3340                }
3341            }
3342
3343            pub fn first_arm_wins() {
3344                match 1i64 {
3345                    _ => 7i64,
3346                    1i64 => 9i64,
3347                }
3348            }
3349
3350            pub fn block_body(value: i64) {
3351                match value {
3352                    3i64 => {
3353                        let base = 4i64;
3354                        base + 5i64
3355                    },
3356                    _ => 1i64,
3357                }
3358            }
3359            "#
3360            .as_bytes()
3361            .to_vec(),
3362        )?;
3363
3364        let classify = vm.get_fn("vm_match_scalar::classify", &[Type::I64])?;
3365        assert_eq!(call_i64_1(&classify, 0), 10);
3366        assert_eq!(call_i64_1(&classify, 1), 20);
3367        assert_eq!(call_i64_1(&classify, 2), 20);
3368        assert_eq!(call_i64_1(&classify, 12), 112);
3369        assert_eq!(call_i64_1(&classify, 5), -1);
3370
3371        let first_arm_wins = vm.get_fn("vm_match_scalar::first_arm_wins", &[])?;
3372        assert_eq!(call_i64_0(&first_arm_wins), 7);
3373
3374        let block_body = vm.get_fn("vm_match_scalar::block_body", &[Type::I64])?;
3375        assert_eq!(call_i64_1(&block_body, 3), 9);
3376        assert_eq!(call_i64_1(&block_body, 4), 1);
3377        Ok(())
3378    }
3379
3380    #[test]
3381    fn match_binds_tuple_list_rest_and_struct_fields() -> anyhow::Result<()> {
3382        let vm = Vm::with_all()?;
3383        vm.import_code(
3384            "vm_match_bindings",
3385            r#"
3386            pub fn tuple_sum() {
3387                match (3i64, 4i64) {
3388                    (a, b) => a + b,
3389                    _ => 0i64,
3390                }
3391            }
3392
3393            pub fn list_rest_score() {
3394                let items = [1i64, 2i64, 3i64, 4i64];
3395                match items {
3396                    [head, second, ..tail] if tail.len() == 2 => head * 100i64 + second * 10i64 + tail[1],
3397                    _ => -1i64,
3398                }
3399            }
3400
3401            pub fn struct_field_score() {
3402                let data = {
3403                    id: 7i64,
3404                    tags: ["a", "b", "c"],
3405                    nested: { value: 5i64 }
3406                };
3407                match data {
3408                    Data { id, tags: ["a", second, ..rest], nested: Data { value } } => {
3409                        id * 100i64 + value * 10i64 + rest.len()
3410                    },
3411                    _ => -1i64,
3412                }
3413            }
3414            "#
3415            .as_bytes()
3416            .to_vec(),
3417        )?;
3418
3419        let tuple_sum = vm.get_fn("vm_match_bindings::tuple_sum", &[])?;
3420        assert_eq!(call_i64_0(&tuple_sum), 7);
3421
3422        let list_rest_score = vm.get_fn("vm_match_bindings::list_rest_score", &[])?;
3423        assert_eq!(call_i64_0(&list_rest_score), 124);
3424
3425        let struct_field_score = vm.get_fn("vm_match_bindings::struct_field_score", &[])?;
3426        assert_eq!(call_i64_0(&struct_field_score), 751);
3427        Ok(())
3428    }
3429
3430    #[test]
3431    fn match_supports_nested_expressions_and_null_miss() -> anyhow::Result<()> {
3432        let vm = Vm::with_all()?;
3433        vm.import_code(
3434            "vm_match_nested",
3435            r#"
3436            pub fn nested(value: i64) {
3437                match value {
3438                    1i64 => match "a" {
3439                        "a" => 11i64,
3440                        _ => 12i64,
3441                    },
3442                    2i64 => match [1i64, 2i64] {
3443                        [_, tail] => tail + 20i64,
3444                        _ => 0i64,
3445                    },
3446                    _ => 0i64,
3447                }
3448            }
3449
3450            pub fn no_arm(value: i64) {
3451                match value {
3452                    1i64 => 10i64,
3453                }
3454            }
3455            "#
3456            .as_bytes()
3457            .to_vec(),
3458        )?;
3459
3460        let nested = vm.get_fn("vm_match_nested::nested", &[Type::I64])?;
3461        assert_eq!(call_i64_1(&nested, 1), 11);
3462        assert_eq!(call_i64_1(&nested, 2), 22);
3463        assert_eq!(call_i64_1(&nested, 3), 0);
3464
3465        let no_arm = vm.get_fn("vm_match_nested::no_arm", &[Type::I64])?;
3466        assert_eq!(no_arm.ret_ty(), &Type::Any);
3467        let no_arm: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(no_arm.ptr()) };
3468        assert_eq!(unsafe { &*no_arm(1) }.as_int(), Some(10));
3469        assert!(unsafe { &*no_arm(2) }.is_null());
3470        Ok(())
3471    }
3472
3473    #[test]
3474    fn match_rejects_binding_after_first_or_pattern() -> anyhow::Result<()> {
3475        let vm = Vm::with_all()?;
3476        let err = vm
3477            .import_code(
3478                "vm_match_bad_or",
3479                r#"
3480                pub fn bad(value: i64) {
3481                    match value {
3482                        a | b => 1i64,
3483                    }
3484                }
3485                "#
3486                .as_bytes()
3487                .to_vec(),
3488            )
3489            .expect_err("non-first or-pattern alternatives cannot bind");
3490        assert!(err.to_string().contains("or-pattern"));
3491        Ok(())
3492    }
3493
3494    #[test]
3495    fn list_return_value_supports_get_idx_method_call() -> anyhow::Result<()> {
3496        let vm = Vm::with_all()?;
3497        vm.import_code(
3498            "vm_returned_list_get_idx",
3499            r#"
3500            pub fn ids() {
3501                [
3502                    "base",
3503                    "2",
3504                    "3"
3505                ]
3506            }
3507
3508            pub fn combinations() {
3509                let result = [];
3510                let values = ids();
3511                let idx = 0;
3512                while idx < values.len() {
3513                    result.push(values.get_idx(idx));
3514                    idx = idx + 1;
3515                }
3516                result
3517            }
3518            "#
3519            .as_bytes()
3520            .to_vec(),
3521        )?;
3522
3523        let compiled = vm.get_fn("vm_returned_list_get_idx::combinations", &[])?;
3524        assert_eq!(compiled.ret_ty(), &Type::Any);
3525        let combinations: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3526        let result = unsafe { &*combinations() };
3527
3528        assert_eq!(result.len(), 3);
3529        assert_eq!(result.get_idx(0).map(|value| value.as_str().to_string()), Some("base".to_string()));
3530        assert_eq!(result.get_idx(2).map(|value| value.as_str().to_string()), Some("3".to_string()));
3531        Ok(())
3532    }
3533
3534    #[test]
3535    fn repeated_deep_step_literals_import_successfully() -> anyhow::Result<()> {
3536        fn extra_page_literal(depth: usize) -> String {
3537            let mut value = "{leaf: \"done\"}".to_string();
3538            for idx in 0..depth {
3539                value = format!("{{kind: \"page\", idx: {idx}, children: [{value}], meta: {{title: \"extra\", visible: true}}}}");
3540            }
3541            value
3542        }
3543
3544        let extra = extra_page_literal(48);
3545        let code = format!(
3546            r#"
3547            pub fn script() {{
3548                return [
3549                    {{ja: "一つ目", note: "first", extra: {extra}}},
3550                    {{ja: "二つ目", note: "second", extra: {extra}}},
3551                    {{ja: "三つ目", note: "third", extra: {extra}}}
3552                ]
3553            }}
3554            "#
3555        );
3556
3557        let vm = Vm::with_all()?;
3558        vm.import_code("vm_repeated_deep_step_literals", code.into_bytes())?;
3559        let compiled = vm.get_fn("vm_repeated_deep_step_literals::script", &[])?;
3560        assert_eq!(compiled.ret_ty(), &Type::Any);
3561        let script: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3562        let result = unsafe { &*script() };
3563        assert_eq!(result.len(), 3);
3564        assert_eq!(result.get_idx(2).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("third".to_string()));
3565        Ok(())
3566    }
3567
3568    #[test]
3569    fn native_import_uses_owning_vm() -> anyhow::Result<()> {
3570        let module_path = std::env::temp_dir().join(format!("zust_vm_import_owner_{}.zs", std::process::id()));
3571        std::fs::write(&module_path, "pub fn value() { 41 }")?;
3572        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
3573
3574        let vm1 = Vm::with_all()?;
3575        vm1.import_code(
3576            "vm_import_owner",
3577            format!(
3578                r#"
3579                pub fn run() {{
3580                    import("vm_imported_owner", "{module_path}");
3581                }}
3582                "#
3583            )
3584            .into_bytes(),
3585        )?;
3586        let compiled = vm1.get_fn("vm_import_owner::run", &[])?;
3587
3588        let vm2 = Vm::with_all()?;
3589        vm2.import_code("vm_import_other", b"pub fn run() { 0 }".to_vec())?;
3590        let _ = vm2.get_fn("vm_import_other::run", &[])?;
3591
3592        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
3593        run();
3594
3595        assert!(vm1.get_fn("vm_imported_owner::value", &[]).is_ok());
3596        assert!(vm2.get_fn("vm_imported_owner::value", &[]).is_err());
3597        Ok(())
3598    }
3599
3600    #[test]
3601    fn object_last_field_call_does_not_need_trailing_comma() -> anyhow::Result<()> {
3602        let vm = Vm::with_all()?;
3603        vm.import_code(
3604            "vm_object_last_call_field",
3605            r#"
3606            pub fn extra_page() {
3607                {
3608                    title: "extra",
3609                    pages: [
3610                        {note: "nested"}
3611                    ]
3612                }
3613            }
3614
3615            pub fn data() {
3616                return [
3617                    {
3618                        note: "first",
3619                        choices: ["a", "b"],
3620                        extras: extra_page()
3621                    },
3622                    {
3623                        note: "second",
3624                        choices: ["c"],
3625                        extras: extra_page()
3626                    }
3627                ]
3628            }
3629            "#
3630            .as_bytes()
3631            .to_vec(),
3632        )?;
3633
3634        let compiled = vm.get_fn("vm_object_last_call_field::data", &[])?;
3635        assert_eq!(compiled.ret_ty(), &Type::Any);
3636        let data: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3637        let result = unsafe { &*data() };
3638        assert_eq!(result.len(), 2);
3639        let first = result.get_idx(0).expect("first step");
3640        assert_eq!(first.get_dynamic("extras").and_then(|extras| extras.get_dynamic("title")).map(|title| title.as_str().to_string()), Some("extra".to_string()));
3641        Ok(())
3642    }
3643
3644    #[test]
3645    fn string_return_survives_scope_exit() -> anyhow::Result<()> {
3646        let vm = Vm::with_all()?;
3647        vm.import_code(
3648            "vm_string_return_scope",
3649            r#"
3650            pub fn source_root() {
3651                "../assets/character/男主角换装"
3652            }
3653
3654            pub fn binary_root() {
3655                "character_binary/男主角换装"
3656            }
3657
3658            pub fn runtime_binary_url() {
3659                "/" + binary_root()
3660            }
3661
3662            pub fn action_groups() {
3663                let root = source_root();
3664                let binary_url = runtime_binary_url();
3665                let binary_root = binary_root();
3666                [
3667                    {
3668                        id: "field_bottom",
3669                        source_spine: root + "/战斗外/boy_b.spine",
3670                        skeleton: binary_url + "/战斗外/boy_b/boy_b.skel.bytes",
3671                        export_skeleton: binary_root + "/战斗外/boy_b/boy_b.skel.bytes"
3672                    }
3673                ]
3674            }
3675            "#
3676            .as_bytes()
3677            .to_vec(),
3678        )?;
3679
3680        let compiled = vm.get_fn("vm_string_return_scope::source_root", &[])?;
3681        assert_eq!(compiled.ret_ty(), &Type::Str);
3682        let source_root: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3683        let source_root = unsafe { &*source_root() };
3684        assert_eq!(source_root.as_str(), "../assets/character/男主角换装");
3685
3686        let compiled = vm.get_fn("vm_string_return_scope::action_groups", &[])?;
3687        assert_eq!(compiled.ret_ty(), &Type::Any);
3688        let action_groups: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3689        let groups = unsafe { &*action_groups() };
3690        let first = groups.get_idx(0).expect("first action group");
3691        assert_eq!(first.get_dynamic("source_spine").map(|value| value.as_str().to_string()), Some("../assets/character/男主角换装/战斗外/boy_b.spine".to_string()));
3692        assert_eq!(first.get_dynamic("skeleton").map(|value| value.as_str().to_string()), Some("/character_binary/男主角换装/战斗外/boy_b/boy_b.skel.bytes".to_string()));
3693        Ok(())
3694    }
3695
3696    #[test]
3697    fn dynamic_string_add_uses_any_binary_fast_path() -> anyhow::Result<()> {
3698        let vm = Vm::with_all()?;
3699        vm.import_code(
3700            "vm_dynamic_string_add",
3701            br#"
3702            pub fn concat(left, right) {
3703                left + right
3704            }
3705            "#
3706            .to_vec(),
3707        )?;
3708
3709        let compiled = vm.get_fn("vm_dynamic_string_add::concat", &[Type::Any, Type::Any])?;
3710        assert_eq!(compiled.ret_ty(), &Type::Any);
3711        let concat: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3712        let left = Dynamic::from("hello");
3713        let right = Dynamic::from(" world");
3714        let result = unsafe { &*concat(&left, &right) };
3715        assert_eq!(result.as_str(), "hello world");
3716        Ok(())
3717    }
3718
3719    #[test]
3720    fn large_dynamic_object_accepts_inline_call_fields() -> anyhow::Result<()> {
3721        let vm = Vm::with_all()?;
3722        let model_count = 180;
3723        let combination_count = 90;
3724        let models = (0..model_count)
3725            .map(|idx| {
3726                format!(
3727                    r#"{{id: "model_{idx}", name: "模型_{idx}", source: "/美术资源/角色/少年/套装_{idx}/模型_{idx}.model.json", parts: [
3728                        {{slot: "hair", path: "/模型/头发/颜色_{idx}/默认.png", z: 10}},
3729                        {{slot: "body", path: "/模型/身体/套装_{idx}/默认.png", z: 1}},
3730                        {{slot: "face", path: "/模型/表情/表情_{idx}/默认.png", z: 20}}
3731                    ]}}"#
3732                )
3733            })
3734            .collect::<Vec<_>>()
3735            .join(",\n");
3736        let combinations = (0..combination_count).map(|idx| format!(r#"{{hair: "color_{idx}", body: "set_{idx}", face: "face_{idx}"}}"#)).collect::<Vec<_>>().join(",\n");
3737        let code = format!(
3738            r#"
3739            pub fn source_root() {{
3740                "/美术资源/角色/少年/默认"
3741            }}
3742
3743            pub fn runtime_boy_url() {{
3744                "/cdn/runtime/角色/少年/少年.model.json"
3745            }}
3746
3747            pub fn parts() {{
3748                [
3749                    {{id: "hair", path: "/模型/头发/黑色/默认.png", z: 10}},
3750                    {{id: "body", path: "/模型/身体/校服/默认.png", z: 1}},
3751                    {{id: "face", path: "/模型/表情/微笑/默认.png", z: 20}}
3752                ]
3753            }}
3754
3755            pub fn action_groups() {{
3756                {{
3757                    idle: [
3758                        {{id: "stand", name: "站立", frames: ["待机/0001.png", "待机/0002.png"]}},
3759                        {{id: "blink", name: "眨眼", frames: ["表情/眨眼/0001.png", "表情/眨眼/0002.png"]}}
3760                    ],
3761                    move: [
3762                        {{id: "walk", name: "行走", frames: ["行走/0001.png", "行走/0002.png"]}},
3763                        {{id: "run", name: "奔跑", frames: ["奔跑/0001.png", "奔跑/0002.png"]}}
3764                    ]
3765                }}
3766            }}
3767
3768            pub fn default_model() {{
3769                {{
3770                    id: "runtime_boy",
3771                    name: "运行时少年",
3772                    skins: [
3773                        {{id: "school", title: "校服", source: "/套装/校服/model.json"}},
3774                        {{id: "casual", title: "便服", source: "/套装/便服/model.json"}}
3775                    ],
3776                    models: [
3777                        {models}
3778                    ]
3779                }}
3780            }}
3781
3782            pub fn first_nine_combinations() {{
3783                [
3784                    {combinations}
3785                ]
3786            }}
3787
3788            pub fn config() {{
3789                {{
3790                    source_root: source_root(),
3791                    runtime_boy_url: runtime_boy_url(),
3792                    parts: parts(),
3793                    action_groups: action_groups(),
3794                    default_model: default_model(),
3795                    first_nine_combinations: first_nine_combinations()
3796                }}
3797            }}
3798
3799            pub fn start() {{
3800                root::add("local/vm_large_inline_call_object/config", {{
3801                    source_root: source_root(),
3802                    runtime_boy_url: runtime_boy_url(),
3803                    parts: parts(),
3804                    action_groups: action_groups(),
3805                    default_model: default_model(),
3806                    first_nine_combinations: first_nine_combinations()
3807                }})
3808            }}
3809            "#
3810        );
3811        vm.import_code("vm_large_inline_call_object", code.into_bytes())?;
3812
3813        let compiled = vm.get_fn("vm_large_inline_call_object::config", &[])?;
3814        assert_eq!(compiled.ret_ty(), &Type::Any);
3815        let config: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3816        let result = unsafe { &*config() };
3817        assert_eq!(result.get_dynamic("source_root").map(|value| value.as_str().to_string()), Some("/美术资源/角色/少年/默认".to_string()));
3818        assert_eq!(result.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
3819
3820        let compiled = vm.get_fn("vm_large_inline_call_object::start", &[])?;
3821        assert_eq!(compiled.ret_ty(), &Type::Bool);
3822        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3823        assert!(start());
3824        let saved = root::get("local/vm_large_inline_call_object/config")?;
3825        assert_eq!(saved.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
3826        Ok(())
3827    }
3828
3829    #[cfg(feature = "http")]
3830    #[test]
3831    fn http_serve_accepts_inline_config_map() -> anyhow::Result<()> {
3832        let vm = Vm::with_all()?;
3833        vm.import_code(
3834            "vm_http_serve_inline_config",
3835            br#"
3836            pub fn start() {
3837                let server = http::serve({host: "127.0.0.1:5192"});
3838                server
3839            }
3840            "#
3841            .to_vec(),
3842        )?;
3843
3844        let compiled = vm.get_fn("vm_http_serve_inline_config::start", &[])?;
3845        assert_eq!(compiled.ret_ty(), &Type::Any);
3846        Ok(())
3847    }
3848
3849    #[cfg(feature = "http")]
3850    #[test]
3851    fn http_serve_accepts_variable_and_quoted_static_key() -> anyhow::Result<()> {
3852        let vm = Vm::with_all()?;
3853        vm.import_code(
3854            "vm_http_serve_quoted_static",
3855            br#"
3856            pub fn start(server_addr) {
3857                let http_server = http::serve({
3858                    host: server_addr,
3859                    ws: true,
3860                    upload: "upload",
3861                    "static": {
3862                        path: "/",
3863                        dir: "public/local"
3864                    }
3865                });
3866                http_server
3867            }
3868            "#
3869            .to_vec(),
3870        )?;
3871
3872        let compiled = vm.get_fn("vm_http_serve_quoted_static::start", &[Type::Any])?;
3873        assert_eq!(compiled.ret_ty(), &Type::Any);
3874        Ok(())
3875    }
3876
3877    #[cfg(all(feature = "http", feature = "llm"))]
3878    #[test]
3879    fn oss_helpers_accept_explicit_config() -> anyhow::Result<()> {
3880        let vm = Vm::with_all()?;
3881        vm.import_code(
3882            "vm_oss_explicit_config",
3883            br#"
3884            pub fn upload(oss, bytes) {
3885                oss::upload(oss, "llm/input/audio.wav", bytes)
3886            }
3887
3888            pub fn http_upload(oss, bytes) {
3889                http::upload(oss, "uploads/input.bin", bytes)
3890            }
3891
3892            pub fn link(oss, uploaded) {
3893                oss::signed_url(oss, {oss_url: uploaded, expires: 3600})
3894            }
3895            "#
3896            .to_vec(),
3897        )?;
3898
3899        assert_eq!(vm.get_fn("vm_oss_explicit_config::upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
3900        assert_eq!(vm.get_fn("vm_oss_explicit_config::http_upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
3901        assert_eq!(vm.get_fn("vm_oss_explicit_config::link", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
3902        Ok(())
3903    }
3904
3905    #[cfg(feature = "http")]
3906    #[test]
3907    fn load_script_accepts_http_serve_inline_config() -> anyhow::Result<()> {
3908        let vm = Vm::with_all()?;
3909        let (_fn_ptr, ty) = vm.load(
3910            br#"
3911            let server_addr = "127.0.0.1:5192";
3912            let http_server = http::serve({
3913                host: server_addr,
3914                ws: true,
3915                upload: "upload",
3916                "static": {
3917                    path: "/",
3918                    dir: "public/local"
3919                }
3920            });
3921            http_server
3922            "#
3923            .to_vec(),
3924            "arg".into(),
3925        )?;
3926
3927        assert_eq!(ty, Type::Any);
3928        Ok(())
3929    }
3930
3931    #[test]
3932    fn load_script_resolves_import_before_compile() -> anyhow::Result<()> {
3933        let module_path = std::env::temp_dir().join(format!("zust_vm_load_import_{}.zs", std::process::id()));
3934        std::fs::write(&module_path, "pub fn init() { return {ok: true}; }")?;
3935        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
3936
3937        let vm = Vm::with_all()?;
3938        let (_fn_ptr, ty) = vm.load(
3939            format!(
3940                r#"
3941                import("create_scene", "{module_path}");
3942                create_scene::init();
3943                "#
3944            )
3945            .into_bytes(),
3946            "req".into(),
3947        )?;
3948
3949        assert_eq!(ty, Type::Void);
3950        Ok(())
3951    }
3952
3953    #[test]
3954    fn gpu_struct_layout_packs_and_unpacks_dynamic_maps() -> anyhow::Result<()> {
3955        let vm = Vm::with_all()?;
3956        vm.import_code(
3957            "vm_gpu_layout",
3958            br#"
3959            pub struct Params {
3960                a: u32,
3961                b: u32,
3962                c: u32,
3963            }
3964            "#
3965            .to_vec(),
3966        )?;
3967
3968        let layout = vm.gpu_struct_layout("vm_gpu_layout::Params", &[])?;
3969        assert_eq!(layout.size, 16);
3970        assert_eq!(layout.fields.iter().map(|field| (field.name.as_str(), field.offset)).collect::<Vec<_>>(), vec![("a", 0), ("b", 4), ("c", 8)]);
3971
3972        let value = dynamic::map!("a"=> 1u32, "b"=> 2u32, "c"=> 3u32);
3973        let bytes = layout.pack_map(&value)?;
3974        assert_eq!(bytes.len(), 16);
3975        assert_eq!(&bytes[0..4], &1u32.to_ne_bytes());
3976        assert_eq!(&bytes[4..8], &2u32.to_ne_bytes());
3977        assert_eq!(&bytes[8..12], &3u32.to_ne_bytes());
3978
3979        let read = layout.unpack_map(&bytes)?;
3980        assert_eq!(read.get_dynamic("a").and_then(|value| value.as_uint()), Some(1));
3981        assert_eq!(read.get_dynamic("b").and_then(|value| value.as_uint()), Some(2));
3982        assert_eq!(read.get_dynamic("c").and_then(|value| value.as_uint()), Some(3));
3983        Ok(())
3984    }
3985
3986    #[test]
3987    fn root_native_calls_do_not_take_ownership_of_dynamic_args() -> anyhow::Result<()> {
3988        let vm = Vm::with_all()?;
3989        vm.import_code(
3990            "vm_root_clone_bridge",
3991            br#"
3992            pub fn add_then_reuse(arg) {
3993                let user = {
3994                    address: "test-wallet",
3995                    points: 20
3996                };
3997                root::add("local/root-clone-bridge-user", user);
3998                user.points = user.points - 7;
3999                root::add("local/root-clone-bridge-user", user);
4000                {
4001                    user: user,
4002                    points: user.points
4003                }
4004            }
4005
4006            pub fn clone_then_mutate(arg) {
4007                let user = {
4008                    profile: {
4009                        points: 20
4010                    }
4011                };
4012                let copied = user.clone();
4013                copied.profile.points = 13;
4014                user
4015            }
4016            "#
4017            .to_vec(),
4018        )?;
4019
4020        let compiled = vm.get_fn("vm_root_clone_bridge::add_then_reuse", &[Type::Any])?;
4021        assert_eq!(compiled.ret_ty(), &Type::Any);
4022        let add_then_reuse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4023        let arg = Dynamic::Null;
4024        let result = add_then_reuse(&arg);
4025        let result = unsafe { &*result };
4026
4027        assert_eq!(result.get_dynamic("points").and_then(|value| value.as_int()), Some(13));
4028        let mut json = String::new();
4029        result.to_json(&mut json);
4030        assert!(json.contains("\"points\": 13"));
4031
4032        let clone_then_mutate = vm.get_fn("vm_root_clone_bridge::clone_then_mutate", &[Type::Any])?;
4033        let clone_then_mutate: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(clone_then_mutate.ptr()) };
4034        let result = clone_then_mutate(&arg);
4035        let result = unsafe { &*result };
4036        assert_eq!(result.get_dynamic("profile").unwrap().get_dynamic("points").and_then(|value| value.as_int()), Some(20));
4037        Ok(())
4038    }
4039
4040    struct CounterForTypedReceiver {
4041        value: i64,
4042    }
4043
4044    extern "C" fn counter_for_typed_receiver_get(value: *const Dynamic) -> i64 {
4045        unsafe { &*value }.as_custom::<CounterForTypedReceiver>().map(|counter| counter.value).unwrap_or(-1)
4046    }
4047
4048    struct NavMapForFunctionArg;
4049
4050    extern "C" fn nav_map_for_function_arg_new() -> *const Dynamic {
4051        Box::into_raw(Box::new(Dynamic::custom(NavMapForFunctionArg)))
4052    }
4053
4054    #[derive(Debug, Default)]
4055    struct PropertyForwardingObject {
4056        values: parking_lot::RwLock<BTreeMap<String, Dynamic>>,
4057    }
4058
4059    impl CustomProperty for PropertyForwardingObject {
4060        fn get_key(&self, key: &str) -> Option<Dynamic> {
4061            self.values.read().get(key).cloned()
4062        }
4063
4064        fn set_key(&self, key: &str, value: Dynamic) -> bool {
4065            self.values.write().insert(key.to_string(), value);
4066            true
4067        }
4068    }
4069
4070    extern "C" fn property_forwarding_object_new() -> *const Dynamic {
4071        Box::into_raw(Box::new(Dynamic::custom_with_properties(PropertyForwardingObject::default())))
4072    }
4073
4074    #[test]
4075    fn typed_receiver_method_call_dispatches_with_type_hint() -> anyhow::Result<()> {
4076        let vm = Vm::with_all()?;
4077        vm.add_empty_type("Counter")?;
4078        let counter_ty = vm.get_symbol("Counter", Vec::new())?;
4079        vm.add_native_method_ptr("Counter", "get", &[counter_ty], Type::I64, counter_for_typed_receiver_get as *const u8)?;
4080        vm.import_code(
4081            "vm_typed_receiver_method",
4082            br#"
4083            pub fn run(value) {
4084                value::<Counter>::get()
4085            }
4086            "#
4087            .to_vec(),
4088        )?;
4089
4090        let compiled = vm.get_fn("vm_typed_receiver_method::run", &[Type::Any])?;
4091        assert_eq!(compiled.ret_ty(), &Type::I64);
4092        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4093        let value = Dynamic::custom(CounterForTypedReceiver { value: 42 });
4094
4095        assert_eq!(run(&value), 42);
4096        Ok(())
4097    }
4098
4099    #[test]
4100    fn native_custom_object_can_be_passed_to_zs_function() -> anyhow::Result<()> {
4101        let vm = Vm::with_all()?;
4102        vm.add_empty_type("NavMap")?;
4103        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
4104        vm.import_code(
4105            "vm_native_custom_arg",
4106            br#"
4107            pub fn add_nav_spawns(world, navmap) {
4108                navmap
4109            }
4110
4111            pub fn run(world) {
4112                let navmap = NavMap::new();
4113                let with_spawns = add_nav_spawns(world, navmap);
4114                with_spawns
4115            }
4116            "#
4117            .to_vec(),
4118        )?;
4119
4120        let compiled = vm.get_fn("vm_native_custom_arg::run", &[Type::Any])?;
4121        assert_eq!(compiled.ret_ty(), &Type::Any);
4122        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4123        let world = Dynamic::Null;
4124        let result = run(&world);
4125        let result = unsafe { &*result };
4126
4127        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
4128        Ok(())
4129    }
4130
4131    #[test]
4132    fn any_field_assignment_forwards_to_custom_properties() -> anyhow::Result<()> {
4133        let vm = Vm::with_all()?;
4134        vm.add_empty_type("Dialog")?;
4135        vm.add_native_method_ptr("Dialog", "new", &[], Type::Any, property_forwarding_object_new as *const u8)?;
4136        vm.import_code(
4137            "vm_custom_property_forwarding",
4138            br#"
4139            pub fn run() {
4140                let dialog = Dialog::new();
4141                dialog.file_mode = 3;
4142                dialog.file_mode
4143            }
4144            "#
4145            .to_vec(),
4146        )?;
4147
4148        let compiled = vm.get_fn("vm_custom_property_forwarding::run", &[])?;
4149        assert_eq!(compiled.ret_ty(), &Type::Any);
4150        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4151        let result = unsafe { &*run() };
4152
4153        assert_eq!(result.as_int(), Some(3));
4154        Ok(())
4155    }
4156
4157    #[test]
4158    fn native_custom_object_typed_local_can_be_passed_to_zs_function() -> anyhow::Result<()> {
4159        let vm = Vm::with_all()?;
4160        vm.add_empty_type("NavMap")?;
4161        let _nav_map_ty = vm.get_symbol("NavMap", Vec::new())?;
4162        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
4163        vm.import_code(
4164            "vm_native_custom_typed_arg",
4165            br#"
4166            pub fn add_nav_spawns(world, navmap) {
4167                navmap
4168            }
4169
4170            pub fn run(world) {
4171                let navmap: NavMap = NavMap::new();
4172                let with_spawns = add_nav_spawns(world, navmap);
4173                with_spawns
4174            }
4175            "#
4176            .to_vec(),
4177        )?;
4178
4179        let compiled = vm.get_fn("vm_native_custom_typed_arg::run", &[Type::Any])?;
4180        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4181        let world = Dynamic::Null;
4182        let result = run(&world);
4183        let result = unsafe { &*result };
4184
4185        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
4186        Ok(())
4187    }
4188
4189    // ---- 新增边界条件测试 ----
4190
4191    #[test]
4192    fn dynamic_type_checks_on_null_and_primitive_values() -> anyhow::Result<()> {
4193        let vm = Vm::with_all()?;
4194        vm.import_code(
4195            "vm_dynamic_type_checks",
4196            br#"
4197            pub fn is_list_on_int() {
4198                let x = 42i64;
4199                x.is_list()
4200            }
4201
4202            pub fn is_map_on_int() {
4203                let x = 42i64;
4204                x.is_map()
4205            }
4206
4207            pub fn is_null_on_int() {
4208                let x = 42i64;
4209                x.is_null()
4210            }
4211            "#
4212            .to_vec(),
4213        )?;
4214
4215        let compiled = vm.get_fn("vm_dynamic_type_checks::is_list_on_int", &[])?;
4216        assert_eq!(compiled.ret_ty(), &Type::Bool);
4217        let is_list_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4218        assert!(!is_list_on_int());
4219
4220        let compiled = vm.get_fn("vm_dynamic_type_checks::is_map_on_int", &[])?;
4221        assert_eq!(compiled.ret_ty(), &Type::Bool);
4222        let is_map_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4223        assert!(!is_map_on_int());
4224
4225        let compiled = vm.get_fn("vm_dynamic_type_checks::is_null_on_int", &[])?;
4226        assert_eq!(compiled.ret_ty(), &Type::Bool);
4227        let is_null_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4228        assert!(!is_null_on_int());
4229        Ok(())
4230    }
4231
4232    #[test]
4233    fn void_and_null_are_false_in_boolean_context() -> anyhow::Result<()> {
4234        let vm = Vm::with_all()?;
4235        vm.import_code(
4236            "vm_void_bool_context",
4237            br#"
4238            pub fn run() {
4239                let items = [1i32, 2i32];
4240                let ok1 = !(items.push(3i32) && false);
4241                let ok2 = !(true && items.push(4i32));
4242                let ok3 = null || true;
4243                let ok4 = null || items.len() == 4;
4244                ok1 && ok2 && ok3 && ok4
4245            }
4246            "#
4247            .to_vec(),
4248        )?;
4249
4250        let compiled = vm.get_fn("vm_void_bool_context::run", &[])?;
4251        assert_eq!(compiled.ret_ty(), &Type::Bool);
4252        let run: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4253        assert!(run());
4254        Ok(())
4255    }
4256
4257    #[test]
4258    fn empty_for_loop_range_has_zero_iterations() -> anyhow::Result<()> {
4259        let vm = Vm::with_all()?;
4260        vm.import_code(
4261            "vm_empty_for_range",
4262            br#"
4263            pub fn empty_exclusive() {
4264                let count = 0i32;
4265                for i in 0..0 {
4266                    count += i;
4267                }
4268                count
4269            }
4270
4271            pub fn single_inclusive_iteration() {
4272                let count = 0i32;
4273                for i in 5..=5 {
4274                    count += i;
4275                }
4276                count
4277            }
4278            "#
4279            .to_vec(),
4280        )?;
4281
4282        // 无后缀 range 字面量(0..0 / 5..=5)默认 I64,累加器随复合赋值提升为 I64
4283        let compiled = vm.get_fn("vm_empty_for_range::empty_exclusive", &[])?;
4284        assert_eq!(compiled.ret_ty(), &Type::I64);
4285        let empty_exclusive: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4286        assert_eq!(empty_exclusive(), 0);
4287
4288        let compiled = vm.get_fn("vm_empty_for_range::single_inclusive_iteration", &[])?;
4289        assert_eq!(compiled.ret_ty(), &Type::I64);
4290        let single_inclusive: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4291        assert_eq!(single_inclusive(), 5);
4292        Ok(())
4293    }
4294
4295    #[test]
4296    fn for_loop_range_accepts_dynamic_i64_bounds() -> anyhow::Result<()> {
4297        let vm = Vm::with_all()?;
4298        vm.import_code(
4299            "vm_dynamic_for_range",
4300            br#"
4301            pub fn main() {
4302                let view = {};
4303                view.grid_min_x = -2i64;
4304                view.grid_max_x = 2i64;
4305
4306                let end_x = view.grid_max_x + 1i64;
4307                let count = 0i64;
4308
4309                for x in view.grid_min_x..end_x {
4310                    count += 1i64;
4311                }
4312
4313                count
4314            }
4315            "#
4316            .to_vec(),
4317        )?;
4318
4319        let compiled = vm.get_fn("vm_dynamic_for_range::main", &[])?;
4320        assert_eq!(compiled.ret_ty(), &Type::I64);
4321        let main: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4322        assert_eq!(main(), 5);
4323        Ok(())
4324    }
4325
4326    #[test]
4327    fn map_contains_key_on_non_existent_and_nested_keys() -> anyhow::Result<()> {
4328        let vm = Vm::with_all()?;
4329        vm.import_code(
4330            "vm_map_contains",
4331            br#"
4332            pub fn contains_existing(data) {
4333                data.contains("name")
4334            }
4335
4336            pub fn contains_missing(data) {
4337                data.contains("nothing")
4338            }
4339            "#
4340            .to_vec(),
4341        )?;
4342
4343        let compiled = vm.get_fn("vm_map_contains::contains_existing", &[Type::Any])?;
4344        assert_eq!(compiled.ret_ty(), &Type::Bool);
4345        let contains_existing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4346        let data = dynamic::map!("name"=> "test");
4347        assert!(contains_existing(&data));
4348
4349        let compiled = vm.get_fn("vm_map_contains::contains_missing", &[Type::Any])?;
4350        assert_eq!(compiled.ret_ty(), &Type::Bool);
4351        let contains_missing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4352        assert!(!contains_missing(&data));
4353        Ok(())
4354    }
4355
4356    #[test]
4357    fn list_pop_on_empty_list_returns_null() -> anyhow::Result<()> {
4358        let vm = Vm::with_all()?;
4359        vm.import_code(
4360            "vm_pop_empty",
4361            br#"
4362            pub fn pop_new_list() {
4363                let items = [];
4364                let value = items.pop();
4365                let still_empty = items.len() == 0;
4366                {value: value, empty: still_empty}
4367            }
4368
4369            pub fn pop_until_empty() {
4370                let items = [1i64, 2i64];
4371                items.pop();
4372                let last = items.pop();
4373                let drained = items.pop();
4374                {last: last, drained: drained}
4375            }
4376            "#
4377            .to_vec(),
4378        )?;
4379
4380        let compiled = vm.get_fn("vm_pop_empty::pop_new_list", &[])?;
4381        assert_eq!(compiled.ret_ty(), &Type::Any);
4382        let pop_new_list: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4383        let result = unsafe { &*pop_new_list() };
4384        assert!(result.get_dynamic("value").is_some_and(|v| v.is_null()));
4385        assert_eq!(result.get_dynamic("empty").and_then(|v| v.as_bool()), Some(true));
4386
4387        let compiled = vm.get_fn("vm_pop_empty::pop_until_empty", &[])?;
4388        assert_eq!(compiled.ret_ty(), &Type::Any);
4389        let pop_until_empty: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4390        let result = unsafe { &*pop_until_empty() };
4391        assert_eq!(result.get_dynamic("last").and_then(|v| v.as_int()), Some(1));
4392        assert!(result.get_dynamic("drained").is_some_and(|v| v.is_null()));
4393        Ok(())
4394    }
4395
4396    #[test]
4397    fn void_function_with_multiple_code_paths() -> anyhow::Result<()> {
4398        let vm = Vm::with_all()?;
4399        vm.import_code(
4400            "vm_void_multi_path",
4401            br#"
4402            pub fn log_if_positive(value: i64) {
4403                if value > 0 {
4404                    print(value);
4405                    return;
4406                }
4407                if value < 0 {
4408                    print(-value);
4409                    return;
4410                }
4411                print(0);
4412            }
4413            "#
4414            .to_vec(),
4415        )?;
4416
4417        let compiled = vm.get_fn("vm_void_multi_path::log_if_positive", &[Type::I64])?;
4418        assert!(compiled.ret_ty().is_void());
4419        Ok(())
4420    }
4421
4422    #[test]
4423    fn any_method_call_chain_on_returned_dynamic_value() -> anyhow::Result<()> {
4424        let vm = Vm::with_all()?;
4425        vm.import_code(
4426            "vm_any_method_chain",
4427            br#"
4428            pub fn get_tags(data) {
4429                let tags = data.tags;
4430                if tags.is_list() {
4431                    return tags.len();
4432                }
4433                0
4434            }
4435            "#
4436            .to_vec(),
4437        )?;
4438
4439        let compiled = vm.get_fn("vm_any_method_chain::get_tags", &[Type::Any])?;
4440        assert_eq!(compiled.ret_ty(), &Type::I64);
4441        let get_tags: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4442        let data = dynamic::map!("tags"=> Dynamic::list(vec!["a".into(), "b".into(), "c".into()]));
4443        assert_eq!(get_tags(&data), 3);
4444
4445        let empty_data = Dynamic::Null;
4446        assert_eq!(get_tags(&empty_data), 0);
4447        Ok(())
4448    }
4449
4450    #[test]
4451    fn infers_any_arg_function_return_before_body_compile() -> anyhow::Result<()> {
4452        let vm = Vm::with_all()?;
4453        vm.import_code(
4454            "vm_infer_any_arg_return",
4455            br#"
4456            pub fn caller(candidate) {
4457                let center = polygon_center(candidate.visualPolygon);
4458                center[0]
4459            }
4460
4461            pub fn polygon_center(point_list) {
4462                let total_x = 0;
4463                let total_y = 0;
4464                let count = 0;
4465                if point_list.is_list() {
4466                    for point in point_list {
4467                        if point.is_list() && point.len() >= 2 {
4468                            total_x += point[0];
4469                            total_y += point[1];
4470                            count += 1;
4471                        }
4472                    }
4473                }
4474                if count == 0 {
4475                    return [0, 0];
4476                }
4477                [total_x / count, total_y / count]
4478            }
4479            "#
4480            .to_vec(),
4481        )?;
4482
4483        let compiled = vm.get_fn("vm_infer_any_arg_return::caller", &[Type::Any])?;
4484        assert_eq!(compiled.ret_ty(), &Type::Any);
4485        let caller: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4486        let candidate = dynamic::map!(
4487            "visualPolygon"=> Dynamic::list(vec![
4488                Dynamic::list(vec![2i64.into(), 4i64.into()]),
4489                Dynamic::list(vec![6i64.into(), 8i64.into()]),
4490            ])
4491        );
4492        let result = unsafe { &*caller(&candidate) };
4493        assert_eq!(result.as_int(), Some(4));
4494        Ok(())
4495    }
4496
4497    #[test]
4498    fn recursive_factorial_keeps_static_return_type() -> anyhow::Result<()> {
4499        let vm = Vm::with_all()?;
4500        vm.import_code(
4501            "vm_recursive_factorial",
4502            br#"
4503            fn factorial(n: i64) {
4504                if n <= 1 {
4505                    return 1;
4506                }
4507                n * factorial(n - 1)
4508            }
4509
4510            pub fn run(n: i64) {
4511                factorial(n)
4512            }
4513            "#
4514            .to_vec(),
4515        )?;
4516
4517        let compiled = vm.get_fn("vm_recursive_factorial::run", &[Type::I64])?;
4518        assert_eq!(compiled.ret_ty(), &Type::I64);
4519        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4520        assert_eq!(run(5), 120);
4521        Ok(())
4522    }
4523
4524    #[test]
4525    fn explicit_const_generic_function_calls_generate_distinct_variants() -> anyhow::Result<()> {
4526        let vm = Vm::with_all()?;
4527        vm.import_code(
4528            "vm_generic_const_variants",
4529            br#"
4530            fn value<N>() {
4531                N
4532            }
4533
4534            pub fn two() {
4535                value::<2>()
4536            }
4537
4538            pub fn three() {
4539                value::<3>()
4540            }
4541            "#
4542            .to_vec(),
4543        )?;
4544
4545        let compiled = vm.get_fn("vm_generic_const_variants::two", &[])?;
4546        assert_eq!(compiled.ret_ty(), &Type::I32);
4547        let two: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4548        assert_eq!(two(), 2);
4549
4550        let compiled = vm.get_fn("vm_generic_const_variants::three", &[])?;
4551        assert_eq!(compiled.ret_ty(), &Type::I32);
4552        let three: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4553        assert_eq!(three(), 3);
4554        Ok(())
4555    }
4556
4557    #[test]
4558    fn generic_function_body_resolves_private_generic_helper_after_import() -> anyhow::Result<()> {
4559        let vm = Vm::with_all()?;
4560        vm.import_code(
4561            "vm_generic_private_helper",
4562            br#"
4563            fn helper<N>() {
4564                N
4565            }
4566
4567            pub fn bench<N>() {
4568                helper::<N>()
4569            }
4570            "#
4571            .to_vec(),
4572        )?;
4573
4574        let compiled = vm.get_fn_with_params("vm_generic_private_helper::bench", &[], &[Type::ConstInt(7)])?;
4575        assert_eq!(compiled.ret_ty(), &Type::I32);
4576        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4577        assert_eq!(run(), 7);
4578        Ok(())
4579    }
4580
4581    #[test]
4582    fn const_generic_repeat_array_initializes_all_items() -> anyhow::Result<()> {
4583        let vm = Vm::with_all()?;
4584        vm.import_code(
4585            "vm_generic_repeat_array",
4586            br#"
4587            fn bench<N>() {
4588                let is_prime = [true; N];
4589                is_prime[0] = false;
4590                is_prime[1] = false;
4591                let count = 0i64;
4592                for p in 2i64..N {
4593                    if is_prime[p] == true {
4594                        count = count + 1;
4595                        let step = p;
4596                        let j = p * p;
4597                        while j < N {
4598                            is_prime[j] = false;
4599                            j = j + step;
4600                        }
4601                    }
4602                }
4603                count
4604            }
4605
4606            pub fn run() {
4607                bench::<10>()
4608            }
4609
4610            pub fn run_1000() {
4611                bench::<1000>()
4612            }
4613
4614            pub fn run_100000() {
4615                bench::<100000>()
4616            }
4617            "#
4618            .to_vec(),
4619        )?;
4620
4621        let compiled = vm.get_fn("vm_generic_repeat_array::run", &[])?;
4622        assert_eq!(compiled.ret_ty(), &Type::I64);
4623        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4624        assert_eq!(run(), 4);
4625
4626        let compiled = vm.get_fn("vm_generic_repeat_array::run_1000", &[])?;
4627        assert_eq!(compiled.ret_ty(), &Type::I64);
4628        let run_1000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4629        assert_eq!(run_1000(), 168);
4630
4631        let compiled = vm.get_fn("vm_generic_repeat_array::run_100000", &[])?;
4632        assert_eq!(compiled.ret_ty(), &Type::I64);
4633        let run_100000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4634        assert_eq!(run_100000(), 9592);
4635        Ok(())
4636    }
4637
4638    #[test]
4639    fn repeat_array_initializes_scalar_patterns() -> anyhow::Result<()> {
4640        let vm = Vm::with_all()?;
4641        vm.import_code(
4642            "vm_repeat_scalar_patterns",
4643            br#"
4644            pub fn count_true() {
4645                let items = [true; 100000];
4646                let count = 0i64;
4647                for idx in 0i64..100000 {
4648                    if items[idx] == true {
4649                        count = count + 1;
4650                    }
4651                }
4652                count
4653            }
4654
4655            pub fn i32_pair() {
4656                let items = [-7i32; 1000];
4657                items[0i64] + items[999i64]
4658            }
4659
4660            pub fn i64_pair() {
4661                let items = [1234567890123i64; 1000];
4662                items[0i64] + items[999i64]
4663            }
4664
4665            pub fn f64_pair() {
4666                let items = [1.5f64; 1000];
4667                items[0i64] + items[999i64]
4668            }
4669            "#
4670            .to_vec(),
4671        )?;
4672
4673        let compiled = vm.get_fn("vm_repeat_scalar_patterns::count_true", &[])?;
4674        assert_eq!(compiled.ret_ty(), &Type::I64);
4675        let count_true: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4676        assert_eq!(count_true(), 100000);
4677
4678        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i32_pair", &[])?;
4679        assert_eq!(compiled.ret_ty(), &Type::I32);
4680        let i32_pair: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4681        assert_eq!(i32_pair(), -14);
4682
4683        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i64_pair", &[])?;
4684        assert_eq!(compiled.ret_ty(), &Type::I64);
4685        let i64_pair: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4686        assert_eq!(i64_pair(), 2469135780246);
4687
4688        let compiled = vm.get_fn("vm_repeat_scalar_patterns::f64_pair", &[])?;
4689        assert_eq!(compiled.ret_ty(), &Type::F64);
4690        let f64_pair: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
4691        assert_eq!(f64_pair(), 3.0);
4692        Ok(())
4693    }
4694
4695    #[test]
4696    fn bool_array_store_normalizes_condition_values() -> anyhow::Result<()> {
4697        let vm = Vm::with_all()?;
4698        vm.import_code(
4699            "vm_bool_array_store",
4700            br#"
4701            pub fn run() {
4702                let items = [false; 4];
4703                items[1] = 3i64 > 2i64;
4704                items[2] = 3i64 < 2i64;
4705                if items[1] == true && items[2] == false {
4706                    1i64
4707                } else {
4708                    0i64
4709                }
4710            }
4711            "#
4712            .to_vec(),
4713        )?;
4714
4715        let compiled = vm.get_fn("vm_bool_array_store::run", &[])?;
4716        assert_eq!(compiled.ret_ty(), &Type::I64);
4717        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4718        assert_eq!(run(), 1);
4719        Ok(())
4720    }
4721
4722    #[test]
4723    fn bool_array_large_sequential_writes() -> anyhow::Result<()> {
4724        let vm = Vm::with_all()?;
4725        vm.import_code(
4726            "vm_bool_array_large_writes",
4727            br#"
4728            pub fn run() {
4729                let items = [true; 100000];
4730                for idx in 0i64..100000 {
4731                    items[idx] = false;
4732                }
4733                let count = 0i64;
4734                for idx in 0i64..100000 {
4735                    if items[idx] == false {
4736                        count = count + 1;
4737                    }
4738                }
4739                count
4740            }
4741            "#
4742            .to_vec(),
4743        )?;
4744
4745        let compiled = vm.get_fn("vm_bool_array_large_writes::run", &[])?;
4746        assert_eq!(compiled.ret_ty(), &Type::I64);
4747        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4748        assert_eq!(run(), 100000);
4749        Ok(())
4750    }
4751
4752    #[test]
4753    fn bool_array_sieve_style_indices_stay_in_bounds() -> anyhow::Result<()> {
4754        let vm = Vm::with_all()?;
4755        vm.import_code(
4756            "vm_bool_array_sieve_indices",
4757            br#"
4758            pub fn run() {
4759                let items = [true; 100000];
4760                let writes = 0i64;
4761                for p in 2i64..100000 {
4762                    let step = p;
4763                    let j = p * p;
4764                    while j < 100000 {
4765                        items[j] = false;
4766                        writes = writes + 1;
4767                        j = j + step;
4768                    }
4769                }
4770                writes
4771            }
4772            "#
4773            .to_vec(),
4774        )?;
4775
4776        let compiled = vm.get_fn("vm_bool_array_sieve_indices::run", &[])?;
4777        assert_eq!(compiled.ret_ty(), &Type::I64);
4778        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4779        assert!(run() > 0);
4780        Ok(())
4781    }
4782
4783    #[test]
4784    fn sieve_style_indices_compute_in_bounds_without_array_write() -> anyhow::Result<()> {
4785        let vm = Vm::with_all()?;
4786        vm.import_code(
4787            "vm_sieve_indices_no_write",
4788            br#"
4789            pub fn run() {
4790                let max_j = 0i64;
4791                for p in 2i64..100000 {
4792                    let step = p;
4793                    let j = p * p;
4794                    while j < 100000 {
4795                        if j < 0i64 {
4796                            return -1i64;
4797                        }
4798                        if j > max_j {
4799                            max_j = j;
4800                        }
4801                        j = j + step;
4802                    }
4803                }
4804                max_j
4805            }
4806            "#
4807            .to_vec(),
4808        )?;
4809
4810        let compiled = vm.get_fn("vm_sieve_indices_no_write::run", &[])?;
4811        assert_eq!(compiled.ret_ty(), &Type::I64);
4812        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4813        assert_eq!(run(), 99999);
4814        Ok(())
4815    }
4816
4817    #[test]
4818    fn dynamic_list_index_sum_uses_static_accumulator_type() -> anyhow::Result<()> {
4819        let vm = Vm::with_all()?;
4820        vm.import_code(
4821            "vm_dynamic_index_sum",
4822            br#"
4823            pub fn sum_list(n: i64) {
4824                let l = [];
4825                for i in 0..n {
4826                    l.push(i);
4827                }
4828                let sum = 0i64;
4829                for j in 0..n {
4830                    sum = sum + l[j];
4831                }
4832                sum
4833            }
4834            "#
4835            .to_vec(),
4836        )?;
4837
4838        let compiled = vm.get_fn("vm_dynamic_index_sum::sum_list", &[Type::I64])?;
4839        let sum_list_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_dynamic_index_sum::sum_list")?;
4840        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_list_id, &[], &[Type::I64]);
4841        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I64)), "local type hints: {:?}", hints);
4842        assert_eq!(compiled.ret_ty(), &Type::I64);
4843        let sum_list: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4844        assert_eq!(sum_list(1000), 499500);
4845        Ok(())
4846    }
4847
4848    #[test]
4849    fn loop_pushed_list_is_typed_vector() -> anyhow::Result<()> {
4850        let vm = Vm::with_all()?;
4851        vm.import_code(
4852            "vm_loop_pushed_list",
4853            br#"
4854            pub fn make(n: i64) {
4855                let l = [];
4856                for i in 0..n {
4857                    l.push(i);
4858                }
4859                l
4860            }
4861            "#
4862            .to_vec(),
4863        )?;
4864        let compiled = vm.get_fn("vm_loop_pushed_list::make", &[Type::I64])?;
4865        let make: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4866        let result = unsafe { &*make(3) };
4867        assert!(matches!(result, Dynamic::VecI64(v) if v == &vec![0, 1, 2]), "expected flat VecI64, got: {:?}", result);
4868        Ok(())
4869    }
4870
4871    #[test]
4872    fn inferred_empty_list_uses_typed_dynamic_vector() -> anyhow::Result<()> {
4873        let vm = Vm::with_all()?;
4874        vm.import_code(
4875            "vm_inferred_typed_list",
4876            br#"
4877            pub fn make() {
4878                let l = [];
4879                l.push(1i64);
4880                l
4881            }
4882            "#
4883            .to_vec(),
4884        )?;
4885
4886        let compiled = vm.get_fn("vm_inferred_typed_list::make", &[])?;
4887        assert_eq!(compiled.ret_ty(), &Type::Any);
4888        let make: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4889        let result = unsafe { &*make() };
4890        assert!(matches!(result, Dynamic::VecI64(values) if values == &vec![1]), "result: {:?}", result);
4891        Ok(())
4892    }
4893
4894    #[test]
4895    fn for_in_iterates_list_filled_in_same_function() -> anyhow::Result<()> {
4896        let vm = Vm::with_all()?;
4897        vm.import_code(
4898            "vm_for_in_local_pushed_list",
4899            br#"
4900            pub fn sum_i32_items() {
4901                let items = [];
4902                items.push(6000i32);
4903                items.push(4000i32);
4904                let total = 0i32;
4905                for item in items {
4906                    total += item;
4907                }
4908                total
4909            }
4910
4911            pub fn sum_split_bps() {
4912                let splits = [];
4913                splits.push({ bps: "6000" });
4914                splits.push({ bps: 4000 });
4915                let total = 0i32;
4916                let count = 0i32;
4917                for split in splits {
4918                    total += split.bps as i32;
4919                    count += 1i32;
4920                }
4921                total + count
4922            }
4923            "#
4924            .to_vec(),
4925        )?;
4926
4927        let compiled = vm.get_fn("vm_for_in_local_pushed_list::sum_i32_items", &[])?;
4928        assert_eq!(compiled.ret_ty(), &Type::I32);
4929        let sum_i32_items: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4930        assert_eq!(sum_i32_items(), 10000);
4931
4932        let compiled = vm.get_fn("vm_for_in_local_pushed_list::sum_split_bps", &[])?;
4933        assert_eq!(compiled.ret_ty(), &Type::I32);
4934        let sum_split_bps: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
4935        assert_eq!(sum_split_bps(), 10002);
4936        Ok(())
4937    }
4938
4939    #[test]
4940    fn inferred_list_shortcuts_cover_scalar_types() -> anyhow::Result<()> {
4941        let vm = Vm::with_all()?;
4942        vm.import_code(
4943            "vm_inferred_list_shortcuts",
4944            br#"
4945            pub fn second_bool() {
4946                let l = [];
4947                l.push(true);
4948                l.push(false);
4949                l[1]
4950            }
4951
4952            pub fn first_u8() {
4953                let l = [];
4954                l.push(7u8);
4955                l[0]
4956            }
4957
4958            pub fn sum_u8_for_in() {
4959                let l = [];
4960                l.push(7u8);
4961                l.push(8u8);
4962                let sum = 0i64;
4963                for item in l {
4964                    sum = sum + item as i64;
4965                }
4966                sum
4967            }
4968
4969            pub fn count_bool_for_in() {
4970                let l = [];
4971                l.push(true);
4972                l.push(false);
4973                l.push(true);
4974                let count = 0i64;
4975                for item in l {
4976                    if item {
4977                        count += 1i64;
4978                    }
4979                }
4980                count
4981            }
4982
4983            pub fn sum_i32(n: i64) {
4984                let l = [];
4985                for i in 0..n {
4986                    l.push(i as i32);
4987                }
4988                let sum = 0i32;
4989                for j in 0..n {
4990                    sum = sum + l[j];
4991                }
4992                sum
4993            }
4994
4995            pub fn sum_f32(n: i64) {
4996                let l = [];
4997                for i in 0..n {
4998                    l.push(i as f32);
4999                }
5000                let sum = 0f32;
5001                for j in 0..n {
5002                    sum = sum + l[j];
5003                }
5004                sum
5005            }
5006
5007            pub fn second_str() {
5008                let l = [];
5009                l.push("first");
5010                l.push("second");
5011                l[1]
5012            }
5013            "#
5014            .to_vec(),
5015        )?;
5016
5017        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_bool", &[])?;
5018        let second_bool_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::second_bool")?;
5019        let hints = vm.jit.write().compiler.inferred_local_type_hints(second_bool_id, &[], &[]);
5020        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Bool)), "bool local type hints: {:?}", hints);
5021        assert_eq!(compiled.ret_ty(), &Type::Bool);
5022        let second_bool: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5023        assert!(!second_bool());
5024
5025        let compiled = vm.get_fn("vm_inferred_list_shortcuts::first_u8", &[])?;
5026        let first_u8_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::first_u8")?;
5027        let hints = vm.jit.write().compiler.inferred_local_type_hints(first_u8_id, &[], &[]);
5028        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::U8)), "u8 local type hints: {:?}", hints);
5029        assert_eq!(compiled.ret_ty(), &Type::U8);
5030        let first_u8: extern "C" fn() -> u8 = unsafe { std::mem::transmute(compiled.ptr()) };
5031        assert_eq!(first_u8(), 7);
5032
5033        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_u8_for_in", &[])?;
5034        assert_eq!(compiled.ret_ty(), &Type::I64);
5035        let sum_u8_for_in: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5036        assert_eq!(sum_u8_for_in(), 15);
5037
5038        let compiled = vm.get_fn("vm_inferred_list_shortcuts::count_bool_for_in", &[])?;
5039        assert_eq!(compiled.ret_ty(), &Type::I64);
5040        let count_bool_for_in: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5041        assert_eq!(count_bool_for_in(), 2);
5042
5043        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_i32", &[Type::I64])?;
5044        let sum_i32_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::sum_i32")?;
5045        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_i32_id, &[], &[Type::I64]);
5046        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I32)), "i32 local type hints: {:?}", hints);
5047        assert_eq!(compiled.ret_ty(), &Type::I32);
5048        let sum_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5049        assert_eq!(sum_i32(100), 4950);
5050
5051        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_f32", &[Type::I64])?;
5052        let sum_f32_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::sum_f32")?;
5053        let hints = vm.jit.write().compiler.inferred_local_type_hints(sum_f32_id, &[], &[Type::I64]);
5054        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::F32)), "f32 local type hints: {:?}", hints);
5055        assert_eq!(compiled.ret_ty(), &Type::F32);
5056        let sum_f32: extern "C" fn(i64) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
5057        assert_eq!(sum_f32(10), 45.0);
5058
5059        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_str", &[])?;
5060        let second_str_id = vm.jit.write().compiler.sym_tab.symbols.get_id("vm_inferred_list_shortcuts::second_str")?;
5061        let hints = vm.jit.write().compiler.inferred_local_type_hints(second_str_id, &[], &[]);
5062        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Str)), "str local type hints: {:?}", hints);
5063        assert_eq!(compiled.ret_ty(), &Type::Str);
5064        let second_str: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5065        let result = unsafe { &*second_str() };
5066        assert_eq!(result.as_str(), "second");
5067        Ok(())
5068    }
5069
5070    #[test]
5071    fn inferred_list_supports_bracket_set_idx() -> anyhow::Result<()> {
5072        let vm = Vm::with_all()?;
5073        vm.import_code(
5074            "vm_inferred_list_set_idx",
5075            br#"
5076            pub fn swap_first_two() {
5077                let items = [];
5078                items.push(1i64);
5079                items.push(2i64);
5080                let j = 0i64;
5081                let a = items[j];
5082                let b = items[j + 1];
5083                items[j] = b;
5084                items[j + 1] = a;
5085                items[0] * 10i64 + items[1]
5086            }
5087
5088            pub fn replace_string() {
5089                let items = [];
5090                items.push("old");
5091                items[0] = "new";
5092                items[0]
5093            }
5094            "#
5095            .to_vec(),
5096        )?;
5097
5098        let compiled = vm.get_fn("vm_inferred_list_set_idx::swap_first_two", &[])?;
5099        assert_eq!(compiled.ret_ty(), &Type::I64);
5100        let swap_first_two: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5101        assert_eq!(swap_first_two(), 21);
5102
5103        let compiled = vm.get_fn("vm_inferred_list_set_idx::replace_string", &[])?;
5104        assert_eq!(compiled.ret_ty(), &Type::Str);
5105        let replace_string: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5106        let result = unsafe { &*replace_string() };
5107        assert_eq!(result.as_str(), "new");
5108        Ok(())
5109    }
5110
5111    #[test]
5112    fn root_get_returns_null_for_missing_key_which_compares_correctly() -> anyhow::Result<()> {
5113        let vm = Vm::with_all()?;
5114        vm.import_code(
5115            "vm_root_get_missing",
5116            br#"
5117            pub fn check_missing() {
5118                let existing = root::get("local/vm_root_get_missing_test");
5119                if existing.is_map() {
5120                    return false;
5121                }
5122                true
5123            }
5124            "#
5125            .to_vec(),
5126        )?;
5127
5128        let compiled = vm.get_fn("vm_root_get_missing::check_missing", &[])?;
5129        assert_eq!(compiled.ret_ty(), &Type::Bool);
5130        let check_missing: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5131        assert!(check_missing());
5132        Ok(())
5133    }
5134
5135    #[test]
5136    fn map_get_key_on_null_map_returns_null() -> anyhow::Result<()> {
5137        let vm = Vm::with_all()?;
5138        vm.import_code(
5139            "vm_get_key_null_map",
5140            br#"
5141            pub fn get_key_null(data) {
5142                data.get_key("missing")
5143            }
5144            "#
5145            .to_vec(),
5146        )?;
5147
5148        let compiled = vm.get_fn("vm_get_key_null_map::get_key_null", &[Type::Any])?;
5149        assert_eq!(compiled.ret_ty(), &Type::Any);
5150        let get_key_null: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5151
5152        let data_map = dynamic::map!("exists"=> 1i64);
5153        let missing = unsafe { &*get_key_null(&data_map) };
5154        assert!(missing.is_null());
5155
5156        let null = Dynamic::Null;
5157        let result = unsafe { &*get_key_null(&null) };
5158        assert!(result.is_null());
5159        Ok(())
5160    }
5161
5162    #[test]
5163    fn keys_on_empty_map_returns_empty_list() -> anyhow::Result<()> {
5164        let vm = Vm::with_all()?;
5165        vm.import_code(
5166            "vm_keys_empty_map",
5167            br#"
5168            pub fn empty_map_keys() {
5169                let data = {};
5170                data.keys().len()
5171            }
5172            "#
5173            .to_vec(),
5174        )?;
5175
5176        let compiled = vm.get_fn("vm_keys_empty_map::empty_map_keys", &[])?;
5177        assert_eq!(compiled.ret_ty(), &Type::I32);
5178        let empty_map_keys: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5179        assert_eq!(empty_map_keys(), 0);
5180        Ok(())
5181    }
5182
5183    #[test]
5184    fn cast_between_all_integer_widths() -> anyhow::Result<()> {
5185        let vm = Vm::with_all()?;
5186        vm.import_code(
5187            "vm_cast_integer_widths",
5188            br#"
5189            pub fn i64_to_i32(value: i64) {
5190                value as i32
5191            }
5192
5193            pub fn i32_to_i64(value: i32) {
5194                value as i64
5195            }
5196
5197            pub fn u32_to_i64(value: u32) {
5198                value as i64
5199            }
5200            "#
5201            .to_vec(),
5202        )?;
5203
5204        let compiled = vm.get_fn("vm_cast_integer_widths::i64_to_i32", &[Type::I64])?;
5205        assert_eq!(compiled.ret_ty(), &Type::I32);
5206        let i64_to_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
5207        assert_eq!(i64_to_i32(42), 42);
5208
5209        let compiled = vm.get_fn("vm_cast_integer_widths::i32_to_i64", &[Type::I32])?;
5210        assert_eq!(compiled.ret_ty(), &Type::I64);
5211        let i32_to_i64: extern "C" fn(i32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5212        assert_eq!(i32_to_i64(-1), -1);
5213
5214        let compiled = vm.get_fn("vm_cast_integer_widths::u32_to_i64", &[Type::U32])?;
5215        assert_eq!(compiled.ret_ty(), &Type::I64);
5216        let u32_to_i64: extern "C" fn(u32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5217        assert_eq!(u32_to_i64(42), 42);
5218        Ok(())
5219    }
5220
5221    #[test]
5222    fn boolean_literals_in_complex_expression_trees() -> anyhow::Result<()> {
5223        let vm = Vm::with_all()?;
5224        vm.import_code(
5225            "vm_complex_boolean",
5226            br#"
5227            pub fn exclusive_or(a: bool, b: bool) {
5228                (a && !b) || (!a && b)
5229            }
5230
5231            pub fn implies(a: bool, b: bool) {
5232                !a || b
5233            }
5234            "#
5235            .to_vec(),
5236        )?;
5237
5238        let compiled = vm.get_fn("vm_complex_boolean::exclusive_or", &[Type::Bool, Type::Bool])?;
5239        assert_eq!(compiled.ret_ty(), &Type::Bool);
5240        let exclusive_or: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5241        assert!(exclusive_or(true, false));
5242        assert!(exclusive_or(false, true));
5243        assert!(!exclusive_or(true, true));
5244        assert!(!exclusive_or(false, false));
5245
5246        let compiled = vm.get_fn("vm_complex_boolean::implies", &[Type::Bool, Type::Bool])?;
5247        assert_eq!(compiled.ret_ty(), &Type::Bool);
5248        let implies: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5249        assert!(implies(false, true));
5250        assert!(implies(false, false));
5251        assert!(implies(true, true));
5252        assert!(!implies(true, false));
5253        Ok(())
5254    }
5255
5256    #[test]
5257    fn concrete_struct_method_returning_self_type() -> anyhow::Result<()> {
5258        let vm = Vm::with_all()?;
5259        vm.import_code(
5260            "vm_struct_method_self",
5261            br#"
5262            pub struct Vec3 {
5263                x: f64,
5264                y: f64,
5265                z: f64,
5266            }
5267
5268            impl Vec3 {
5269                pub fn add(self: Vec3, other: Vec3) {
5270                    Vec3{x: self.x + other.x, y: self.y + other.y, z: self.z + other.z}
5271                }
5272            }
5273
5274            pub fn run() {
5275                let v1 = Vec3{x: 1.0f64, y: 2.0f64, z: 3.0f64};
5276                let v2 = Vec3{x: 4.0f64, y: 5.0f64, z: 6.0f64};
5277                let sum = v1.add(v2);
5278                sum.x + sum.y + sum.z
5279            }
5280            "#
5281            .to_vec(),
5282        )?;
5283
5284        let compiled = vm.get_fn("vm_struct_method_self::run", &[])?;
5285        assert_eq!(compiled.ret_ty(), &Type::F64);
5286        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
5287        assert_eq!(run(), 21.0);
5288        Ok(())
5289    }
5290
5291    #[test]
5292    fn deep_nested_struct_access_with_multiple_field_levels() -> anyhow::Result<()> {
5293        let vm = Vm::with_all()?;
5294        vm.import_code(
5295            "vm_deep_nested_struct",
5296            br#"
5297            pub struct A {
5298                value: i64,
5299            }
5300
5301            pub struct B {
5302                a: A,
5303            }
5304
5305            pub struct C {
5306                b: B,
5307            }
5308
5309            pub fn direct_access() {
5310                let c = C{b: B{a: A{value: 99}}};
5311                c.b.a.value
5312            }
5313
5314            pub fn via_variable() {
5315                let c = C{b: B{a: A{value: 77}}};
5316                let b = c.b;
5317                let a = b.a;
5318                a.value
5319            }
5320            "#
5321            .to_vec(),
5322        )?;
5323
5324        let compiled = vm.get_fn("vm_deep_nested_struct::direct_access", &[])?;
5325        assert_eq!(compiled.ret_ty(), &Type::I64);
5326        let direct_access: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5327        assert_eq!(direct_access(), 99);
5328
5329        let compiled = vm.get_fn("vm_deep_nested_struct::via_variable", &[])?;
5330        assert_eq!(compiled.ret_ty(), &Type::I64);
5331        let via_variable: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5332        assert_eq!(via_variable(), 77);
5333        Ok(())
5334    }
5335
5336    #[test]
5337    fn array_index_with_dynamic_value_via_method() -> anyhow::Result<()> {
5338        let vm = Vm::with_all()?;
5339        vm.import_code(
5340            "vm_array_idx_dynamic",
5341            br#"
5342            pub fn get_by_idx(list, idx) {
5343                list.get_idx(idx)
5344            }
5345            "#
5346            .to_vec(),
5347        )?;
5348
5349        let compiled = vm.get_fn("vm_array_idx_dynamic::get_by_idx", &[Type::Any, Type::I64])?;
5350        assert_eq!(compiled.ret_ty(), &Type::Any);
5351        let get_by_idx: extern "C" fn(*const Dynamic, i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5352
5353        let list = Dynamic::list(vec!["a".into(), "b".into()]);
5354        let first = unsafe { &*get_by_idx(&list, 0) };
5355        assert_eq!(first.as_str(), "a");
5356
5357        let out = unsafe { &*get_by_idx(&list, 10) };
5358        assert!(out.is_null());
5359        Ok(())
5360    }
5361
5362    #[test]
5363    fn dynamic_field_access_with_optional_or_fallback() -> anyhow::Result<()> {
5364        let vm = Vm::with_all()?;
5365        vm.import_code(
5366            "vm_dynamic_or_fallback",
5367            br#"
5368            pub fn with_fallback(data) {
5369                if data.contains("name") { data.name } else { "unknown" }
5370            }
5371
5372            pub fn with_fallback_missing(data) {
5373                if data.contains("nickname") { data.nickname } else { "unnamed" }
5374            }
5375            "#
5376            .to_vec(),
5377        )?;
5378
5379        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback", &[Type::Any])?;
5380        assert_eq!(compiled.ret_ty(), &Type::Any);
5381        let with_fallback: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5382        let data = dynamic::map!("name"=> "Alice");
5383        let result = unsafe { &*with_fallback(&data) };
5384        assert_eq!(result.as_str(), "Alice");
5385
5386        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback_missing", &[Type::Any])?;
5387        let with_fallback_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
5388        let result = unsafe { &*with_fallback_missing(&data) };
5389        assert_eq!(result.as_str(), "unnamed");
5390        Ok(())
5391    }
5392
5393    #[test]
5394    fn for_in_loop_iterates_over_list_and_map_directly() -> anyhow::Result<()> {
5395        let vm = Vm::with_all()?;
5396        vm.import_code(
5397            "vm_for_in_collection",
5398            br#"
5399            pub fn sum_list(items) {
5400                let total = 0i64;
5401                for item in items {
5402                    total = total + 1;
5403                }
5404                total
5405            }
5406
5407            pub fn count_map_keys(data) {
5408                let count = 0i64;
5409                for key in data.keys() {
5410                    count = count + 1;
5411                }
5412                count
5413            }
5414
5415            pub fn for_in_list_works(items) {
5416                let exists = false;
5417                for item in items {
5418                    exists = true;
5419                }
5420                exists
5421            }
5422
5423            pub fn for_in_map_values_works(data) {
5424                let exists = false;
5425                for value in data {
5426                    exists = true;
5427                }
5428                exists
5429            }
5430            "#
5431            .to_vec(),
5432        )?;
5433
5434        let compiled = vm.get_fn("vm_for_in_collection::sum_list", &[Type::Any])?;
5435        assert_eq!(compiled.ret_ty(), &Type::I64);
5436        let sum_list: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5437        let items = Dynamic::list(vec![Dynamic::from(1i64), Dynamic::from(2i64), Dynamic::from(3i64)]);
5438        assert_eq!(sum_list(&items), 3);
5439
5440        let data = dynamic::map!("x"=> 1i64, "y"=> 2i64);
5441        let compiled = vm.get_fn("vm_for_in_collection::count_map_keys", &[Type::Any])?;
5442        assert_eq!(compiled.ret_ty(), &Type::I64);
5443        let count_map_keys: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
5444        assert_eq!(count_map_keys(&data), 2);
5445
5446        let compiled = vm.get_fn("vm_for_in_collection::for_in_list_works", &[Type::Any])?;
5447        assert_eq!(compiled.ret_ty(), &Type::Bool);
5448        let for_in_list_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5449        let empty = Dynamic::list(Vec::new());
5450        assert!(!for_in_list_works(&empty));
5451        assert!(for_in_list_works(&items));
5452
5453        let compiled = vm.get_fn("vm_for_in_collection::for_in_map_values_works", &[Type::Any])?;
5454        assert_eq!(compiled.ret_ty(), &Type::Bool);
5455        let for_in_map_values_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
5456        let empty_map = dynamic::map!();
5457        assert!(!for_in_map_values_works(&empty_map));
5458        assert!(for_in_map_values_works(&data));
5459
5460        Ok(())
5461    }
5462
5463    #[test]
5464    fn concurrent_100_threads_no_memory_leak() -> anyhow::Result<()> {
5465        let vm = Vm::with_all()?;
5466        vm.import_code(
5467            "vm_stress",
5468            br#"
5469            pub fn heavy_alloc(idx: i64) {
5470                let items = [];
5471                let i = 0;
5472                while i < 50 {
5473                    items.push({
5474                        id: i + idx,
5475                        name: "item-" + i,
5476                        tags: ["tag-a", "tag-b", "tag-c"],
5477                        meta: {
5478                            created: 1234567890i64,
5479                            score: (i * 3.14f64) as i64,
5480                            extra: "prefix/" + i + "/" + idx
5481                        }
5482                    });
5483                    i = i + 1;
5484                }
5485                items
5486            }
5487
5488            pub fn string_concat_stress() {
5489                let i = 0;
5490                let result = "";
5491                while i < 200 {
5492                    result = result + "data-" + i + ",";
5493                    i = i + 1;
5494                }
5495                result
5496            }
5497            "#
5498            .to_vec(),
5499        )?;
5500
5501        let (heavy_ptr, _) = vm.get_fn_ptr("vm_stress::heavy_alloc", &[Type::I64])?;
5502        let (concat_ptr, _) = vm.get_fn_ptr("vm_stress::string_concat_stress", &[])?;
5503
5504        let threads: usize = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).max(100);
5505        let iters_per_thread = 200;
5506        let total_calls = threads * iters_per_thread * 2;
5507
5508        let before = current_rss_kb();
5509        eprintln!("threads={threads} iters_per_thread={iters_per_thread} total_calls={total_calls} rss_before={before}KB");
5510
5511        // Round 1: first concurrent execution (arena warm-up)
5512        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5513        let r1 = current_rss_kb();
5514        eprintln!("rss_after_round1={r1}KB");
5515
5516        // Round 2: should stabilize (no unbounded growth)
5517        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5518        let r2 = current_rss_kb();
5519        eprintln!("rss_after_round2={r2}KB");
5520
5521        // Round 3: final check
5522        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5523        let r3 = current_rss_kb();
5524        eprintln!("rss_after_round3={r3}KB");
5525
5526        // Round 4: confirm that any one-time allocator growth has settled.
5527        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
5528        let r4 = current_rss_kb();
5529        eprintln!("rss_after_round4={r4}KB");
5530
5531        // Allocator/arena growth is allowed during warm-up, but it must settle.
5532        let d12 = r2.saturating_sub(r1);
5533        let d23 = r3.saturating_sub(r2);
5534        let d34 = r4.saturating_sub(r3);
5535        eprintln!("delta_r1→r2={d12}KB delta_r2→r3={d23}KB delta_r3→r4={d34}KB");
5536
5537        // The last interval must be small to prove the growth is not continuing.
5538        let max_growth_kb = 20 * 1024;
5539        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)");
5540
5541        Ok(())
5542    }
5543
5544    fn run_stress_round(threads: usize, iters: usize, heavy_ptr: usize, concat_ptr: usize) {
5545        std::thread::scope(|scope| {
5546            let mut handles = Vec::with_capacity(threads);
5547            for t in 0..threads {
5548                let heavy_ptr = heavy_ptr;
5549                let concat_ptr = concat_ptr;
5550                handles.push(scope.spawn(move || {
5551                    let heavy_fn: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(heavy_ptr as *const u8) };
5552                    let concat_fn: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(concat_ptr as *const u8) };
5553                    for i in 0..iters {
5554                        // heavy_alloc: drop returned value to free heap allocation
5555                        let r_ptr = heavy_fn((t * iters + i) as i64);
5556                        assert!(!r_ptr.is_null());
5557                        unsafe {
5558                            let r = &*r_ptr;
5559                            assert!(r.len() > 0, "heavy_alloc returned empty list");
5560                            drop(Box::from_raw(r_ptr as *mut Dynamic));
5561                        }
5562
5563                        // concat: same, drop returned value
5564                        let s_ptr = concat_fn();
5565                        assert!(!s_ptr.is_null());
5566                        unsafe {
5567                            let s = &*s_ptr;
5568                            assert!(s.len() > 0, "string_concat_stress returned empty");
5569                            drop(Box::from_raw(s_ptr as *mut Dynamic));
5570                        }
5571                    }
5572                }));
5573            }
5574            for h in handles {
5575                h.join().unwrap();
5576            }
5577        });
5578    }
5579
5580    fn current_rss_kb() -> u64 {
5581        // macOS: use ps
5582        let pid = std::process::id();
5583        if let Ok(output) = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "rss="]).output() {
5584            if let Ok(s) = String::from_utf8(output.stdout) {
5585                if let Some(kb) = s.trim().parse::<u64>().ok() {
5586                    return kb;
5587                }
5588            }
5589        }
5590        // Linux fallback: /proc/self/statm
5591        if let Ok(statm) = std::fs::read_to_string("/proc/self/statm") {
5592            let parts: Vec<&str> = statm.split_whitespace().collect();
5593            if let Some(rss_pages) = parts.get(1).and_then(|s| s.parse::<u64>().ok()) {
5594                return rss_pages * 4; // pages (4KB) → KB
5595            }
5596        }
5597        0
5598    }
5599}