Skip to main content

vm/
lib.rs

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