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