Skip to main content

vm/
lib.rs

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