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