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::Type;
16pub use rt::JITRunTime;
17use smol_str::SmolStr;
18mod db_module;
19mod gpu_layout;
20mod gpu_module;
21mod http_module;
22mod llm_module;
23mod oss_module;
24mod root_module;
25pub use gpu_layout::{GpuFieldLayout, GpuStructLayout};
26
27use std::sync::{Mutex, OnceLock, Weak};
28static PTR_TYPE: OnceLock<types::Type> = OnceLock::new();
29pub fn ptr_type() -> types::Type {
30    PTR_TYPE.get().cloned().unwrap()
31}
32
33pub fn get_type(ty: &Type) -> Result<types::Type> {
34    if ty.is_f64() {
35        Ok(types::F64)
36    } else if ty.is_f32() {
37        Ok(types::F32)
38    } else if ty.is_int() | ty.is_uint() {
39        match ty.width() {
40            1 => Ok(types::I8),
41            2 => Ok(types::I16),
42            4 => Ok(types::I32),
43            8 => Ok(types::I64),
44            _ => Err(anyhow!("非法类型 {:?}", ty)),
45        }
46    } else if let Type::Bool = ty {
47        Ok(types::I8)
48    } else {
49        Ok(ptr_type())
50    }
51}
52
53use compiler::Symbol;
54use cranelift::prelude::*;
55use cranelift_module::Module;
56
57pub fn init_jit(mut jit: JITRunTime) -> Result<JITRunTime> {
58    jit.add_all()?;
59    Ok(jit)
60}
61
62use std::sync::Arc;
63unsafe impl Send for JITRunTime {}
64unsafe impl Sync for JITRunTime {}
65
66pub(crate) fn with_vm_context<T>(context: *const Weak<Mutex<JITRunTime>>, f: impl FnOnce(&Vm) -> Result<T>) -> Result<T> {
67    if context.is_null() {
68        return Err(anyhow!("VM context is null"));
69    }
70    let jit = unsafe { &*context }.upgrade().ok_or_else(|| anyhow!("VM context has expired"))?;
71    let vm = Vm { jit };
72    f(&vm)
73}
74
75fn add_method_field(jit: &mut JITRunTime, def: &str, method: &str, id: u32) -> Result<()> {
76    let def_id = jit.get_id(def)?;
77    if let Some((_, define)) = jit.compiler.symbols.get_symbol_mut(def_id) {
78        if let Symbol::Struct(Type::Struct { params, fields }, _) = define {
79            fields.push((method.into(), Type::Symbol { id, params: params.clone() }));
80        }
81    }
82    Ok(())
83}
84
85fn add_native_module_fns(jit: &mut JITRunTime, module: &str, fns: &[(&str, &[Type], Type, *const u8)]) -> Result<()> {
86    jit.add_module(module);
87    for (name, arg_tys, ret_ty, fn_ptr) in fns {
88        let full_name = format!("{}::{}", module, name);
89        jit.add_native_ptr(&full_name, name, arg_tys, ret_ty.clone(), *fn_ptr)?;
90    }
91    jit.pop_module();
92    Ok(())
93}
94
95impl JITRunTime {
96    fn add_memory_runtime(&mut self) -> Result<()> {
97        self.native_symbols.write().unwrap().insert("__vm_scope_enter".to_string(), memory::scope_enter as *const () as usize);
98        self.native_symbols.write().unwrap().insert("__vm_scope_exit_void".to_string(), memory::scope_exit_void as *const () as usize);
99        self.native_symbols.write().unwrap().insert("__vm_scope_exit_dynamic".to_string(), memory::scope_exit_dynamic as *const () as usize);
100        self.native_symbols.write().unwrap().insert("__vm_scope_exit_bytes".to_string(), memory::scope_exit_bytes as *const () as usize);
101        self.native_symbols.write().unwrap().insert("__vm_struct_alloc".to_string(), native::struct_alloc as *const () as usize);
102        self.native_symbols.write().unwrap().insert("__vm_repeat_fill".to_string(), native::repeat_fill as *const () as usize);
103        self.native_symbols.write().unwrap().insert("__vm_strcat".to_string(), native::strcat as *const () as usize);
104        self.native_symbols.write().unwrap().insert("__vm_strcat_i64".to_string(), native::strcat_i64 as *const () as usize);
105        self.native_symbols.write().unwrap().insert("__vm_strcat_assign".to_string(), native::strcat_assign as *const () as usize);
106        self.native_symbols.write().unwrap().insert("__vm_callback_new".to_string(), native::callback_new as *const () as usize);
107        self.native_symbols.write().unwrap().insert("__vm_spawn_ptr".to_string(), native::spawn_ptr as *const () as usize);
108        self.native_symbols.write().unwrap().insert("__vm_struct_from_ptr".to_string(), native::struct_from_ptr as *const () as usize);
109        self.native_symbols.write().unwrap().insert("__vm_array_from_ptr".to_string(), native::array_from_ptr as *const () as usize);
110        self.native_symbols.write().unwrap().insert("__vm_array_to_ptr".to_string(), native::array_to_ptr as *const () as usize);
111
112        let void_sig = self.get_sig(&[], Type::Void)?;
113        self.scope_enter_fn = Some(self.module.declare_function("__vm_scope_enter", cranelift_module::Linkage::Import, &void_sig)?);
114        self.scope_exit_void_fn = Some(self.module.declare_function("__vm_scope_exit_void", cranelift_module::Linkage::Import, &void_sig)?);
115
116        let dynamic_sig = self.get_sig(&[Type::Any], Type::Any)?;
117        self.scope_exit_dynamic_fn = Some(self.module.declare_function("__vm_scope_exit_dynamic", cranelift_module::Linkage::Import, &dynamic_sig)?);
118
119        let bytes_sig = self.get_sig(&[Type::Any, Type::I64], Type::Any)?;
120        self.scope_exit_bytes_fn = Some(self.module.declare_function("__vm_scope_exit_bytes", cranelift_module::Linkage::Import, &bytes_sig)?);
121
122        let struct_alloc_sig = self.get_sig(&[Type::I64], Type::Any)?;
123        self.struct_alloc_fn = Some(self.module.declare_function("__vm_struct_alloc", cranelift_module::Linkage::Import, &struct_alloc_sig)?);
124
125        let repeat_fill_sig = self.get_sig(&[Type::Any, Type::I64, Type::I64, Type::I64], Type::Void)?;
126        self.repeat_fill_fn = Some(self.module.declare_function("__vm_repeat_fill", cranelift_module::Linkage::Import, &repeat_fill_sig)?);
127
128        let strcat_sig = self.get_sig(&[Type::Str, Type::Str], Type::Str)?;
129        self.strcat_fn = Some(self.module.declare_function("__vm_strcat", cranelift_module::Linkage::Import, &strcat_sig)?);
130
131        let strcat_i64_sig = self.get_sig(&[Type::Str, Type::I64], Type::Str)?;
132        self.strcat_i64_fn = Some(self.module.declare_function("__vm_strcat_i64", cranelift_module::Linkage::Import, &strcat_i64_sig)?);
133
134        let strcat_assign_sig = self.get_sig(&[Type::Any, Type::Any], Type::Any)?;
135        self.strcat_assign_fn = Some(self.module.declare_function("__vm_strcat_assign", cranelift_module::Linkage::Import, &strcat_assign_sig)?);
136
137        let callback_new_sig = self.get_sig(&[Type::I64, Type::I64, Type::I64, Type::Any], Type::Any)?;
138        self.callback_new_fn = Some(self.module.declare_function("__vm_callback_new", cranelift_module::Linkage::Import, &callback_new_sig)?);
139
140        let spawn_ptr_sig = self.get_sig(&[Type::I64, Type::I64, Type::Any], Type::Bool)?;
141        self.spawn_ptr_fn = Some(self.module.declare_function("__vm_spawn_ptr", cranelift_module::Linkage::Import, &spawn_ptr_sig)?);
142
143        let struct_from_ptr_sig = self.get_sig(&[Type::I64, Type::I64], Type::Any)?;
144        self.struct_from_ptr_fn = Some(self.module.declare_function("__vm_struct_from_ptr", cranelift_module::Linkage::Import, &struct_from_ptr_sig)?);
145        self.array_from_ptr_fn = Some(self.module.declare_function("__vm_array_from_ptr", cranelift_module::Linkage::Import, &struct_from_ptr_sig)?);
146        let array_to_ptr_sig = self.get_sig(&[Type::Any, Type::Any, Type::I64], Type::Void)?;
147        self.array_to_ptr_fn = Some(self.module.declare_function("__vm_array_to_ptr", cranelift_module::Linkage::Import, &array_to_ptr_sig)?);
148        Ok(())
149    }
150
151    pub fn add_module(&mut self, name: &str) {
152        self.compiler.symbols.add_module(name.into());
153    }
154
155    pub fn pop_module(&mut self) {
156        self.compiler.symbols.pop_module();
157    }
158
159    pub fn add_type(&mut self, name: &str, ty: Type, is_pub: bool) -> u32 {
160        self.compiler.add_symbol(name, Symbol::Struct(ty, is_pub))
161    }
162
163    pub fn add_empty_type(&mut self, name: &str) -> Result<u32> {
164        match self.get_id(name) {
165            Ok(id) => Ok(id),
166            Err(_) => Ok(self.add_type(name, Type::Struct { params: Vec::new(), fields: Vec::new() }, true)),
167        }
168    }
169
170    pub fn add_native_module_ptr(&mut self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
171        self.add_module(module);
172        let full_name = format!("{}::{}", module, name);
173        let result = self.add_native_ptr(&full_name, name, arg_tys, ret_ty, fn_ptr);
174        self.pop_module();
175        result
176    }
177
178    pub(crate) fn add_native_module_context_ptr(&mut self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
179        self.add_module(module);
180        let full_name = format!("{}::{}", module, name);
181        let result = self.add_context_native_ptr(&full_name, name, arg_tys, ret_ty, fn_ptr);
182        self.pop_module();
183        result
184    }
185
186    pub fn add_native_method_ptr(&mut self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
187        self.add_empty_type(def)?;
188        let full_name = format!("{}::{}", def, method);
189        let id = self.add_native_ptr(&full_name, &full_name, arg_tys, ret_ty, fn_ptr)?;
190        add_method_field(self, def, method, id)?;
191        Ok(id)
192    }
193
194    pub fn add_std(&mut self) -> Result<()> {
195        if self.compiler.symbols.get_id("std::print").is_ok() {
196            return Ok(());
197        }
198        self.add_module("std");
199        for (name, arg_tys, ret_ty, fn_ptr) in STD {
200            self.add_native_ptr(name, name, arg_tys, ret_ty, fn_ptr)?;
201        }
202        self.add_context_native_ptr("import", "import", &[Type::Any, Type::Any], Type::Bool, native::import_with_vm as *const u8)?;
203        self.add_context_native_ptr("spawn", "spawn", &[Type::Any, Type::Any], Type::Bool, native::spawn_with_vm as *const u8)?;
204        Ok(())
205    }
206
207    pub fn add_any(&mut self) -> Result<()> {
208        if self.compiler.symbols.get_id("Any").is_ok() && self.compiler.symbols.get_id("Any::is_map").is_ok() {
209            return Ok(());
210        }
211        for (name, arg_tys, ret_ty, fn_ptr) in ANY {
212            let (_, method) = name.split_once("::").ok_or_else(|| anyhow!("非法 Any 方法名 {}", name))?;
213            self.add_native_method_ptr("Any", method, arg_tys, ret_ty, fn_ptr)?;
214        }
215        Ok(())
216    }
217
218    pub fn add_vec(&mut self) -> Result<()> {
219        self.add_empty_type("Vec")?;
220        let vec_def = Type::Symbol { id: self.get_id("Vec")?, params: Vec::new() };
221        self.add_inline("Vec::swap", vec![vec_def.clone(), Type::I64, Type::I64], Type::Void, |ctx: Option<&mut BuildContext>, args: Vec<Value>| {
222            if let Some(ctx) = ctx {
223                let width = ctx.builder.ins().iconst(types::I64, 4);
224                let offset_val = ctx.builder.ins().imul(args[1], width); // i * 4 i32大小四字节
225                let final_addr = ctx.builder.ins().iadd(args[0], offset_val); // base + (i*4)
226                let dest = ctx.builder.ins().imul(args[2], width);
227                let dest_addr = ctx.builder.ins().iadd(args[0], dest); // base + (i*4)
228                let dest_val = ctx.builder.ins().load(types::I32, MemFlags::trusted(), dest_addr, 0);
229                let v = ctx.builder.ins().load(types::I32, MemFlags::trusted(), final_addr, 0);
230                ctx.builder.ins().store(MemFlags::trusted(), v, dest_addr, 0);
231                ctx.builder.ins().store(MemFlags::trusted(), dest_val, final_addr, 0);
232            }
233            Err(anyhow!("无返回值"))
234        })?;
235
236        self.add_inline("Vec::get_idx", vec![vec_def.clone(), Type::I64], Type::I32, |ctx: Option<&mut BuildContext>, args: Vec<Value>| {
237            if let Some(ctx) = ctx {
238                let width = ctx.builder.ins().iconst(types::I64, 4);
239                let offset_val = ctx.builder.ins().imul(args[1], width); // i * 4 i32大小四字节
240                let final_addr = ctx.builder.ins().iadd(args[0], offset_val);
241                Ok((Some(ctx.builder.ins().load(types::I32, MemFlags::trusted(), final_addr, 0)), Type::I32))
242            } else {
243                Ok((None, Type::I32))
244            }
245        })?;
246        Ok(())
247    }
248
249    pub fn add_llm(&mut self) -> Result<()> {
250        add_native_module_fns(self, "llm", &llm_module::LLM_NATIVE)
251    }
252
253    pub fn add_root(&mut self) -> Result<()> {
254        add_native_module_fns(self, "root", &root_module::ROOT_NATIVE)?;
255        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)?;
256        Ok(())
257    }
258
259    pub fn add_http(&mut self) -> Result<()> {
260        add_native_module_fns(self, "http", &http_module::HTTP_NATIVE)?;
261        http_module::add_root_handlers()
262    }
263
264    pub fn add_oss(&mut self) -> Result<()> {
265        add_native_module_fns(self, "oss", &oss_module::OSS_NATIVE)
266    }
267
268    pub fn add_db(&mut self) -> Result<()> {
269        add_native_module_fns(self, "db", &db_module::DB_NATIVE)
270    }
271
272    pub fn add_gpu(&mut self) -> Result<()> {
273        add_native_module_fns(self, "gpu", &gpu_module::GPU_NATIVE)
274    }
275
276    pub fn add_all(&mut self) -> Result<()> {
277        self.add_std()?;
278        self.add_any()?;
279        self.add_vec()?;
280        self.add_llm()?;
281        self.add_root()?;
282        self.add_http()?;
283        self.add_oss()?;
284        self.add_db()?;
285        self.add_gpu()?;
286        Ok(())
287    }
288}
289
290#[derive(Clone)]
291pub struct Vm {
292    jit: Arc<Mutex<JITRunTime>>,
293}
294
295#[derive(Clone)]
296pub struct CompiledFn {
297    ptr: usize,
298    ret: Type,
299    owner: Vm,
300}
301
302impl CompiledFn {
303    pub fn ptr(&self) -> *const u8 {
304        self.ptr as *const u8
305    }
306
307    pub fn ret_ty(&self) -> &Type {
308        &self.ret
309    }
310
311    pub fn owner(&self) -> &Vm {
312        &self.owner
313    }
314}
315
316impl Vm {
317    pub fn new() -> Self {
318        dynamic::set_dynamic_return_handler(memory::take_dynamic_return);
319        let jit = Arc::new(Mutex::new(JITRunTime::new(|_| {})));
320        {
321            let mut guard = jit.lock().unwrap();
322            guard.set_owner(Arc::downgrade(&jit));
323            guard.add_memory_runtime().expect("register VM memory runtime");
324            guard.add_std().expect("register VM std runtime");
325            guard.add_any().expect("register VM Any runtime");
326        }
327        Self { jit }
328    }
329
330    pub fn with_all() -> Result<Self> {
331        let vm = Self::new();
332        vm.add_all()?;
333        Ok(vm)
334    }
335
336    pub fn add_module(&self, name: &str) {
337        self.jit.lock().unwrap().add_module(name)
338    }
339
340    pub fn pop_module(&self) {
341        self.jit.lock().unwrap().pop_module()
342    }
343
344    pub fn add_type(&self, name: &str, ty: Type, is_pub: bool) -> u32 {
345        self.jit.lock().unwrap().add_type(name, ty, is_pub)
346    }
347
348    pub fn add_empty_type(&self, name: &str) -> Result<u32> {
349        self.jit.lock().unwrap().add_empty_type(name)
350    }
351
352    pub fn add_std(&self) -> Result<()> {
353        self.jit.lock().unwrap().add_std()
354    }
355
356    pub fn add_any(&self) -> Result<()> {
357        self.jit.lock().unwrap().add_any()
358    }
359
360    pub fn add_vec(&self) -> Result<()> {
361        self.jit.lock().unwrap().add_vec()
362    }
363
364    pub fn add_llm(&self) -> Result<()> {
365        self.jit.lock().unwrap().add_llm()
366    }
367
368    pub fn add_root(&self) -> Result<()> {
369        self.jit.lock().unwrap().add_root()
370    }
371
372    pub fn add_http(&self) -> Result<()> {
373        self.jit.lock().unwrap().add_http()
374    }
375
376    pub fn add_oss(&self) -> Result<()> {
377        self.jit.lock().unwrap().add_oss()
378    }
379
380    pub fn add_db(&self) -> Result<()> {
381        self.jit.lock().unwrap().add_db()
382    }
383
384    pub fn add_gpu(&self) -> Result<()> {
385        self.jit.lock().unwrap().add_gpu()
386    }
387
388    pub fn add_all(&self) -> Result<()> {
389        self.jit.lock().unwrap().add_all()
390    }
391
392    pub fn add_native_ptr(&self, full_name: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
393        self.jit.lock().unwrap().add_native_ptr(full_name, name, arg_tys, ret_ty, fn_ptr)
394    }
395
396    pub fn add_native_module_ptr(&self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
397        self.jit.lock().unwrap().add_native_module_ptr(module, name, arg_tys, ret_ty, fn_ptr)
398    }
399
400    pub fn add_native_method_ptr(&self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
401        self.jit.lock().unwrap().add_native_method_ptr(def, method, arg_tys, ret_ty, fn_ptr)
402    }
403
404    pub fn add_inline(&self, name: &str, args: Vec<Type>, ret: Type, f: fn(Option<&mut BuildContext>, Vec<Value>) -> Result<(Option<Value>, Type)>) -> Result<u32> {
405        self.jit.lock().unwrap().add_inline(name, args, ret, f)
406    }
407
408    pub fn import_code(&self, name: &str, code: Vec<u8>) -> Result<()> {
409        self.jit.lock().unwrap().import_code(name, code)
410    }
411
412    pub fn import_file(&self, name: &str, path: &str) -> Result<()> {
413        self.jit.lock().unwrap().compiler.import_file(name, path)?;
414        Ok(())
415    }
416
417    pub fn import(&self, name: &str, path: &str) -> Result<()> {
418        if root::contains(path) {
419            let code = root::get(path).unwrap();
420            if code.is_str() {
421                self.import_code(name, code.as_str().as_bytes().to_vec())
422            } else {
423                self.import_code(name, code.get_dynamic("code").ok_or(anyhow!("{:?} 没有 code 成员", code))?.as_str().as_bytes().to_vec())
424            }
425        } else {
426            self.import_file(name, path)
427        }
428    }
429
430    pub fn infer(&self, name: &str, arg_tys: &[Type]) -> Result<Type> {
431        self.jit.lock().unwrap().get_type(name, arg_tys)
432    }
433
434    pub fn get_fn_ptr(&self, name: &str, arg_tys: &[Type]) -> Result<(*const u8, Type)> {
435        self.jit.lock().unwrap().get_fn_ptr(name, arg_tys)
436    }
437
438    pub fn get_fn_ptr_with_params(&self, name: &str, arg_tys: &[Type], generic_args: &[Type]) -> Result<(*const u8, Type)> {
439        self.jit.lock().unwrap().get_fn_ptr_with_params(name, arg_tys, generic_args)
440    }
441
442    pub fn get_fn(&self, name: &str, arg_tys: &[Type]) -> Result<CompiledFn> {
443        let (ptr, ret) = self.get_fn_ptr(name, arg_tys)?;
444        Ok(CompiledFn { ptr: ptr as usize, ret, owner: self.clone() })
445    }
446
447    pub fn get_fn_with_params(&self, name: &str, arg_tys: &[Type], generic_args: &[Type]) -> Result<CompiledFn> {
448        let (ptr, ret) = self.get_fn_ptr_with_params(name, arg_tys, generic_args)?;
449        Ok(CompiledFn { ptr: ptr as usize, ret, owner: self.clone() })
450    }
451
452    pub fn load(&self, code: Vec<u8>, arg_name: SmolStr) -> Result<(i64, Type)> {
453        self.jit.lock().unwrap().load(code, arg_name)
454    }
455
456    pub fn get_symbol(&self, name: &str, params: Vec<Type>) -> Result<Type> {
457        Ok(Type::Symbol { id: self.jit.lock().unwrap().get_id(name)?, params })
458    }
459
460    pub fn gpu_struct_layout(&self, name: &str, params: &[Type]) -> Result<GpuStructLayout> {
461        let jit = self.jit.lock().unwrap();
462        GpuStructLayout::from_symbol_table(&jit.compiler.symbols, name, params)
463    }
464
465    pub fn disassemble(&self, name: &str) -> Result<String> {
466        self.jit.lock().unwrap().compiler.symbols.disassemble(name)
467    }
468
469    #[cfg(feature = "ir-disassembly")]
470    pub fn disassemble_ir(&self, name: &str) -> Result<String> {
471        self.jit.lock().unwrap().disassemble_ir(name)
472    }
473}
474
475impl Default for Vm {
476    fn default() -> Self {
477        Self::new()
478    }
479}
480
481#[cfg(test)]
482mod tests {
483    use super::{Vm, ZustCallback};
484    use dynamic::{CustomProperty, Dynamic, ToJson, Type};
485    use std::collections::BTreeMap;
486    use std::sync::{Mutex, RwLock};
487
488    extern "C" fn math_double(value: i64) -> i64 {
489        value * 2
490    }
491
492    #[test]
493    fn build_context_set_var_fills_sparse_none_slots() -> anyhow::Result<()> {
494        use crate::context::{BuildContext, LocalVar};
495        use cranelift::codegen::ir::{Function, Signature, UserFuncName};
496        use cranelift::codegen::isa::CallConv;
497        use cranelift::prelude::{FunctionBuilder, FunctionBuilderContext};
498
499        let mut function = Function::with_name_signature(UserFuncName::user(0, 0), Signature::new(CallConv::Fast));
500        let mut function_ctx = FunctionBuilderContext::new();
501        let builder = FunctionBuilder::new(&mut function, &mut function_ctx);
502        let mut ctx = BuildContext::new(builder, &[], Type::Void)?;
503
504        ctx.set_var(33, LocalVar::None)?;
505
506        assert!(matches!(ctx.get_var(32)?, LocalVar::None));
507        assert!(matches!(ctx.get_var(33)?, LocalVar::None));
508        assert!(ctx.get_var(34).is_err());
509        Ok(())
510    }
511
512    #[test]
513    fn vm_can_add_native_after_jit_creation() -> anyhow::Result<()> {
514        let vm = Vm::new();
515        vm.add_native_module_ptr("math", "double", &[Type::I64], Type::I64, math_double as *const u8)?;
516        vm.import_code(
517            "vm_dynamic_native",
518            br#"
519            pub fn run(value: i64) {
520                math::double(value)
521            }
522            "#
523            .to_vec(),
524        )?;
525
526        let compiled = vm.get_fn("vm_dynamic_native::run", &[Type::I64])?;
527        assert_eq!(compiled.ret_ty(), &Type::I64);
528        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
529        assert_eq!(run(21), 42);
530        Ok(())
531    }
532
533    #[test]
534    fn vm_new_registers_std_and_any() -> anyhow::Result<()> {
535        let vm = Vm::new();
536        vm.add_std()?;
537        vm.add_any()?;
538        assert_eq!(vm.infer("std::print", &[Type::Any])?, Type::Void);
539        assert_eq!(vm.infer("std::sqrt", &[Type::F64])?, Type::F64);
540
541        vm.import_code(
542            "vm_new_default_any",
543            br#"
544            pub fn has_items(content) {
545                if content.is_map() {
546                    if content.contains("items") {
547                        return content.items.len() > 0;
548                    }
549                }
550                false
551            }
552            "#
553            .to_vec(),
554        )?;
555
556        assert_eq!(vm.infer("vm_new_default_any::has_items", &[Type::Any])?, Type::Bool);
557        let compiled = vm.get_fn("vm_new_default_any::has_items", &[Type::Any])?;
558        assert_eq!(compiled.ret_ty(), &Type::Bool);
559        Ok(())
560    }
561
562    #[test]
563    fn std_sqrt_is_available_as_top_level_function() -> anyhow::Result<()> {
564        let vm = Vm::with_all()?;
565        vm.import_code(
566            "vm_std_sqrt",
567            br#"
568            pub fn run() {
569                sqrt(9.0f64)
570            }
571            "#
572            .to_vec(),
573        )?;
574
575        let compiled = vm.get_fn("vm_std_sqrt::run", &[])?;
576        assert_eq!(compiled.ret_ty(), &Type::F64);
577        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
578        assert_eq!(run(), 3.0);
579        Ok(())
580    }
581
582    #[test]
583    fn tuple_assignment_uses_simultaneous_scalar_temps() -> anyhow::Result<()> {
584        let vm = Vm::with_all()?;
585        vm.import_code(
586            "vm_tuple_assignment",
587            br#"
588            pub fn swap() {
589                let a = 1i64;
590                let b = 2i64;
591                (a, b) = (b, a);
592                a * 10i64 + b
593            }
594
595            pub fn fib(n: i64) {
596                let a = 0i64;
597                let b = 1i64;
598                for _ in 0..n {
599                    (a, b) = (b, (a + b) % 1000000007i64);
600                }
601                a
602            }
603            "#
604            .to_vec(),
605        )?;
606
607        let swap = vm.get_fn("vm_tuple_assignment::swap", &[])?;
608        let swap: extern "C" fn() -> i64 = unsafe { std::mem::transmute(swap.ptr()) };
609        assert_eq!(swap(), 21);
610
611        let fib = vm.get_fn("vm_tuple_assignment::fib", &[Type::I64])?;
612        let fib: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(fib.ptr()) };
613        assert_eq!(fib(10), 55);
614        Ok(())
615    }
616
617    #[test]
618    fn nested_struct_arg_return_struct_field_is_static_field_access() -> anyhow::Result<()> {
619        let vm = Vm::with_all()?;
620        vm.import_code(
621            "vm_nested_struct_return_field",
622            br#"
623            pub struct Inner {
624                value: i64,
625            }
626
627            pub struct RoleMini {
628                inner: Inner,
629                hp: i64,
630            }
631
632            pub struct TeamMini {
633                role: RoleMini,
634            }
635
636            pub struct BigSummary {
637                winner: i64,
638                loser: i64,
639            }
640
641            pub fn make_big_with_team(team: TeamMini) {
642                let score = team.role.inner.value;
643                BigSummary{winner: score, loser: 0}
644            }
645
646            pub fn read_team_winner_direct() {
647                let team = TeamMini{role: RoleMini{inner: Inner{value: 9}, hp: 1}};
648                make_big_with_team(team).winner
649            }
650
651            pub fn read_team_winner_bound() {
652                let team = TeamMini{role: RoleMini{inner: Inner{value: 9}, hp: 1}};
653                let summary = make_big_with_team(team);
654                summary.winner
655            }
656            "#
657            .to_vec(),
658        )?;
659
660        let compiled = vm.get_fn("vm_nested_struct_return_field::read_team_winner_direct", &[])?;
661        assert_eq!(compiled.ret_ty(), &Type::I64);
662        let direct: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
663        assert_eq!(direct(), 9);
664
665        let compiled = vm.get_fn("vm_nested_struct_return_field::read_team_winner_bound", &[])?;
666        assert_eq!(compiled.ret_ty(), &Type::I64);
667        let bound: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
668        assert_eq!(bound(), 9);
669        Ok(())
670    }
671
672    #[test]
673    fn any_push_does_not_consume_reused_value() -> anyhow::Result<()> {
674        let vm = Vm::with_all()?;
675        vm.import_code(
676            "vm_any_push_reused_value",
677            br#"
678            pub fn run() {
679                let role_id = "acct_role_2";
680                let updated = [];
681                updated.push(role_id);
682                {
683                    ok: true,
684                    user_id: role_id,
685                    first: updated.get_idx(0)
686                }
687            }
688            "#
689            .to_vec(),
690        )?;
691
692        let compiled = vm.get_fn("vm_any_push_reused_value::run", &[])?;
693        assert_eq!(compiled.ret_ty(), &Type::Any);
694        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
695        let result = unsafe { &*run() };
696        assert_eq!(result.get_dynamic("ok").and_then(|value| value.as_bool()), Some(true));
697        assert_eq!(result.get_dynamic("user_id").map(|value| value.as_str().to_string()), Some("acct_role_2".to_string()));
698        assert_eq!(result.get_dynamic("first").map(|value| value.as_str().to_string()), Some("acct_role_2".to_string()));
699        Ok(())
700    }
701
702    #[test]
703    fn compares_any_with_string_literal_as_string() -> anyhow::Result<()> {
704        let vm = Vm::with_all()?;
705        vm.import_code(
706            "vm_string_compare_any",
707            br#"
708            pub fn any_ne_empty(chat_path) {
709                chat_path != ""
710            }
711            "#
712            .to_vec(),
713        )?;
714
715        let compiled = vm.get_fn("vm_string_compare_any::any_ne_empty", &[Type::Any])?;
716        assert_eq!(compiled.ret_ty(), &Type::Bool);
717
718        let any_ne_empty: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
719        let empty = Dynamic::from("");
720        let non_empty = Dynamic::from("chat");
721
722        assert!(!any_ne_empty(&empty));
723        assert!(any_ne_empty(&non_empty));
724        Ok(())
725    }
726
727    #[test]
728    fn compares_bool_values_and_bool_literals() -> anyhow::Result<()> {
729        let vm = Vm::with_all()?;
730        vm.import_code(
731            "vm_bool_compare",
732            br#"
733            pub fn eq_true(value: bool) {
734                value == true
735            }
736
737            pub fn ne_false(value: bool) {
738                value != false
739            }
740
741            pub fn literal_left(value: bool) {
742                true == value
743            }
744
745            pub fn eq_pair(left: bool, right: bool) {
746                left == right
747            }
748
749            pub fn logic_pair(left: bool, right: bool) {
750                (left && right) || (left == true && right != false)
751            }
752            "#
753            .to_vec(),
754        )?;
755
756        let compiled = vm.get_fn("vm_bool_compare::eq_true", &[Type::Bool])?;
757        assert_eq!(compiled.ret_ty(), &Type::Bool);
758        let eq_true: extern "C" fn(bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
759        assert!(eq_true(true));
760        assert!(!eq_true(false));
761
762        let compiled = vm.get_fn("vm_bool_compare::ne_false", &[Type::Bool])?;
763        assert_eq!(compiled.ret_ty(), &Type::Bool);
764        let ne_false: extern "C" fn(bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
765        assert!(ne_false(true));
766        assert!(!ne_false(false));
767
768        let compiled = vm.get_fn("vm_bool_compare::literal_left", &[Type::Bool])?;
769        assert_eq!(compiled.ret_ty(), &Type::Bool);
770        let literal_left: extern "C" fn(bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
771        assert!(literal_left(true));
772        assert!(!literal_left(false));
773
774        let compiled = vm.get_fn("vm_bool_compare::eq_pair", &[Type::Bool, Type::Bool])?;
775        assert_eq!(compiled.ret_ty(), &Type::Bool);
776        let eq_pair: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
777        assert!(eq_pair(true, true));
778        assert!(eq_pair(false, false));
779        assert!(!eq_pair(true, false));
780        assert!(!eq_pair(false, true));
781
782        let compiled = vm.get_fn("vm_bool_compare::logic_pair", &[Type::Bool, Type::Bool])?;
783        assert_eq!(compiled.ret_ty(), &Type::Bool);
784        let logic_pair: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
785        assert!(logic_pair(true, true));
786        assert!(!logic_pair(true, false));
787        assert!(!logic_pair(false, true));
788        assert!(!logic_pair(false, false));
789        Ok(())
790    }
791
792    #[test]
793    fn parenthesized_expression_can_call_any_method() -> anyhow::Result<()> {
794        let vm = Vm::with_all()?;
795        vm.import_code(
796            "vm_parenthesized_method_call",
797            br#"
798            pub fn run(value) {
799                (value + 2).to_i64()
800            }
801            "#
802            .to_vec(),
803        )?;
804
805        let compiled = vm.get_fn("vm_parenthesized_method_call::run", &[Type::Any])?;
806        assert_eq!(compiled.ret_ty(), &Type::I64);
807        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
808        let value = Dynamic::from(40i64);
809
810        assert_eq!(run(&value), 42);
811        Ok(())
812    }
813
814    #[test]
815    fn casts_any_float_to_i32_without_zeroing() -> anyhow::Result<()> {
816        let vm = Vm::with_all()?;
817        vm.import_code(
818            "vm_any_float_to_i32",
819            br#"
820            pub fn direct(value) {
821                value as i32
822            }
823
824            pub fn map_field(value) {
825                let field = value.v;
826                field as i32
827            }
828
829            pub fn damage(attacker, def_rate) {
830                let x = attacker.atk * (1.0 - def_rate);
831                x as i32
832            }
833            "#
834            .to_vec(),
835        )?;
836
837        let compiled = vm.get_fn("vm_any_float_to_i32::direct", &[Type::Any])?;
838        assert_eq!(compiled.ret_ty(), &Type::I32);
839        let direct: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
840        let value = Dynamic::from(9.5f64);
841        assert_eq!(direct(&value), 9);
842
843        let compiled = vm.get_fn("vm_any_float_to_i32::map_field", &[Type::Any])?;
844        assert_eq!(compiled.ret_ty(), &Type::I32);
845        let map_field: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
846        let value = dynamic::map!("v"=> 9.5f64);
847        assert_eq!(map_field(&value), 9);
848
849        let compiled = vm.get_fn("vm_any_float_to_i32::damage", &[Type::Any, Type::Any])?;
850        assert_eq!(compiled.ret_ty(), &Type::I32);
851        let damage: extern "C" fn(*const Dynamic, *const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
852        let attacker = dynamic::map!("atk"=> 64i64);
853        let def_rate = Dynamic::from(0.17f64);
854        assert_eq!(damage(&attacker, &def_rate), 53);
855        Ok(())
856    }
857
858    #[test]
859    fn binary_imm_promotes_integer_literals_for_float_left_values() -> anyhow::Result<()> {
860        let vm = Vm::with_all()?;
861        vm.import_code(
862            "vm_float_binary_imm",
863            br#"
864            pub fn add_f32(value: f32) {
865                value + 1i32
866            }
867
868            pub fn sub_f32(value: f32) {
869                value - 1i32
870            }
871
872            pub fn mul_f32(value: f32) {
873                value * 2i32
874            }
875
876            pub fn div_f32(value: f32) {
877                value / 2i32
878            }
879
880            pub fn gt_f32(value: f32) {
881                value > 2i32
882            }
883            "#
884            .to_vec(),
885        )?;
886
887        let compiled = vm.get_fn("vm_float_binary_imm::add_f32", &[Type::F32])?;
888        assert_eq!(compiled.ret_ty(), &Type::F32);
889        let add_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
890        assert_eq!(add_f32(2.5), 3.5);
891
892        let compiled = vm.get_fn("vm_float_binary_imm::sub_f32", &[Type::F32])?;
893        assert_eq!(compiled.ret_ty(), &Type::F32);
894        let sub_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
895        assert_eq!(sub_f32(2.5), 1.5);
896
897        let compiled = vm.get_fn("vm_float_binary_imm::mul_f32", &[Type::F32])?;
898        assert_eq!(compiled.ret_ty(), &Type::F32);
899        let mul_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
900        assert_eq!(mul_f32(2.5), 5.0);
901
902        let compiled = vm.get_fn("vm_float_binary_imm::div_f32", &[Type::F32])?;
903        assert_eq!(compiled.ret_ty(), &Type::F32);
904        let div_f32: extern "C" fn(f32) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
905        assert_eq!(div_f32(5.0), 2.5);
906
907        let compiled = vm.get_fn("vm_float_binary_imm::gt_f32", &[Type::F32])?;
908        assert_eq!(compiled.ret_ty(), &Type::Bool);
909        let gt_f32: extern "C" fn(f32) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
910        assert!(gt_f32(2.5));
911        assert!(!gt_f32(1.5));
912        Ok(())
913    }
914
915    #[test]
916    fn any_keys_returns_map_keys_and_empty_list_for_other_values() -> anyhow::Result<()> {
917        let vm = Vm::with_all()?;
918        vm.import_code(
919            "vm_any_keys",
920            br#"
921            pub fn map_keys(value) {
922                let keys = value.keys();
923                keys.len() == 2 && keys.contains("alpha") && keys.contains("beta")
924            }
925
926            pub fn non_map_keys(value) {
927                value.keys().len() == 0
928            }
929            "#
930            .to_vec(),
931        )?;
932
933        let compiled = vm.get_fn("vm_any_keys::map_keys", &[Type::Any])?;
934        assert_eq!(compiled.ret_ty(), &Type::Bool);
935        let map_keys: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
936        let value = dynamic::map!("alpha"=> 1i64, "beta"=> 2i64);
937        assert!(map_keys(&value));
938
939        let compiled = vm.get_fn("vm_any_keys::non_map_keys", &[Type::Any])?;
940        assert_eq!(compiled.ret_ty(), &Type::Bool);
941        let non_map_keys: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
942        let value = Dynamic::from("alpha");
943        assert!(non_map_keys(&value));
944        Ok(())
945    }
946
947    #[test]
948    fn string_methods_work_on_static_string_and_any_string_values() -> anyhow::Result<()> {
949        let vm = Vm::with_all()?;
950        vm.import_code(
951            "vm_string_methods",
952            br#"
953            pub fn static_string_methods(text: string) {
954                let parts = text.split(",");
955                text.starts_with("alpha")
956                    && text.is_string()
957                    && !text.is_null()
958                    && parts.len() == 2
959                    && parts.get_idx(0) == "alpha"
960                    && parts.get_idx(1) == "beta"
961            }
962
963            pub fn any_string_methods(value) {
964                let parts = value.split(",");
965                value.starts_with("alpha")
966                    && value.is_string()
967                    && !value.is_null()
968                    && parts.len() == 2
969                    && parts.get_idx(0) == "alpha"
970                    && parts.get_idx(1) == "beta"
971            }
972
973            pub fn any_null_methods(value) {
974                value.is_null() && !value.is_string()
975            }
976            "#
977            .to_vec(),
978        )?;
979
980        let compiled = vm.get_fn("vm_string_methods::static_string_methods", &[Type::Str])?;
981        assert_eq!(compiled.ret_ty(), &Type::Bool);
982        let static_string_methods: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
983        let text = Dynamic::from("alpha,beta");
984        assert!(static_string_methods(&text));
985
986        let compiled = vm.get_fn("vm_string_methods::any_string_methods", &[Type::Any])?;
987        assert_eq!(compiled.ret_ty(), &Type::Bool);
988        let any_string_methods: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
989        assert!(any_string_methods(&text));
990
991        let compiled = vm.get_fn("vm_string_methods::any_null_methods", &[Type::Any])?;
992        assert_eq!(compiled.ret_ty(), &Type::Bool);
993        let any_null_methods: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
994        let value = Dynamic::Null;
995        assert!(any_null_methods(&value));
996        Ok(())
997    }
998
999    #[test]
1000    fn static_string_add_uses_direct_strcat() -> anyhow::Result<()> {
1001        let vm = Vm::with_all()?;
1002        vm.import_code(
1003            "vm_static_strcat",
1004            br#"
1005            pub fn join(left: string, right: string) {
1006                left + right
1007            }
1008
1009            pub fn suffix(left: string) {
1010                left + "-tail"
1011            }
1012
1013            pub fn append_local() {
1014                let text: string = "alpha";
1015                text += "-beta";
1016                text += "-tail";
1017                text
1018            }
1019
1020            pub fn append_local_assign() {
1021                let text: string = "alpha";
1022                text = text + "-beta";
1023                text = text + "-tail";
1024                text
1025            }
1026
1027            pub fn append_arg(text: string) {
1028                text += "-tail";
1029                text
1030            }
1031
1032            pub fn append_arg_assign(text: string) {
1033                text = text + "-tail";
1034                text
1035            }
1036
1037            pub fn append_any(value) {
1038                value += "-tail";
1039                value
1040            }
1041
1042            pub fn add_sub_assign_form() {
1043                let x = 10i64;
1044                x = x + 1i64;
1045                x = x - 2i64;
1046                x
1047            }
1048            "#
1049            .to_vec(),
1050        )?;
1051
1052        let compiled = vm.get_fn("vm_static_strcat::join", &[Type::Str, Type::Str])?;
1053        assert_eq!(compiled.ret_ty(), &Type::Str);
1054        let join: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1055        let left = Dynamic::from("alpha");
1056        let right = Dynamic::from("-beta");
1057        let result = unsafe { &*join(&left, &right) };
1058        assert!(matches!(result, Dynamic::StringBuf(_)));
1059        assert_eq!(result.as_str(), "alpha-beta");
1060
1061        let compiled = vm.get_fn("vm_static_strcat::suffix", &[Type::Str])?;
1062        assert_eq!(compiled.ret_ty(), &Type::Str);
1063        let suffix: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1064        let result = unsafe { &*suffix(&left) };
1065        assert!(matches!(result, Dynamic::StringBuf(_)));
1066        assert_eq!(result.as_str(), "alpha-tail");
1067
1068        let compiled = vm.get_fn("vm_static_strcat::append_local", &[])?;
1069        assert_eq!(compiled.ret_ty(), &Type::Str);
1070        let append_local: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1071        let result = unsafe { &*append_local() };
1072        assert!(matches!(result, Dynamic::StringBuf(_)));
1073        assert_eq!(result.as_str(), "alpha-beta-tail");
1074
1075        let compiled = vm.get_fn("vm_static_strcat::append_local_assign", &[])?;
1076        assert_eq!(compiled.ret_ty(), &Type::Str);
1077        let append_local_assign: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1078        let result = unsafe { &*append_local_assign() };
1079        assert!(matches!(result, Dynamic::StringBuf(_)));
1080        assert_eq!(result.as_str(), "alpha-beta-tail");
1081
1082        let compiled = vm.get_fn("vm_static_strcat::append_arg", &[Type::Str])?;
1083        assert_eq!(compiled.ret_ty(), &Type::Str);
1084        let append_arg: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1085        let input = Dynamic::from("alpha");
1086        let result = unsafe { &*append_arg(&input) };
1087        assert_eq!(result.as_str(), "alpha-tail");
1088        assert_eq!(input.as_str(), "alpha");
1089
1090        let compiled = vm.get_fn("vm_static_strcat::append_arg_assign", &[Type::Str])?;
1091        assert_eq!(compiled.ret_ty(), &Type::Str);
1092        let append_arg_assign: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1093        let input = Dynamic::from("alpha");
1094        let result = unsafe { &*append_arg_assign(&input) };
1095        assert_eq!(result.as_str(), "alpha-tail");
1096        assert_eq!(input.as_str(), "alpha");
1097
1098        let compiled = vm.get_fn("vm_static_strcat::append_any", &[Type::Any])?;
1099        assert_eq!(compiled.ret_ty(), &Type::Str);
1100        let append_any: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1101        let input = Dynamic::from("alpha");
1102        let result = unsafe { &*append_any(&input) };
1103        assert_eq!(result.as_str(), "alpha-tail");
1104        assert_eq!(input.as_str(), "alpha");
1105
1106        let compiled = vm.get_fn("vm_static_strcat::add_sub_assign_form", &[])?;
1107        assert_eq!(compiled.ret_ty(), &Type::I64);
1108        let add_sub_assign_form: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1109        assert_eq!(add_sub_assign_form(), 9);
1110        Ok(())
1111    }
1112
1113    #[test]
1114    fn primitive_type_check_methods_call_any_runtime() -> anyhow::Result<()> {
1115        let vm = Vm::with_all()?;
1116        vm.import_code(
1117            "vm_primitive_type_check_methods",
1118            br#"
1119            pub fn int_checks() {
1120                !42i64.is_list()
1121                    && !42i64.is_map()
1122                    && !42i64.is_string()
1123                    && !42i64.is_null()
1124            }
1125
1126            pub fn bool_checks() {
1127                !true.is_list() && !true.is_map() && !true.is_null()
1128            }
1129            "#
1130            .to_vec(),
1131        )?;
1132
1133        let compiled = vm.get_fn("vm_primitive_type_check_methods::int_checks", &[])?;
1134        assert_eq!(compiled.ret_ty(), &Type::Bool);
1135        let int_checks: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1136        assert!(int_checks());
1137
1138        let compiled = vm.get_fn("vm_primitive_type_check_methods::bool_checks", &[])?;
1139        assert_eq!(compiled.ret_ty(), &Type::Bool);
1140        let bool_checks: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1141        assert!(bool_checks());
1142        Ok(())
1143    }
1144
1145    #[test]
1146    fn for_loop_iterates_any_list_and_map_values() -> anyhow::Result<()> {
1147        let vm = Vm::with_all()?;
1148        vm.import_code(
1149            "vm_for_any_collections",
1150            br#"
1151            pub fn list_sum(items) {
1152                let total = 0i64;
1153                for item in items {
1154                    total += item;
1155                }
1156                total
1157            }
1158
1159            pub fn map_sum(data) {
1160                let total = 0i64;
1161                for (key, value) in data {
1162                    total += value;
1163                }
1164                total
1165            }
1166            "#
1167            .to_vec(),
1168        )?;
1169
1170        let compiled = vm.get_fn("vm_for_any_collections::list_sum", &[Type::Any])?;
1171        assert_eq!(compiled.ret_ty(), &Type::I64);
1172        let list_sum: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1173        let items = Dynamic::list(vec![1i64.into(), 2i64.into(), 3i64.into()]);
1174        assert_eq!(list_sum(&items), 6);
1175
1176        let compiled = vm.get_fn("vm_for_any_collections::map_sum", &[Type::Any])?;
1177        assert_eq!(compiled.ret_ty(), &Type::I64);
1178        let map_sum: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1179        let data = dynamic::map!("a"=> 4i64, "b"=> 5i64);
1180        assert_eq!(map_sum(&data), 9);
1181        Ok(())
1182    }
1183
1184    #[test]
1185    fn compares_concrete_value_with_string_literal_as_string() -> anyhow::Result<()> {
1186        let vm = Vm::with_all()?;
1187        vm.import_code(
1188            "vm_string_compare_imm",
1189            br#"
1190            pub fn int_eq_str(value: i64) {
1191                value == "42"
1192            }
1193
1194            pub fn int_to_str(value: i64) {
1195                value + ""
1196            }
1197            "#
1198            .to_vec(),
1199        )?;
1200
1201        let compiled = vm.get_fn("vm_string_compare_imm::int_eq_str", &[Type::I64])?;
1202        assert_eq!(compiled.ret_ty(), &Type::Bool);
1203
1204        let int_eq_str: extern "C" fn(i64) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1205
1206        let compiled = vm.get_fn("vm_string_compare_imm::int_to_str", &[Type::I64])?;
1207        assert_eq!(compiled.ret_ty(), &Type::Str);
1208        let int_to_str: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1209        let text = int_to_str(42);
1210        assert_eq!(unsafe { &*text }.as_str(), "42");
1211
1212        assert!(int_eq_str(42));
1213        assert!(!int_eq_str(7));
1214        Ok(())
1215    }
1216
1217    #[test]
1218    fn concatenates_string_with_integer_values() -> anyhow::Result<()> {
1219        let vm = Vm::with_all()?;
1220        vm.import_code(
1221            "vm_string_concat_integer",
1222            br#"
1223            pub fn idx_key(idx: i64) {
1224                "" + idx
1225            }
1226
1227            pub fn level_text(level: i64) {
1228                "" + level + " level"
1229            }
1230
1231            pub fn gold_text(currency) {
1232                "" + currency.gold
1233            }
1234            "#
1235            .to_vec(),
1236        )?;
1237
1238        let compiled = vm.get_fn("vm_string_concat_integer::idx_key", &[Type::I64])?;
1239        let idx_key: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1240        let result = unsafe { &*idx_key(7) };
1241        assert!(matches!(result, Dynamic::StringBuf(_)));
1242        assert_eq!(result.as_str(), "7");
1243
1244        let compiled = vm.get_fn("vm_string_concat_integer::level_text", &[Type::I64])?;
1245        let level_text: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1246        let result = unsafe { &*level_text(12) };
1247        assert_eq!(result.as_str(), "12 level");
1248
1249        let compiled = vm.get_fn("vm_string_concat_integer::gold_text", &[Type::Any])?;
1250        let gold_text: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1251        let currency = dynamic::map!("gold"=> 345i64);
1252        let result = unsafe { &*gold_text(&currency) };
1253        assert_eq!(result.as_str(), "345");
1254        Ok(())
1255    }
1256
1257    #[test]
1258    fn coerces_string_concat_to_i64_without_unimplemented_log() -> anyhow::Result<()> {
1259        let vm = Vm::with_all()?;
1260        vm.import_code(
1261            "vm_string_concat_to_i64",
1262            br#"
1263            pub fn run(idx: i64) {
1264                ("" + idx) as i64
1265            }
1266            "#
1267            .to_vec(),
1268        )?;
1269
1270        let compiled = vm.get_fn("vm_string_concat_to_i64::run", &[Type::I64])?;
1271        assert_eq!(compiled.ret_ty(), &Type::I64);
1272        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1273        assert_eq!(run(7), 7);
1274        Ok(())
1275    }
1276
1277    #[test]
1278    fn casts_dynamic_string_numbers_to_ints_and_floats() -> anyhow::Result<()> {
1279        let vm = Vm::with_all()?;
1280        vm.import_code(
1281            "vm_string_number_casts",
1282            br#"
1283            pub fn limit_i64(req) {
1284                req["@query"].limit as i64
1285            }
1286
1287            pub fn limit_i32(req) {
1288                req["@query"].limit as i32
1289            }
1290
1291            pub fn price_f64(req) {
1292                req["@query"].price as f64
1293            }
1294
1295            pub fn price_f32(req) {
1296                req["@query"].price as f32
1297            }
1298
1299            pub fn literal_i64() {
1300                "42" as i64
1301            }
1302
1303            pub fn literal_f64() {
1304                "3.5" as f64
1305            }
1306
1307            pub fn bad_number(req) {
1308                req["@query"].bad as i64
1309            }
1310            "#
1311            .to_vec(),
1312        )?;
1313
1314        let req = dynamic::map!("@query"=> dynamic::map!("limit"=> "50", "price"=> "3.5", "bad"=> "nope"));
1315
1316        let limit_i64 = vm.get_fn("vm_string_number_casts::limit_i64", &[Type::Any])?;
1317        assert_eq!(limit_i64.ret_ty(), &Type::I64);
1318        let limit_i64: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(limit_i64.ptr()) };
1319        assert_eq!(limit_i64(&req), 50);
1320
1321        let limit_i32 = vm.get_fn("vm_string_number_casts::limit_i32", &[Type::Any])?;
1322        assert_eq!(limit_i32.ret_ty(), &Type::I32);
1323        let limit_i32: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(limit_i32.ptr()) };
1324        assert_eq!(limit_i32(&req), 50);
1325
1326        let price_f64 = vm.get_fn("vm_string_number_casts::price_f64", &[Type::Any])?;
1327        assert_eq!(price_f64.ret_ty(), &Type::F64);
1328        let price_f64: extern "C" fn(*const Dynamic) -> f64 = unsafe { std::mem::transmute(price_f64.ptr()) };
1329        assert_eq!(price_f64(&req), 3.5);
1330
1331        let price_f32 = vm.get_fn("vm_string_number_casts::price_f32", &[Type::Any])?;
1332        assert_eq!(price_f32.ret_ty(), &Type::F32);
1333        let price_f32: extern "C" fn(*const Dynamic) -> f32 = unsafe { std::mem::transmute(price_f32.ptr()) };
1334        assert_eq!(price_f32(&req), 3.5);
1335
1336        let literal_i64 = vm.get_fn("vm_string_number_casts::literal_i64", &[])?;
1337        assert_eq!(literal_i64.ret_ty(), &Type::I64);
1338        let literal_i64: extern "C" fn() -> i64 = unsafe { std::mem::transmute(literal_i64.ptr()) };
1339        assert_eq!(literal_i64(), 42);
1340
1341        let literal_f64 = vm.get_fn("vm_string_number_casts::literal_f64", &[])?;
1342        assert_eq!(literal_f64.ret_ty(), &Type::F64);
1343        let literal_f64: extern "C" fn() -> f64 = unsafe { std::mem::transmute(literal_f64.ptr()) };
1344        assert_eq!(literal_f64(), 3.5);
1345
1346        let bad_number = vm.get_fn("vm_string_number_casts::bad_number", &[Type::Any])?;
1347        assert_eq!(bad_number.ret_ty(), &Type::I64);
1348        let bad_number: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(bad_number.ptr()) };
1349        assert_eq!(bad_number(&req), 0);
1350        Ok(())
1351    }
1352
1353    #[test]
1354    fn unifies_explicit_return_and_tail_integer_widths() -> anyhow::Result<()> {
1355        let vm = Vm::with_all()?;
1356        vm.import_code(
1357            "vm_return_integer_widths",
1358            br#"
1359            pub fn selected(flag, slot) {
1360                if flag {
1361                    return slot;
1362                }
1363                0
1364            }
1365            "#
1366            .to_vec(),
1367        )?;
1368
1369        let compiled = vm.get_fn("vm_return_integer_widths::selected", &[Type::Bool, Type::I64])?;
1370        assert_eq!(compiled.ret_ty(), &Type::I64);
1371        let selected: extern "C" fn(bool, i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1372
1373        assert_eq!(selected(true, 7), 7);
1374        assert_eq!(selected(false, 7), 0);
1375        Ok(())
1376    }
1377
1378    #[test]
1379    fn root_contains_string_concat_is_bool_condition() -> anyhow::Result<()> {
1380        let vm = Vm::with_all()?;
1381        vm.import_code(
1382            "vm_root_contains_condition",
1383            br#"
1384            pub fn exists(user_id) {
1385                if root::contains("redis/user/" + user_id) {
1386                    return 1;
1387                }
1388                0
1389            }
1390            "#
1391            .to_vec(),
1392        )?;
1393
1394        assert_eq!(vm.infer("root::contains", &[Type::Any])?, Type::Bool);
1395        let compiled = vm.get_fn("vm_root_contains_condition::exists", &[Type::Any])?;
1396        assert_eq!(compiled.ret_ty(), &Type::I32);
1397        Ok(())
1398    }
1399
1400    #[test]
1401    fn root_add_map_can_be_printed() -> anyhow::Result<()> {
1402        let vm = Vm::with_all()?;
1403        assert_eq!(vm.infer("root::add_map", &[Type::Any])?, Type::Bool);
1404        vm.import_code(
1405            "vm_root_add_map_print",
1406            br#"
1407            pub fn run() {
1408                print(root::add_map("local/world_handlers/til_map_novicevillage"));
1409            }
1410            "#
1411            .to_vec(),
1412        )?;
1413
1414        let compiled = vm.get_fn("vm_root_add_map_print::run", &[])?;
1415        assert!(compiled.ret_ty().is_void());
1416        Ok(())
1417    }
1418
1419    #[test]
1420    fn std_log_accepts_any_and_returns_void() -> anyhow::Result<()> {
1421        let vm = Vm::with_all()?;
1422        vm.import_code(
1423            "vm_std_log",
1424            br#"
1425            pub fn run(value) {
1426                log({ ok: true, value: value });
1427            }
1428            "#
1429            .to_vec(),
1430        )?;
1431
1432        let compiled = vm.get_fn("vm_std_log::run", &[Type::Any])?;
1433        assert!(compiled.ret_ty().is_void());
1434        let run: extern "C" fn(*const Dynamic) = unsafe { std::mem::transmute(compiled.ptr()) };
1435        let value = Dynamic::from(7i64);
1436        run(&value);
1437        Ok(())
1438    }
1439
1440    #[test]
1441    fn unary_not_any_loop_var_is_bool_condition() -> anyhow::Result<()> {
1442        let vm = Vm::with_all()?;
1443        vm.import_code(
1444            "vm_unary_not_any_loop_var",
1445            br#"
1446            pub fn count_missing(flags) {
1447                let missing = 0;
1448                for exists in flags {
1449                    if !exists {
1450                        missing = missing + 1;
1451                    }
1452                }
1453                missing
1454            }
1455            "#
1456            .to_vec(),
1457        )?;
1458
1459        let compiled = vm.get_fn("vm_unary_not_any_loop_var::count_missing", &[Type::Any])?;
1460        assert_eq!(compiled.ret_ty(), &Type::I32);
1461        Ok(())
1462    }
1463
1464    #[test]
1465    fn closure_literal_can_be_called_immediately() -> anyhow::Result<()> {
1466        let vm = Vm::with_all()?;
1467        vm.import_code(
1468            "vm_closure_immediate_call",
1469            br#"
1470            pub fn no_args() {
1471                let r = || { 1i32 }();
1472                r
1473            }
1474
1475            pub fn with_arg() {
1476                |value: i32| { value + 1i32 }(2i32)
1477            }
1478            "#
1479            .to_vec(),
1480        )?;
1481
1482        let compiled = vm.get_fn("vm_closure_immediate_call::no_args", &[])?;
1483        assert_eq!(compiled.ret_ty(), &Type::I32);
1484        let no_args: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
1485        assert_eq!(no_args(), 1);
1486
1487        let compiled = vm.get_fn("vm_closure_immediate_call::with_arg", &[])?;
1488        assert_eq!(compiled.ret_ty(), &Type::I32);
1489        let with_arg: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
1490        assert_eq!(with_arg(), 3);
1491        Ok(())
1492    }
1493
1494    #[test]
1495    fn semicolon_tail_call_makes_function_void() -> anyhow::Result<()> {
1496        let vm = Vm::with_all()?;
1497        vm.import_code(
1498            "vm_semicolon_tail_void",
1499            br#"
1500            pub fn send_role_select(idx, account_id, selected_slot) {
1501                root::send("local/ui/send_dialog", {
1502                    idx: idx,
1503                    account_id: account_id,
1504                    selected_slot: selected_slot
1505                });
1506            }
1507            "#
1508            .to_vec(),
1509        )?;
1510
1511        let compiled = vm.get_fn("vm_semicolon_tail_void::send_role_select", &[Type::Any, Type::Any, Type::Any])?;
1512        assert_eq!(compiled.ret_ty(), &Type::Void);
1513        Ok(())
1514    }
1515
1516    #[test]
1517    fn bare_return_conflicts_with_non_void_return() -> anyhow::Result<()> {
1518        let vm = Vm::with_all()?;
1519        vm.import_code(
1520            "vm_bare_return_conflict",
1521            br#"
1522            pub fn run(flag) {
1523                if flag {
1524                    return;
1525                }
1526                1
1527            }
1528            "#
1529            .to_vec(),
1530        )?;
1531
1532        let err = match vm.get_fn("vm_bare_return_conflict::run", &[Type::Bool]) {
1533            Ok(_) => panic!("expected mismatched return types to fail"),
1534            Err(err) => err,
1535        };
1536        assert!(format!("{err:#}").contains("返回类型不一致"));
1537        Ok(())
1538    }
1539
1540    #[test]
1541    fn root_get_accepts_string_concat_with_dynamic_field() -> anyhow::Result<()> {
1542        let vm = Vm::with_all()?;
1543        vm.import_code(
1544            "vm_root_get_dynamic_concat",
1545            br#"
1546            pub fn get_action(req) {
1547                root::get("local/game/panel_actions/" + req.idx)
1548            }
1549            "#
1550            .to_vec(),
1551        )?;
1552
1553        root::add("local/game/panel_actions/7", dynamic::map!("id"=> "action-7").into())?;
1554        let compiled = vm.get_fn("vm_root_get_dynamic_concat::get_action", &[Type::Any])?;
1555        assert_eq!(compiled.ret_ty(), &Type::Any);
1556        let get_action: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1557        let req = dynamic::map!("idx"=> 7i64);
1558        let result = unsafe { &*get_action(&req) };
1559
1560        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("action-7".to_string()));
1561        Ok(())
1562    }
1563
1564    #[test]
1565    fn root_add_fn_registers_handler_with_dynamic_field_path_concat() -> anyhow::Result<()> {
1566        let vm = Vm::with_all()?;
1567        vm.import_code(
1568            "vm_registered_panel_action",
1569            br#"
1570            pub fn panel_action(req) {
1571                root::get("local/game/panel_actions/" + req.idx)
1572            }
1573
1574            pub fn register() {
1575                root::add_fn("local/ui/panel_action", "vm_registered_panel_action::panel_action")
1576            }
1577            "#
1578            .to_vec(),
1579        )?;
1580
1581        let compiled = vm.get_fn("vm_registered_panel_action::register", &[])?;
1582        assert_eq!(compiled.ret_ty(), &Type::Bool);
1583        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1584        assert!(register());
1585        Ok(())
1586    }
1587
1588    #[test]
1589    fn std_spawn_runs_named_function_with_tuple_args() -> anyhow::Result<()> {
1590        let zero_path = "local/vm_std_spawn/zero";
1591        let sum_path = "local/vm_std_spawn/sum";
1592        let closure_path = "local/vm_std_spawn/closure";
1593        let closure_vars_path = "local/vm_std_spawn/closure_vars";
1594        let _ = root::remove(zero_path);
1595        let _ = root::remove(sum_path);
1596        let _ = root::remove(closure_path);
1597        let _ = root::remove(closure_vars_path);
1598        let vm = Vm::with_all()?;
1599        vm.import_code(
1600            "vm_std_spawn",
1601            br#"
1602            pub fn zero() {
1603                root::add("local/vm_std_spawn/zero", 1);
1604            }
1605
1606            pub fn job(left, right) {
1607                root::add("local/vm_std_spawn/sum", left + right);
1608            }
1609
1610            pub fn start_zero() {
1611                spawn("vm_std_spawn::zero", ())
1612            }
1613
1614            pub fn start_sum() {
1615                spawn("vm_std_spawn::job", (10, 20))
1616            }
1617
1618            pub fn start_closure() {
1619                spawn(|x, y| {
1620                    root::add("local/vm_std_spawn/closure", x + y);
1621                }, (3, 4))
1622            }
1623
1624            pub fn start_closure_vars() {
1625                let x = 5;
1626                let y = 6;
1627                spawn(|left, right| {
1628                    root::add("local/vm_std_spawn/closure_vars", left + right);
1629                }, (x, y))
1630            }
1631            "#
1632            .to_vec(),
1633        )?;
1634
1635        let compiled = vm.get_fn("vm_std_spawn::start_zero", &[])?;
1636        assert_eq!(compiled.ret_ty(), &Type::Bool);
1637        let start_zero: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1638        assert!(start_zero());
1639
1640        let compiled = vm.get_fn("vm_std_spawn::start_sum", &[])?;
1641        assert_eq!(compiled.ret_ty(), &Type::Bool);
1642        let start_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1643        assert!(start_sum());
1644
1645        let compiled = vm.get_fn("vm_std_spawn::start_closure", &[])?;
1646        assert_eq!(compiled.ret_ty(), &Type::Bool);
1647        let start_closure: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1648        assert!(start_closure());
1649
1650        let compiled = vm.get_fn("vm_std_spawn::start_closure_vars", &[])?;
1651        assert_eq!(compiled.ret_ty(), &Type::Bool);
1652        let start_closure_vars: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1653        assert!(start_closure_vars());
1654
1655        for _ in 0..50 {
1656            let zero_done = root::get(zero_path).ok().and_then(|value| value.as_int()) == Some(1);
1657            let sum_done = root::get(sum_path).ok().and_then(|value| value.as_int()) == Some(30);
1658            let closure_done = root::get(closure_path).ok().and_then(|value| value.as_int()) == Some(7);
1659            let closure_vars_done = root::get(closure_vars_path).ok().and_then(|value| value.as_int()) == Some(11);
1660            if zero_done && sum_done && closure_done && closure_vars_done {
1661                return Ok(());
1662            }
1663            std::thread::sleep(std::time::Duration::from_millis(10));
1664        }
1665
1666        anyhow::bail!("spawned jobs did not write expected results");
1667    }
1668
1669    #[test]
1670    fn native_can_save_and_later_call_closure_callback() -> anyhow::Result<()> {
1671        static SAVED_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1672
1673        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
1674            if callback.is_null() {
1675                return false;
1676            }
1677            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1678                return false;
1679            };
1680            *SAVED_CALLBACK.lock().unwrap() = Some(callback);
1681            true
1682        }
1683
1684        let path = "local/vm_callback/result";
1685        let _ = root::remove(path);
1686        *SAVED_CALLBACK.lock().unwrap() = None;
1687
1688        let vm = Vm::with_all()?;
1689        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
1690        vm.import_code(
1691            "vm_callback",
1692            br#"
1693            pub fn register() {
1694                let n = 41;
1695                callback_test::save(|| {
1696                    root::add("local/vm_callback/result", n + 1);
1697                    true
1698                })
1699            }
1700            "#
1701            .to_vec(),
1702        )?;
1703
1704        let compiled = vm.get_fn("vm_callback::register", &[])?;
1705        assert_eq!(compiled.ret_ty(), &Type::Bool);
1706        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1707        assert!(register());
1708        assert!(root::get(path).is_err());
1709
1710        let callback = SAVED_CALLBACK.lock().unwrap().clone().expect("callback should be saved");
1711        let result = callback.call0()?;
1712        assert_eq!(result.as_bool(), Some(true));
1713        assert_eq!(root::get(path)?.as_int(), Some(42));
1714        Ok(())
1715    }
1716
1717    #[test]
1718    fn native_can_save_and_later_call_named_function_callback() -> anyhow::Result<()> {
1719        static SAVED_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1720
1721        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
1722            if callback.is_null() {
1723                return false;
1724            }
1725            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1726                return false;
1727            };
1728            *SAVED_CALLBACK.lock().unwrap() = Some(callback);
1729            true
1730        }
1731
1732        let path = "local/vm_named_callback/result";
1733        let _ = root::remove(path);
1734        *SAVED_CALLBACK.lock().unwrap() = None;
1735
1736        let vm = Vm::with_all()?;
1737        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
1738        vm.import_code(
1739            "vm_named_callback",
1740            br#"
1741            pub fn on_result() {
1742                root::add("local/vm_named_callback/result", "done");
1743                true
1744            }
1745
1746            pub fn register() {
1747                callback_test::save(on_result)
1748            }
1749            "#
1750            .to_vec(),
1751        )?;
1752
1753        let register = vm.get_fn("vm_named_callback::register", &[])?;
1754        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
1755        assert!(register());
1756        assert!(root::get(path).is_err());
1757
1758        let callback = SAVED_CALLBACK.lock().unwrap().clone().expect("callback should be saved");
1759        assert_eq!(callback.call1(dynamic::map!("text"=> "done"))?.as_bool(), Some(true));
1760        assert_eq!(root::get(path)?.as_str(), "done");
1761        Ok(())
1762    }
1763
1764    #[test]
1765    fn native_callback_can_receive_later_dynamic_args() -> anyhow::Result<()> {
1766        static SAVED_PATH_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1767        static SAVED_SUM_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1768
1769        extern "C" fn save_path_callback(callback: *const Dynamic) -> bool {
1770            if callback.is_null() {
1771                return false;
1772            }
1773            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1774                return false;
1775            };
1776            *SAVED_PATH_CALLBACK.lock().unwrap() = Some(callback);
1777            true
1778        }
1779
1780        extern "C" fn save_sum_callback(callback: *const Dynamic) -> bool {
1781            if callback.is_null() {
1782                return false;
1783            }
1784            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1785                return false;
1786            };
1787            *SAVED_SUM_CALLBACK.lock().unwrap() = Some(callback);
1788            true
1789        }
1790
1791        let path_result = "local/vm_callback/path";
1792        let sum_result = "local/vm_callback/sum8";
1793        let _ = root::remove(path_result);
1794        let _ = root::remove(sum_result);
1795        *SAVED_PATH_CALLBACK.lock().unwrap() = None;
1796        *SAVED_SUM_CALLBACK.lock().unwrap() = None;
1797
1798        let vm = Vm::with_all()?;
1799        vm.add_native_module_ptr("callback_test", "save_path", &[Type::Any], Type::Bool, save_path_callback as *const u8)?;
1800        vm.add_native_module_ptr("callback_test", "save_sum", &[Type::Any], Type::Bool, save_sum_callback as *const u8)?;
1801        vm.import_code(
1802            "vm_callback_args",
1803            br#"
1804            pub fn register_path() {
1805                let key = "local/vm_callback/path";
1806                callback_test::save_path(|path| {
1807                    root::add(key, path);
1808                    true
1809                })
1810            }
1811
1812            pub fn register_sum() {
1813                callback_test::save_sum(|a, b, c, d, e, f, g, h| {
1814                    root::add("local/vm_callback/sum8", a + b + c + d + e + f + g + h);
1815                    true
1816                })
1817            }
1818            "#
1819            .to_vec(),
1820        )?;
1821
1822        let register_path = vm.get_fn("vm_callback_args::register_path", &[])?;
1823        let register_path: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_path.ptr()) };
1824        assert!(register_path());
1825
1826        let register_sum = vm.get_fn("vm_callback_args::register_sum", &[])?;
1827        let register_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_sum.ptr()) };
1828        assert!(register_sum());
1829
1830        let path_callback = SAVED_PATH_CALLBACK.lock().unwrap().clone().expect("path callback should be saved");
1831        assert_eq!(path_callback.call1(Dynamic::from("picked.txt"))?.as_bool(), Some(true));
1832        assert_eq!(root::get(path_result)?.as_str(), "picked.txt");
1833
1834        let sum_callback = SAVED_SUM_CALLBACK.lock().unwrap().clone().expect("sum callback should be saved");
1835        let sum_args = (1i64..=8).map(Dynamic::from).collect();
1836        assert_eq!(sum_callback.call(sum_args)?.as_bool(), Some(true));
1837        assert_eq!(root::get(sum_result)?.as_int(), Some(36));
1838        Ok(())
1839    }
1840
1841    #[test]
1842    fn root_add_fn_accepts_string_concat_in_registered_handler() -> anyhow::Result<()> {
1843        let vm = Vm::with_all()?;
1844        vm.import_code(
1845            "vm_registered_string_concat",
1846            br#"
1847            pub fn send_panel(idx: i64) {
1848                let idx_key = "" + idx;
1849                idx_key
1850            }
1851            "#
1852            .to_vec(),
1853        )?;
1854
1855        assert!(vm.get_fn_ptr("vm_registered_string_concat::send_panel", &[Type::Any]).is_ok());
1856        Ok(())
1857    }
1858
1859    #[test]
1860    fn root_send_idx_returns_handler_value() -> anyhow::Result<()> {
1861        fn echo_handler(msg: Dynamic) -> Dynamic {
1862            dynamic::map!("type"=> "echo", "id"=> msg.get_dynamic("id").unwrap_or(Dynamic::Null))
1863        }
1864
1865        let vm = Vm::with_all()?;
1866        vm.import_code(
1867            "vm_root_send_idx_return",
1868            br#"
1869            pub fn call(req) {
1870                root::send_idx("local/send_idx_return_handlers", 0, req)
1871            }
1872            "#
1873            .to_vec(),
1874        )?;
1875
1876        root::add_list("local/send_idx_return_handlers")?;
1877        let (mount, name) = root::get_mount("local/send_idx_return_handlers")?;
1878        mount.push(name, root::Object::Native(echo_handler))?;
1879
1880        assert_eq!(vm.infer("root::send_idx", &[Type::Any, Type::I64, Type::Any])?, Type::Any);
1881        let compiled = vm.get_fn("vm_root_send_idx_return::call", &[Type::Any])?;
1882        assert_eq!(compiled.ret_ty(), &Type::Any);
1883        let call: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1884        let req = dynamic::map!("id"=> 42i64);
1885        let result = unsafe { &*call(&req) };
1886
1887        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("echo".to_string()));
1888        assert_eq!(result.get_dynamic("id").and_then(|value| value.as_int()), Some(42));
1889        Ok(())
1890    }
1891
1892    #[test]
1893    fn compiles_public_hotspots_with_string_paths_and_keys() -> anyhow::Result<()> {
1894        let vm = Vm::with_all()?;
1895        vm.import_code(
1896            "vm_public_hotspots",
1897            br#"
1898            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
1899                {
1900                    path: action_map_path,
1901                    panel_id: panel_id,
1902                    action_id: action_id,
1903                    id: hotspot.id
1904                }
1905            }
1906
1907            pub fn public_hotspots(idx, panel_id, hotspots) {
1908                let idx_key = "" + idx;
1909                let action_map_path = "local/game/panel_actions/" + idx_key;
1910
1911                let existing_action_map = root::get(action_map_path);
1912                if !existing_action_map.is_map() {
1913                    root::add_map(action_map_path);
1914                }
1915
1916                if hotspots.is_map() {
1917                    let public_items = {};
1918                    for action_id in hotspots.keys() {
1919                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
1920                    }
1921                    return public_items;
1922                }
1923
1924                let public_items = [];
1925                let i = 0;
1926                while i < hotspots.len() {
1927                    let hotspot = hotspots.get_idx(i);
1928                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
1929                    public_items.push(item);
1930                    i = i + 1;
1931                }
1932
1933                public_items
1934            }
1935            "#
1936            .to_vec(),
1937        )?;
1938
1939        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::I64, Type::Any, Type::Any]).is_ok());
1940        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::Any, Type::Any, Type::Any]).is_ok());
1941        Ok(())
1942    }
1943
1944    #[test]
1945    fn send_panel_calls_public_hotspots_with_dynamic_request() -> anyhow::Result<()> {
1946        let vm = Vm::with_all()?;
1947        vm.import_code(
1948            "vm_send_panel_public_hotspots",
1949            br#"
1950            pub fn ok(value) {
1951                value
1952            }
1953
1954            pub fn panel_from_node(req) {
1955                {
1956                    panel_id: req.panel_id,
1957                    hotspots: req.hotspots
1958                }
1959            }
1960
1961            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
1962                {
1963                    path: action_map_path,
1964                    panel_id: panel_id,
1965                    action_id: action_id,
1966                    id: hotspot.id
1967                }
1968            }
1969
1970            pub fn public_hotspots(idx, panel_id, hotspots) {
1971                let idx_key = "" + idx;
1972                let action_map_path = "local/game/panel_actions/" + idx_key;
1973
1974                let existing_action_map = root::get(action_map_path);
1975                if !existing_action_map.is_map() {
1976                    root::add_map(action_map_path);
1977                }
1978
1979                if hotspots.is_map() {
1980                    let public_items = {};
1981                    for action_id in hotspots.keys() {
1982                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
1983                    }
1984                    return public_items;
1985                }
1986
1987                let public_items = [];
1988                let i = 0;
1989                while i < hotspots.len() {
1990                    let hotspot = hotspots.get_idx(i);
1991                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
1992                    public_items.push(item);
1993                    i = i + 1;
1994                }
1995
1996                public_items
1997            }
1998
1999            pub fn send_panel(req) {
2000                let panel = req.panel;
2001                if !panel.is_map() {
2002                    panel = panel_from_node(req);
2003                }
2004                if !panel.is_map() {
2005                    return ok({
2006                        id: 4,
2007                        type: "panel_rejected",
2008                        reason: "invalid panel"
2009                    });
2010                }
2011                panel.id = 4;
2012                panel.idx = req.idx;
2013                if !panel.contains("type") {
2014                    panel.type = "panel";
2015                }
2016                if panel.contains("hotspots") {
2017                    panel.hotspots = public_hotspots(req.idx, panel.panel_id, panel.hotspots);
2018                }
2019                root::send_idx("local/ws", req.idx, panel);
2020                ok({
2021                    id: 4,
2022                    type: "panel",
2023                    panel_id: panel.panel_id
2024                })
2025            }
2026            "#
2027            .to_vec(),
2028        )?;
2029
2030        let compiled = vm.get_fn("vm_send_panel_public_hotspots::send_panel", &[Type::Any])?;
2031        assert_eq!(compiled.ret_ty(), &Type::Any);
2032        let send_panel: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2033        let req = dynamic::map!(
2034            "idx"=> 7i64,
2035            "panel"=> dynamic::map!(
2036                "panel_id"=> "main",
2037                "hotspots"=> dynamic::map!(
2038                    "open"=> dynamic::map!("id"=> "open")
2039                )
2040            )
2041        );
2042        let result = unsafe { &*send_panel(&req) };
2043
2044        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("panel".to_string()));
2045        assert_eq!(result.get_dynamic("panel_id").map(|value| value.as_str().to_string()), Some("main".to_string()));
2046        Ok(())
2047    }
2048
2049    #[test]
2050    fn map_assignment_accepts_string_concat_key() -> anyhow::Result<()> {
2051        let vm = Vm::with_all()?;
2052        vm.import_code(
2053            "vm_string_concat_map_key",
2054            br##"
2055            pub fn write_action(action_map, panel_id, action_id, action) {
2056                action_map[panel_id + "#" + action_id] = action;
2057                action_map[panel_id + "#" + action_id]
2058            }
2059            "##
2060            .to_vec(),
2061        )?;
2062
2063        let compiled = vm.get_fn("vm_string_concat_map_key::write_action", &[Type::Any, Type::Any, Type::Any, Type::Any])?;
2064        let write_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2065        let action_map = dynamic::map!();
2066        let panel_id: Dynamic = "panel".into();
2067        let action_id: Dynamic = "open".into();
2068        let action = dynamic::map!("id"=> "open");
2069
2070        let result = unsafe { &*write_action(&action_map, &panel_id, &action_id, &action) };
2071
2072        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2073        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()));
2074        Ok(())
2075    }
2076
2077    #[test]
2078    fn map_get_key_accepts_string_concat_key_variable() -> anyhow::Result<()> {
2079        let vm = Vm::with_all()?;
2080        vm.import_code(
2081            "vm_get_key_string_concat_key",
2082            br##"
2083            pub fn read_action(action_map, panel_id, action_id) {
2084                let action_key = panel_id + "#" + action_id;
2085                action_map.get_key(action_key)
2086            }
2087            "##
2088            .to_vec(),
2089        )?;
2090
2091        let compiled = vm.get_fn("vm_get_key_string_concat_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
2092        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2093        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2094        let panel_id: Dynamic = "panel".into();
2095        let action_id: Dynamic = "open".into();
2096
2097        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
2098
2099        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2100        Ok(())
2101    }
2102
2103    #[test]
2104    fn map_get_key_accepts_helper_string_key() -> anyhow::Result<()> {
2105        let vm = Vm::with_all()?;
2106        vm.import_code(
2107            "vm_get_key_helper_string_key",
2108            br##"
2109            pub fn make_action_key(panel_id, action_id) {
2110                panel_id + "#" + action_id
2111            }
2112
2113            pub fn read_action(action_map, panel_id, action_id) {
2114                let action_key = make_action_key(panel_id, action_id);
2115                let action = action_map.get_key(action_key);
2116                action
2117            }
2118            "##
2119            .to_vec(),
2120        )?;
2121
2122        let compiled = vm.get_fn("vm_get_key_helper_string_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
2123        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2124        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2125        let panel_id: Dynamic = "panel".into();
2126        let action_id: Dynamic = "open".into();
2127
2128        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
2129
2130        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2131        Ok(())
2132    }
2133
2134    #[test]
2135    fn map_del_key_removes_string_key_and_returns_removed_value() -> anyhow::Result<()> {
2136        let vm = Vm::with_all()?;
2137        vm.import_code(
2138            "vm_del_key_string_key",
2139            br##"
2140            pub fn remove_action(action_map, panel_id, action_id) {
2141                let action_key = panel_id + "#" + action_id;
2142                let removed = action_map.del_key(action_key);
2143                [removed, action_map.get_key(action_key)]
2144            }
2145            "##
2146            .to_vec(),
2147        )?;
2148
2149        let compiled = vm.get_fn("vm_del_key_string_key::remove_action", &[Type::Any, Type::Any, Type::Any])?;
2150        let remove_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2151        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2152        let panel_id: Dynamic = "panel".into();
2153        let action_id: Dynamic = "open".into();
2154
2155        let result = unsafe { &*remove_action(&action_map, &panel_id, &action_id) };
2156
2157        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("id")).map(|value| value.as_str().to_string()), Some("open".to_string()));
2158        assert!(result.get_idx(1).is_some_and(|value| value.is_null()));
2159        assert!(action_map.get_dynamic("panel#open").is_none());
2160        Ok(())
2161    }
2162
2163    #[test]
2164    fn dynamic_field_value_participates_in_or_expression() -> anyhow::Result<()> {
2165        let vm = Vm::with_all()?;
2166        vm.import_code(
2167            "vm_dynamic_field_or",
2168            r#"
2169            pub fn direct_next() {
2170                let choice = {
2171                    label: "颜色",
2172                    next: "color"
2173                };
2174                choice.next
2175            }
2176
2177            pub fn bracket_next() {
2178                let choice = {
2179                    label: "颜色",
2180                    next: "color"
2181                };
2182                choice["next"]
2183            }
2184            "#
2185            .as_bytes()
2186            .to_vec(),
2187        )?;
2188
2189        let compiled = vm.get_fn("vm_dynamic_field_or::direct_next", &[])?;
2190        assert_eq!(compiled.ret_ty(), &Type::Any);
2191        let direct_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2192        assert_eq!(unsafe { &*direct_next() }.as_str(), "color");
2193
2194        let compiled = vm.get_fn("vm_dynamic_field_or::bracket_next", &[])?;
2195        assert_eq!(compiled.ret_ty(), &Type::Any);
2196        let bracket_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2197        assert_eq!(unsafe { &*bracket_next() }.as_str(), "color");
2198        Ok(())
2199    }
2200
2201    #[test]
2202    fn empty_object_literal_in_if_branch_stays_dynamic() -> anyhow::Result<()> {
2203        let vm = Vm::with_all()?;
2204        vm.import_code(
2205            "vm_if_empty_object_branch",
2206            r#"
2207            pub fn first_note(steps) {
2208                let first = if steps.len() > 0 { steps[0] } else { {} };
2209                let first_note = if first.contains("note") { first.note } else { "fallback" };
2210                first_note
2211            }
2212
2213            pub fn first_ja(steps) {
2214                let first = if steps.len() > 0 { steps[0] } else { {} };
2215                if first.contains("ja") { first.ja } else { "すみません" }
2216            }
2217
2218            pub fn assign_first_note(steps) {
2219                let first = {};
2220                first = if steps.len() > 0 { steps[0] } else { {} };
2221                if first.contains("note") { first.note } else { "fallback" }
2222            }
2223            "#
2224            .as_bytes()
2225            .to_vec(),
2226        )?;
2227
2228        let compiled = vm.get_fn("vm_if_empty_object_branch::first_note", &[Type::Any])?;
2229        assert_eq!(compiled.ret_ty(), &Type::Str);
2230        let first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2231
2232        let empty_steps = Dynamic::list(Vec::new());
2233        assert_eq!(unsafe { &*first_note(&empty_steps) }.as_str(), "fallback");
2234
2235        let mut step = std::collections::BTreeMap::new();
2236        step.insert("note".into(), "hello".into());
2237        let steps = Dynamic::list(vec![Dynamic::map(step)]);
2238        assert_eq!(unsafe { &*first_note(&steps) }.as_str(), "hello");
2239
2240        let compiled = vm.get_fn("vm_if_empty_object_branch::first_ja", &[Type::Any])?;
2241        assert_eq!(compiled.ret_ty(), &Type::Any);
2242        let first_ja: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2243        assert_eq!(unsafe { &*first_ja(&empty_steps) }.as_str(), "すみません");
2244
2245        let compiled = vm.get_fn("vm_if_empty_object_branch::assign_first_note", &[Type::Any])?;
2246        assert_eq!(compiled.ret_ty(), &Type::Any);
2247        let assign_first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2248        assert_eq!(unsafe { &*assign_first_note(&empty_steps) }.as_str(), "fallback");
2249        assert_eq!(unsafe { &*assign_first_note(&steps) }.as_str(), "hello");
2250        Ok(())
2251    }
2252
2253    #[test]
2254    fn list_literal_can_be_function_tail_expression() -> anyhow::Result<()> {
2255        let vm = Vm::with_all()?;
2256        vm.import_code(
2257            "vm_tail_list_literal",
2258            r#"
2259            pub fn numbers() {
2260                [1, 2, 3]
2261            }
2262
2263            pub fn maps() {
2264                [
2265                    {note: "first"},
2266                    {note: "second"}
2267                ]
2268            }
2269
2270            pub fn object_with_maps() {
2271                {
2272                    steps: [
2273                        {note: "first"},
2274                        {note: "second"}
2275                    ]
2276                }
2277            }
2278
2279            pub fn return_maps() {
2280                return [
2281                    {note: "first"},
2282                    {note: "second"}
2283                ];
2284            }
2285
2286            pub fn return_maps_without_semicolon() {
2287                return [
2288                    {note: "first"},
2289                    {note: "second"}
2290                ]
2291            }
2292
2293            pub fn tail_bare_variable() {
2294                let value = [
2295                    {note: "first"},
2296                    {note: "second"}
2297                ];
2298                value
2299            }
2300
2301            pub fn return_bare_variable_without_semicolon() {
2302                let value = [
2303                    {note: "first"},
2304                    {note: "second"}
2305                ];
2306                return value
2307            }
2308
2309            pub fn tail_object_variable() {
2310                let result = {
2311                    steps: [
2312                        {note: "first"},
2313                        {note: "second"}
2314                    ]
2315                };
2316                result
2317            }
2318            "#
2319            .as_bytes()
2320            .to_vec(),
2321        )?;
2322
2323        let compiled = vm.get_fn("vm_tail_list_literal::numbers", &[])?;
2324        assert_eq!(compiled.ret_ty(), &Type::Any);
2325        let numbers: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2326        let result = unsafe { &*numbers() };
2327        assert_eq!(result.len(), 3);
2328        assert_eq!(result.get_idx(1).and_then(|value| value.as_int()), Some(2));
2329
2330        let compiled = vm.get_fn("vm_tail_list_literal::maps", &[])?;
2331        assert_eq!(compiled.ret_ty(), &Type::Any);
2332        let maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2333        let result = unsafe { &*maps() };
2334        assert_eq!(result.len(), 2);
2335        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2336
2337        let compiled = vm.get_fn("vm_tail_list_literal::object_with_maps", &[])?;
2338        assert_eq!(compiled.ret_ty(), &Type::Any);
2339        let object_with_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2340        let result = unsafe { &*object_with_maps() };
2341        let steps = result.get_dynamic("steps").expect("steps");
2342        assert_eq!(steps.len(), 2);
2343        assert_eq!(steps.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
2344
2345        let compiled = vm.get_fn("vm_tail_list_literal::return_maps", &[])?;
2346        assert_eq!(compiled.ret_ty(), &Type::Any);
2347        let return_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2348        let result = unsafe { &*return_maps() };
2349        assert_eq!(result.len(), 2);
2350        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2351
2352        let compiled = vm.get_fn("vm_tail_list_literal::return_maps_without_semicolon", &[])?;
2353        assert_eq!(compiled.ret_ty(), &Type::Any);
2354        let return_maps_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2355        let result = unsafe { &*return_maps_without_semicolon() };
2356        assert_eq!(result.len(), 2);
2357        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
2358
2359        let compiled = vm.get_fn("vm_tail_list_literal::tail_bare_variable", &[])?;
2360        assert_eq!(compiled.ret_ty(), &Type::Any);
2361        let tail_bare_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2362        let result = unsafe { &*tail_bare_variable() };
2363        assert_eq!(result.len(), 2);
2364        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2365
2366        let compiled = vm.get_fn("vm_tail_list_literal::return_bare_variable_without_semicolon", &[])?;
2367        assert_eq!(compiled.ret_ty(), &Type::Any);
2368        let return_bare_variable_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2369        let result = unsafe { &*return_bare_variable_without_semicolon() };
2370        assert_eq!(result.len(), 2);
2371        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
2372
2373        let compiled = vm.get_fn("vm_tail_list_literal::tail_object_variable", &[])?;
2374        assert_eq!(compiled.ret_ty(), &Type::Any);
2375        let tail_object_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2376        let result = unsafe { &*tail_object_variable() };
2377        let steps = result.get_dynamic("steps").expect("steps");
2378        assert_eq!(steps.len(), 2);
2379        assert_eq!(steps.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2380        Ok(())
2381    }
2382
2383    #[test]
2384    fn list_return_value_supports_get_idx_method_call() -> anyhow::Result<()> {
2385        let vm = Vm::with_all()?;
2386        vm.import_code(
2387            "vm_returned_list_get_idx",
2388            r#"
2389            pub fn ids() {
2390                [
2391                    "base",
2392                    "2",
2393                    "3"
2394                ]
2395            }
2396
2397            pub fn combinations() {
2398                let result = [];
2399                let values = ids();
2400                let idx = 0;
2401                while idx < values.len() {
2402                    result.push(values.get_idx(idx));
2403                    idx = idx + 1;
2404                }
2405                result
2406            }
2407            "#
2408            .as_bytes()
2409            .to_vec(),
2410        )?;
2411
2412        let compiled = vm.get_fn("vm_returned_list_get_idx::combinations", &[])?;
2413        assert_eq!(compiled.ret_ty(), &Type::Any);
2414        let combinations: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2415        let result = unsafe { &*combinations() };
2416
2417        assert_eq!(result.len(), 3);
2418        assert_eq!(result.get_idx(0).map(|value| value.as_str().to_string()), Some("base".to_string()));
2419        assert_eq!(result.get_idx(2).map(|value| value.as_str().to_string()), Some("3".to_string()));
2420        Ok(())
2421    }
2422
2423    #[test]
2424    fn repeated_deep_step_literals_import_successfully() -> anyhow::Result<()> {
2425        fn extra_page_literal(depth: usize) -> String {
2426            let mut value = "{leaf: \"done\"}".to_string();
2427            for idx in 0..depth {
2428                value = format!("{{kind: \"page\", idx: {idx}, children: [{value}], meta: {{title: \"extra\", visible: true}}}}");
2429            }
2430            value
2431        }
2432
2433        let extra = extra_page_literal(48);
2434        let code = format!(
2435            r#"
2436            pub fn script() {{
2437                return [
2438                    {{ja: "一つ目", note: "first", extra: {extra}}},
2439                    {{ja: "二つ目", note: "second", extra: {extra}}},
2440                    {{ja: "三つ目", note: "third", extra: {extra}}}
2441                ]
2442            }}
2443            "#
2444        );
2445
2446        let vm = Vm::with_all()?;
2447        vm.import_code("vm_repeated_deep_step_literals", code.into_bytes())?;
2448        let compiled = vm.get_fn("vm_repeated_deep_step_literals::script", &[])?;
2449        assert_eq!(compiled.ret_ty(), &Type::Any);
2450        let script: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2451        let result = unsafe { &*script() };
2452        assert_eq!(result.len(), 3);
2453        assert_eq!(result.get_idx(2).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("third".to_string()));
2454        Ok(())
2455    }
2456
2457    #[test]
2458    fn native_import_uses_owning_vm() -> anyhow::Result<()> {
2459        let module_path = std::env::temp_dir().join(format!("zust_vm_import_owner_{}.zs", std::process::id()));
2460        std::fs::write(&module_path, "pub fn value() { 41 }")?;
2461        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
2462
2463        let vm1 = Vm::with_all()?;
2464        vm1.import_code(
2465            "vm_import_owner",
2466            format!(
2467                r#"
2468                pub fn run() {{
2469                    import("vm_imported_owner", "{module_path}");
2470                }}
2471                "#
2472            )
2473            .into_bytes(),
2474        )?;
2475        let compiled = vm1.get_fn("vm_import_owner::run", &[])?;
2476
2477        let vm2 = Vm::with_all()?;
2478        vm2.import_code("vm_import_other", b"pub fn run() { 0 }".to_vec())?;
2479        let _ = vm2.get_fn("vm_import_other::run", &[])?;
2480
2481        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
2482        run();
2483
2484        assert!(vm1.get_fn("vm_imported_owner::value", &[]).is_ok());
2485        assert!(vm2.get_fn("vm_imported_owner::value", &[]).is_err());
2486        Ok(())
2487    }
2488
2489    #[test]
2490    fn object_last_field_call_does_not_need_trailing_comma() -> anyhow::Result<()> {
2491        let vm = Vm::with_all()?;
2492        vm.import_code(
2493            "vm_object_last_call_field",
2494            r#"
2495            pub fn extra_page() {
2496                {
2497                    title: "extra",
2498                    pages: [
2499                        {note: "nested"}
2500                    ]
2501                }
2502            }
2503
2504            pub fn data() {
2505                return [
2506                    {
2507                        note: "first",
2508                        choices: ["a", "b"],
2509                        extras: extra_page()
2510                    },
2511                    {
2512                        note: "second",
2513                        choices: ["c"],
2514                        extras: extra_page()
2515                    }
2516                ]
2517            }
2518            "#
2519            .as_bytes()
2520            .to_vec(),
2521        )?;
2522
2523        let compiled = vm.get_fn("vm_object_last_call_field::data", &[])?;
2524        assert_eq!(compiled.ret_ty(), &Type::Any);
2525        let data: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2526        let result = unsafe { &*data() };
2527        assert_eq!(result.len(), 2);
2528        let first = result.get_idx(0).expect("first step");
2529        assert_eq!(first.get_dynamic("extras").and_then(|extras| extras.get_dynamic("title")).map(|title| title.as_str().to_string()), Some("extra".to_string()));
2530        Ok(())
2531    }
2532
2533    #[test]
2534    fn string_return_survives_scope_exit() -> anyhow::Result<()> {
2535        let vm = Vm::with_all()?;
2536        vm.import_code(
2537            "vm_string_return_scope",
2538            r#"
2539            pub fn source_root() {
2540                "../assets/character/男主角换装"
2541            }
2542
2543            pub fn binary_root() {
2544                "character_binary/男主角换装"
2545            }
2546
2547            pub fn runtime_binary_url() {
2548                "/" + binary_root()
2549            }
2550
2551            pub fn action_groups() {
2552                let root = source_root();
2553                let binary_url = runtime_binary_url();
2554                let binary_root = binary_root();
2555                [
2556                    {
2557                        id: "field_bottom",
2558                        source_spine: root + "/战斗外/boy_b.spine",
2559                        skeleton: binary_url + "/战斗外/boy_b/boy_b.skel.bytes",
2560                        export_skeleton: binary_root + "/战斗外/boy_b/boy_b.skel.bytes"
2561                    }
2562                ]
2563            }
2564            "#
2565            .as_bytes()
2566            .to_vec(),
2567        )?;
2568
2569        let compiled = vm.get_fn("vm_string_return_scope::source_root", &[])?;
2570        assert_eq!(compiled.ret_ty(), &Type::Str);
2571        let source_root: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2572        let source_root = unsafe { &*source_root() };
2573        assert_eq!(source_root.as_str(), "../assets/character/男主角换装");
2574
2575        let compiled = vm.get_fn("vm_string_return_scope::action_groups", &[])?;
2576        assert_eq!(compiled.ret_ty(), &Type::Any);
2577        let action_groups: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2578        let groups = unsafe { &*action_groups() };
2579        let first = groups.get_idx(0).expect("first action group");
2580        assert_eq!(first.get_dynamic("source_spine").map(|value| value.as_str().to_string()), Some("../assets/character/男主角换装/战斗外/boy_b.spine".to_string()));
2581        assert_eq!(first.get_dynamic("skeleton").map(|value| value.as_str().to_string()), Some("/character_binary/男主角换装/战斗外/boy_b/boy_b.skel.bytes".to_string()));
2582        Ok(())
2583    }
2584
2585    #[test]
2586    fn dynamic_string_add_uses_any_binary_fast_path() -> anyhow::Result<()> {
2587        let vm = Vm::with_all()?;
2588        vm.import_code(
2589            "vm_dynamic_string_add",
2590            br#"
2591            pub fn concat(left, right) {
2592                left + right
2593            }
2594            "#
2595            .to_vec(),
2596        )?;
2597
2598        let compiled = vm.get_fn("vm_dynamic_string_add::concat", &[Type::Any, Type::Any])?;
2599        assert_eq!(compiled.ret_ty(), &Type::Any);
2600        let concat: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2601        let left = Dynamic::from("hello");
2602        let right = Dynamic::from(" world");
2603        let result = unsafe { &*concat(&left, &right) };
2604        assert_eq!(result.as_str(), "hello world");
2605        Ok(())
2606    }
2607
2608    #[test]
2609    fn large_dynamic_object_accepts_inline_call_fields() -> anyhow::Result<()> {
2610        let vm = Vm::with_all()?;
2611        let model_count = 180;
2612        let combination_count = 90;
2613        let models = (0..model_count)
2614            .map(|idx| {
2615                format!(
2616                    r#"{{id: "model_{idx}", name: "模型_{idx}", source: "/美术资源/角色/少年/套装_{idx}/模型_{idx}.model.json", parts: [
2617                        {{slot: "hair", path: "/模型/头发/颜色_{idx}/默认.png", z: 10}},
2618                        {{slot: "body", path: "/模型/身体/套装_{idx}/默认.png", z: 1}},
2619                        {{slot: "face", path: "/模型/表情/表情_{idx}/默认.png", z: 20}}
2620                    ]}}"#
2621                )
2622            })
2623            .collect::<Vec<_>>()
2624            .join(",\n");
2625        let combinations = (0..combination_count).map(|idx| format!(r#"{{hair: "color_{idx}", body: "set_{idx}", face: "face_{idx}"}}"#)).collect::<Vec<_>>().join(",\n");
2626        let code = format!(
2627            r#"
2628            pub fn source_root() {{
2629                "/美术资源/角色/少年/默认"
2630            }}
2631
2632            pub fn runtime_boy_url() {{
2633                "/cdn/runtime/角色/少年/少年.model.json"
2634            }}
2635
2636            pub fn parts() {{
2637                [
2638                    {{id: "hair", path: "/模型/头发/黑色/默认.png", z: 10}},
2639                    {{id: "body", path: "/模型/身体/校服/默认.png", z: 1}},
2640                    {{id: "face", path: "/模型/表情/微笑/默认.png", z: 20}}
2641                ]
2642            }}
2643
2644            pub fn action_groups() {{
2645                {{
2646                    idle: [
2647                        {{id: "stand", name: "站立", frames: ["待机/0001.png", "待机/0002.png"]}},
2648                        {{id: "blink", name: "眨眼", frames: ["表情/眨眼/0001.png", "表情/眨眼/0002.png"]}}
2649                    ],
2650                    move: [
2651                        {{id: "walk", name: "行走", frames: ["行走/0001.png", "行走/0002.png"]}},
2652                        {{id: "run", name: "奔跑", frames: ["奔跑/0001.png", "奔跑/0002.png"]}}
2653                    ]
2654                }}
2655            }}
2656
2657            pub fn default_model() {{
2658                {{
2659                    id: "runtime_boy",
2660                    name: "运行时少年",
2661                    skins: [
2662                        {{id: "school", title: "校服", source: "/套装/校服/model.json"}},
2663                        {{id: "casual", title: "便服", source: "/套装/便服/model.json"}}
2664                    ],
2665                    models: [
2666                        {models}
2667                    ]
2668                }}
2669            }}
2670
2671            pub fn first_nine_combinations() {{
2672                [
2673                    {combinations}
2674                ]
2675            }}
2676
2677            pub fn config() {{
2678                {{
2679                    source_root: source_root(),
2680                    runtime_boy_url: runtime_boy_url(),
2681                    parts: parts(),
2682                    action_groups: action_groups(),
2683                    default_model: default_model(),
2684                    first_nine_combinations: first_nine_combinations()
2685                }}
2686            }}
2687
2688            pub fn start() {{
2689                root::add("local/vm_large_inline_call_object/config", {{
2690                    source_root: source_root(),
2691                    runtime_boy_url: runtime_boy_url(),
2692                    parts: parts(),
2693                    action_groups: action_groups(),
2694                    default_model: default_model(),
2695                    first_nine_combinations: first_nine_combinations()
2696                }})
2697            }}
2698            "#
2699        );
2700        vm.import_code("vm_large_inline_call_object", code.into_bytes())?;
2701
2702        let compiled = vm.get_fn("vm_large_inline_call_object::config", &[])?;
2703        assert_eq!(compiled.ret_ty(), &Type::Any);
2704        let config: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2705        let result = unsafe { &*config() };
2706        assert_eq!(result.get_dynamic("source_root").map(|value| value.as_str().to_string()), Some("/美术资源/角色/少年/默认".to_string()));
2707        assert_eq!(result.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
2708
2709        let compiled = vm.get_fn("vm_large_inline_call_object::start", &[])?;
2710        assert_eq!(compiled.ret_ty(), &Type::Bool);
2711        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2712        assert!(start());
2713        let saved = root::get("local/vm_large_inline_call_object/config")?;
2714        assert_eq!(saved.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
2715        Ok(())
2716    }
2717
2718    #[test]
2719    fn http_serve_accepts_inline_config_map() -> anyhow::Result<()> {
2720        let vm = Vm::with_all()?;
2721        vm.import_code(
2722            "vm_http_serve_inline_config",
2723            br#"
2724            pub fn start() {
2725                let server = http::serve({host: "127.0.0.1:5192"});
2726                server
2727            }
2728            "#
2729            .to_vec(),
2730        )?;
2731
2732        let compiled = vm.get_fn("vm_http_serve_inline_config::start", &[])?;
2733        assert_eq!(compiled.ret_ty(), &Type::Any);
2734        Ok(())
2735    }
2736
2737    #[test]
2738    fn http_serve_accepts_variable_and_quoted_static_key() -> anyhow::Result<()> {
2739        let vm = Vm::with_all()?;
2740        vm.import_code(
2741            "vm_http_serve_quoted_static",
2742            br#"
2743            pub fn start(server_addr) {
2744                let http_server = http::serve({
2745                    host: server_addr,
2746                    ws: true,
2747                    upload: "upload",
2748                    "static": {
2749                        path: "/",
2750                        dir: "public/local"
2751                    }
2752                });
2753                http_server
2754            }
2755            "#
2756            .to_vec(),
2757        )?;
2758
2759        let compiled = vm.get_fn("vm_http_serve_quoted_static::start", &[Type::Any])?;
2760        assert_eq!(compiled.ret_ty(), &Type::Any);
2761        Ok(())
2762    }
2763
2764    #[test]
2765    fn oss_helpers_accept_explicit_config() -> anyhow::Result<()> {
2766        let vm = Vm::with_all()?;
2767        vm.import_code(
2768            "vm_oss_explicit_config",
2769            br#"
2770            pub fn upload(oss, bytes) {
2771                oss::upload(oss, "llm/input/audio.wav", bytes)
2772            }
2773
2774            pub fn http_upload(oss, bytes) {
2775                http::upload(oss, "uploads/input.bin", bytes)
2776            }
2777
2778            pub fn link(oss, uploaded) {
2779                oss::signed_url(oss, {oss_url: uploaded, expires: 3600})
2780            }
2781            "#
2782            .to_vec(),
2783        )?;
2784
2785        assert_eq!(vm.get_fn("vm_oss_explicit_config::upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
2786        assert_eq!(vm.get_fn("vm_oss_explicit_config::http_upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
2787        assert_eq!(vm.get_fn("vm_oss_explicit_config::link", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
2788        Ok(())
2789    }
2790
2791    #[test]
2792    fn load_script_accepts_http_serve_inline_config() -> anyhow::Result<()> {
2793        let vm = Vm::with_all()?;
2794        let (_fn_ptr, ty) = vm.load(
2795            br#"
2796            let server_addr = "127.0.0.1:5192";
2797            let http_server = http::serve({
2798                host: server_addr,
2799                ws: true,
2800                upload: "upload",
2801                "static": {
2802                    path: "/",
2803                    dir: "public/local"
2804                }
2805            });
2806            http_server
2807            "#
2808            .to_vec(),
2809            "arg".into(),
2810        )?;
2811
2812        assert_eq!(ty, Type::Any);
2813        Ok(())
2814    }
2815
2816    #[test]
2817    fn load_script_resolves_import_before_compile() -> anyhow::Result<()> {
2818        let module_path = std::env::temp_dir().join(format!("zust_vm_load_import_{}.zs", std::process::id()));
2819        std::fs::write(&module_path, "pub fn init() { return {ok: true}; }")?;
2820        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
2821
2822        let vm = Vm::with_all()?;
2823        let (_fn_ptr, ty) = vm.load(
2824            format!(
2825                r#"
2826                import("create_scene", "{module_path}");
2827                create_scene::init();
2828                "#
2829            )
2830            .into_bytes(),
2831            "req".into(),
2832        )?;
2833
2834        assert_eq!(ty, Type::Void);
2835        Ok(())
2836    }
2837
2838    #[test]
2839    fn gpu_struct_layout_packs_and_unpacks_dynamic_maps() -> anyhow::Result<()> {
2840        let vm = Vm::with_all()?;
2841        vm.import_code(
2842            "vm_gpu_layout",
2843            br#"
2844            pub struct Params {
2845                a: u32,
2846                b: u32,
2847                c: u32,
2848            }
2849            "#
2850            .to_vec(),
2851        )?;
2852
2853        let layout = vm.gpu_struct_layout("vm_gpu_layout::Params", &[])?;
2854        assert_eq!(layout.size, 16);
2855        assert_eq!(layout.fields.iter().map(|field| (field.name.as_str(), field.offset)).collect::<Vec<_>>(), vec![("a", 0), ("b", 4), ("c", 8)]);
2856
2857        let value = dynamic::map!("a"=> 1u32, "b"=> 2u32, "c"=> 3u32);
2858        let bytes = layout.pack_map(&value)?;
2859        assert_eq!(bytes.len(), 16);
2860        assert_eq!(&bytes[0..4], &1u32.to_ne_bytes());
2861        assert_eq!(&bytes[4..8], &2u32.to_ne_bytes());
2862        assert_eq!(&bytes[8..12], &3u32.to_ne_bytes());
2863
2864        let read = layout.unpack_map(&bytes)?;
2865        assert_eq!(read.get_dynamic("a").and_then(|value| value.as_uint()), Some(1));
2866        assert_eq!(read.get_dynamic("b").and_then(|value| value.as_uint()), Some(2));
2867        assert_eq!(read.get_dynamic("c").and_then(|value| value.as_uint()), Some(3));
2868        Ok(())
2869    }
2870
2871    #[test]
2872    fn root_native_calls_do_not_take_ownership_of_dynamic_args() -> anyhow::Result<()> {
2873        let vm = Vm::with_all()?;
2874        vm.import_code(
2875            "vm_root_clone_bridge",
2876            br#"
2877            pub fn add_then_reuse(arg) {
2878                let user = {
2879                    address: "test-wallet",
2880                    points: 20
2881                };
2882                root::add("local/root-clone-bridge-user", user);
2883                user.points = user.points - 7;
2884                root::add("local/root-clone-bridge-user", user);
2885                {
2886                    user: user,
2887                    points: user.points
2888                }
2889            }
2890
2891            pub fn clone_then_mutate(arg) {
2892                let user = {
2893                    profile: {
2894                        points: 20
2895                    }
2896                };
2897                let copied = user.clone();
2898                copied.profile.points = 13;
2899                user
2900            }
2901            "#
2902            .to_vec(),
2903        )?;
2904
2905        let compiled = vm.get_fn("vm_root_clone_bridge::add_then_reuse", &[Type::Any])?;
2906        assert_eq!(compiled.ret_ty(), &Type::Any);
2907        let add_then_reuse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2908        let arg = Dynamic::Null;
2909        let result = add_then_reuse(&arg);
2910        let result = unsafe { &*result };
2911
2912        assert_eq!(result.get_dynamic("points").and_then(|value| value.as_int()), Some(13));
2913        let mut json = String::new();
2914        result.to_json(&mut json);
2915        assert!(json.contains("\"points\": 13"));
2916
2917        let clone_then_mutate = vm.get_fn("vm_root_clone_bridge::clone_then_mutate", &[Type::Any])?;
2918        let clone_then_mutate: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(clone_then_mutate.ptr()) };
2919        let result = clone_then_mutate(&arg);
2920        let result = unsafe { &*result };
2921        assert_eq!(result.get_dynamic("profile").unwrap().get_dynamic("points").and_then(|value| value.as_int()), Some(20));
2922        Ok(())
2923    }
2924
2925    struct CounterForTypedReceiver {
2926        value: i64,
2927    }
2928
2929    extern "C" fn counter_for_typed_receiver_get(value: *const Dynamic) -> i64 {
2930        unsafe { &*value }.as_custom::<CounterForTypedReceiver>().map(|counter| counter.value).unwrap_or(-1)
2931    }
2932
2933    struct NavMapForFunctionArg;
2934
2935    extern "C" fn nav_map_for_function_arg_new() -> *const Dynamic {
2936        Box::into_raw(Box::new(Dynamic::custom(NavMapForFunctionArg)))
2937    }
2938
2939    #[derive(Debug, Default)]
2940    struct PropertyForwardingObject {
2941        values: RwLock<BTreeMap<String, Dynamic>>,
2942    }
2943
2944    impl CustomProperty for PropertyForwardingObject {
2945        fn get_key(&self, key: &str) -> Option<Dynamic> {
2946            self.values.read().unwrap().get(key).cloned()
2947        }
2948
2949        fn set_key(&self, key: &str, value: Dynamic) -> bool {
2950            self.values.write().unwrap().insert(key.to_string(), value);
2951            true
2952        }
2953    }
2954
2955    extern "C" fn property_forwarding_object_new() -> *const Dynamic {
2956        Box::into_raw(Box::new(Dynamic::custom_with_properties(PropertyForwardingObject::default())))
2957    }
2958
2959    #[test]
2960    fn typed_receiver_method_call_dispatches_with_type_hint() -> anyhow::Result<()> {
2961        let vm = Vm::with_all()?;
2962        vm.add_empty_type("Counter")?;
2963        let counter_ty = vm.get_symbol("Counter", Vec::new())?;
2964        vm.add_native_method_ptr("Counter", "get", &[counter_ty], Type::I64, counter_for_typed_receiver_get as *const u8)?;
2965        vm.import_code(
2966            "vm_typed_receiver_method",
2967            br#"
2968            pub fn run(value) {
2969                value::<Counter>::get()
2970            }
2971            "#
2972            .to_vec(),
2973        )?;
2974
2975        let compiled = vm.get_fn("vm_typed_receiver_method::run", &[Type::Any])?;
2976        assert_eq!(compiled.ret_ty(), &Type::I64);
2977        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
2978        let value = Dynamic::custom(CounterForTypedReceiver { value: 42 });
2979
2980        assert_eq!(run(&value), 42);
2981        Ok(())
2982    }
2983
2984    #[test]
2985    fn native_custom_object_can_be_passed_to_zs_function() -> anyhow::Result<()> {
2986        let vm = Vm::with_all()?;
2987        vm.add_empty_type("NavMap")?;
2988        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
2989        vm.import_code(
2990            "vm_native_custom_arg",
2991            br#"
2992            pub fn add_nav_spawns(world, navmap) {
2993                navmap
2994            }
2995
2996            pub fn run(world) {
2997                let navmap = NavMap::new();
2998                let with_spawns = add_nav_spawns(world, navmap);
2999                with_spawns
3000            }
3001            "#
3002            .to_vec(),
3003        )?;
3004
3005        let compiled = vm.get_fn("vm_native_custom_arg::run", &[Type::Any])?;
3006        assert_eq!(compiled.ret_ty(), &Type::Any);
3007        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3008        let world = Dynamic::Null;
3009        let result = run(&world);
3010        let result = unsafe { &*result };
3011
3012        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
3013        Ok(())
3014    }
3015
3016    #[test]
3017    fn any_field_assignment_forwards_to_custom_properties() -> anyhow::Result<()> {
3018        let vm = Vm::with_all()?;
3019        vm.add_empty_type("Dialog")?;
3020        vm.add_native_method_ptr("Dialog", "new", &[], Type::Any, property_forwarding_object_new as *const u8)?;
3021        vm.import_code(
3022            "vm_custom_property_forwarding",
3023            br#"
3024            pub fn run() {
3025                let dialog = Dialog::new();
3026                dialog.file_mode = 3;
3027                dialog.file_mode
3028            }
3029            "#
3030            .to_vec(),
3031        )?;
3032
3033        let compiled = vm.get_fn("vm_custom_property_forwarding::run", &[])?;
3034        assert_eq!(compiled.ret_ty(), &Type::Any);
3035        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3036        let result = unsafe { &*run() };
3037
3038        assert_eq!(result.as_int(), Some(3));
3039        Ok(())
3040    }
3041
3042    #[test]
3043    fn native_custom_object_typed_local_can_be_passed_to_zs_function() -> anyhow::Result<()> {
3044        let vm = Vm::with_all()?;
3045        vm.add_empty_type("NavMap")?;
3046        let _nav_map_ty = vm.get_symbol("NavMap", Vec::new())?;
3047        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
3048        vm.import_code(
3049            "vm_native_custom_typed_arg",
3050            br#"
3051            pub fn add_nav_spawns(world, navmap) {
3052                navmap
3053            }
3054
3055            pub fn run(world) {
3056                let navmap: NavMap = NavMap::new();
3057                let with_spawns = add_nav_spawns(world, navmap);
3058                with_spawns
3059            }
3060            "#
3061            .to_vec(),
3062        )?;
3063
3064        let compiled = vm.get_fn("vm_native_custom_typed_arg::run", &[Type::Any])?;
3065        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3066        let world = Dynamic::Null;
3067        let result = run(&world);
3068        let result = unsafe { &*result };
3069
3070        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
3071        Ok(())
3072    }
3073
3074    // ---- 新增边界条件测试 ----
3075
3076    #[test]
3077    fn dynamic_type_checks_on_null_and_primitive_values() -> anyhow::Result<()> {
3078        let vm = Vm::with_all()?;
3079        vm.import_code(
3080            "vm_dynamic_type_checks",
3081            br#"
3082            pub fn is_list_on_int() {
3083                let x = 42i64;
3084                x.is_list()
3085            }
3086
3087            pub fn is_map_on_int() {
3088                let x = 42i64;
3089                x.is_map()
3090            }
3091
3092            pub fn is_null_on_int() {
3093                let x = 42i64;
3094                x.is_null()
3095            }
3096            "#
3097            .to_vec(),
3098        )?;
3099
3100        let compiled = vm.get_fn("vm_dynamic_type_checks::is_list_on_int", &[])?;
3101        assert_eq!(compiled.ret_ty(), &Type::Bool);
3102        let is_list_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3103        assert!(!is_list_on_int());
3104
3105        let compiled = vm.get_fn("vm_dynamic_type_checks::is_map_on_int", &[])?;
3106        assert_eq!(compiled.ret_ty(), &Type::Bool);
3107        let is_map_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3108        assert!(!is_map_on_int());
3109
3110        let compiled = vm.get_fn("vm_dynamic_type_checks::is_null_on_int", &[])?;
3111        assert_eq!(compiled.ret_ty(), &Type::Bool);
3112        let is_null_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3113        assert!(!is_null_on_int());
3114        Ok(())
3115    }
3116
3117    #[test]
3118    fn empty_for_loop_range_has_zero_iterations() -> anyhow::Result<()> {
3119        let vm = Vm::with_all()?;
3120        vm.import_code(
3121            "vm_empty_for_range",
3122            br#"
3123            pub fn empty_exclusive() {
3124                let count = 0i32;
3125                for i in 0..0 {
3126                    count += i;
3127                }
3128                count
3129            }
3130
3131            pub fn single_inclusive_iteration() {
3132                let count = 0i32;
3133                for i in 5..=5 {
3134                    count += i;
3135                }
3136                count
3137            }
3138            "#
3139            .to_vec(),
3140        )?;
3141
3142        let compiled = vm.get_fn("vm_empty_for_range::empty_exclusive", &[])?;
3143        assert_eq!(compiled.ret_ty(), &Type::I32);
3144        let empty_exclusive: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3145        assert_eq!(empty_exclusive(), 0);
3146
3147        let compiled = vm.get_fn("vm_empty_for_range::single_inclusive_iteration", &[])?;
3148        assert_eq!(compiled.ret_ty(), &Type::I32);
3149        let single_inclusive: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3150        assert_eq!(single_inclusive(), 5);
3151        Ok(())
3152    }
3153
3154    #[test]
3155    fn map_contains_key_on_non_existent_and_nested_keys() -> anyhow::Result<()> {
3156        let vm = Vm::with_all()?;
3157        vm.import_code(
3158            "vm_map_contains",
3159            br#"
3160            pub fn contains_existing(data) {
3161                data.contains("name")
3162            }
3163
3164            pub fn contains_missing(data) {
3165                data.contains("nothing")
3166            }
3167            "#
3168            .to_vec(),
3169        )?;
3170
3171        let compiled = vm.get_fn("vm_map_contains::contains_existing", &[Type::Any])?;
3172        assert_eq!(compiled.ret_ty(), &Type::Bool);
3173        let contains_existing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3174        let data = dynamic::map!("name"=> "test");
3175        assert!(contains_existing(&data));
3176
3177        let compiled = vm.get_fn("vm_map_contains::contains_missing", &[Type::Any])?;
3178        assert_eq!(compiled.ret_ty(), &Type::Bool);
3179        let contains_missing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3180        assert!(!contains_missing(&data));
3181        Ok(())
3182    }
3183
3184    #[test]
3185    fn list_pop_on_empty_list_returns_null() -> anyhow::Result<()> {
3186        let vm = Vm::with_all()?;
3187        vm.import_code(
3188            "vm_pop_empty",
3189            br#"
3190            pub fn pop_new_list() {
3191                let items = [];
3192                let value = items.pop();
3193                let still_empty = items.len() == 0;
3194                {value: value, empty: still_empty}
3195            }
3196
3197            pub fn pop_until_empty() {
3198                let items = [1i64, 2i64];
3199                items.pop();
3200                let last = items.pop();
3201                let drained = items.pop();
3202                {last: last, drained: drained}
3203            }
3204            "#
3205            .to_vec(),
3206        )?;
3207
3208        let compiled = vm.get_fn("vm_pop_empty::pop_new_list", &[])?;
3209        assert_eq!(compiled.ret_ty(), &Type::Any);
3210        let pop_new_list: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3211        let result = unsafe { &*pop_new_list() };
3212        assert!(result.get_dynamic("value").is_some_and(|v| v.is_null()));
3213        assert_eq!(result.get_dynamic("empty").and_then(|v| v.as_bool()), Some(true));
3214
3215        let compiled = vm.get_fn("vm_pop_empty::pop_until_empty", &[])?;
3216        assert_eq!(compiled.ret_ty(), &Type::Any);
3217        let pop_until_empty: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3218        let result = unsafe { &*pop_until_empty() };
3219        assert_eq!(result.get_dynamic("last").and_then(|v| v.as_int()), Some(1));
3220        assert!(result.get_dynamic("drained").is_some_and(|v| v.is_null()));
3221        Ok(())
3222    }
3223
3224    #[test]
3225    fn void_function_with_multiple_code_paths() -> anyhow::Result<()> {
3226        let vm = Vm::with_all()?;
3227        vm.import_code(
3228            "vm_void_multi_path",
3229            br#"
3230            pub fn log_if_positive(value: i64) {
3231                if value > 0 {
3232                    print(value);
3233                    return;
3234                }
3235                if value < 0 {
3236                    print(-value);
3237                    return;
3238                }
3239                print(0);
3240            }
3241            "#
3242            .to_vec(),
3243        )?;
3244
3245        let compiled = vm.get_fn("vm_void_multi_path::log_if_positive", &[Type::I64])?;
3246        assert!(compiled.ret_ty().is_void());
3247        Ok(())
3248    }
3249
3250    #[test]
3251    fn any_method_call_chain_on_returned_dynamic_value() -> anyhow::Result<()> {
3252        let vm = Vm::with_all()?;
3253        vm.import_code(
3254            "vm_any_method_chain",
3255            br#"
3256            pub fn get_tags(data) {
3257                let tags = data.tags;
3258                if tags.is_list() {
3259                    return tags.len();
3260                }
3261                0
3262            }
3263            "#
3264            .to_vec(),
3265        )?;
3266
3267        let compiled = vm.get_fn("vm_any_method_chain::get_tags", &[Type::Any])?;
3268        assert_eq!(compiled.ret_ty(), &Type::I32);
3269        let get_tags: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3270        let data = dynamic::map!("tags"=> Dynamic::list(vec!["a".into(), "b".into(), "c".into()]));
3271        assert_eq!(get_tags(&data), 3);
3272
3273        let empty_data = Dynamic::Null;
3274        assert_eq!(get_tags(&empty_data), 0);
3275        Ok(())
3276    }
3277
3278    #[test]
3279    fn infers_any_arg_function_return_before_body_compile() -> anyhow::Result<()> {
3280        let vm = Vm::with_all()?;
3281        vm.import_code(
3282            "vm_infer_any_arg_return",
3283            br#"
3284            pub fn caller(candidate) {
3285                let center = polygon_center(candidate.visualPolygon);
3286                center[0]
3287            }
3288
3289            pub fn polygon_center(point_list) {
3290                let total_x = 0;
3291                let total_y = 0;
3292                let count = 0;
3293                if point_list.is_list() {
3294                    for point in point_list {
3295                        if point.is_list() && point.len() >= 2 {
3296                            total_x += point[0];
3297                            total_y += point[1];
3298                            count += 1;
3299                        }
3300                    }
3301                }
3302                if count == 0 {
3303                    return [0, 0];
3304                }
3305                [total_x / count, total_y / count]
3306            }
3307            "#
3308            .to_vec(),
3309        )?;
3310
3311        let compiled = vm.get_fn("vm_infer_any_arg_return::caller", &[Type::Any])?;
3312        assert_eq!(compiled.ret_ty(), &Type::Any);
3313        let caller: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3314        let candidate = dynamic::map!(
3315            "visualPolygon"=> Dynamic::list(vec![
3316                Dynamic::list(vec![2i64.into(), 4i64.into()]),
3317                Dynamic::list(vec![6i64.into(), 8i64.into()]),
3318            ])
3319        );
3320        let result = unsafe { &*caller(&candidate) };
3321        assert_eq!(result.as_int(), Some(4));
3322        Ok(())
3323    }
3324
3325    #[test]
3326    fn recursive_factorial_keeps_static_return_type() -> anyhow::Result<()> {
3327        let vm = Vm::with_all()?;
3328        vm.import_code(
3329            "vm_recursive_factorial",
3330            br#"
3331            fn factorial(n: i64) {
3332                if n <= 1 {
3333                    return 1;
3334                }
3335                n * factorial(n - 1)
3336            }
3337
3338            pub fn run(n: i64) {
3339                factorial(n)
3340            }
3341            "#
3342            .to_vec(),
3343        )?;
3344
3345        let compiled = vm.get_fn("vm_recursive_factorial::run", &[Type::I64])?;
3346        assert_eq!(compiled.ret_ty(), &Type::I64);
3347        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3348        assert_eq!(run(5), 120);
3349        Ok(())
3350    }
3351
3352    #[test]
3353    fn explicit_const_generic_function_calls_generate_distinct_variants() -> anyhow::Result<()> {
3354        let vm = Vm::with_all()?;
3355        vm.import_code(
3356            "vm_generic_const_variants",
3357            br#"
3358            fn value<N>() {
3359                N
3360            }
3361
3362            pub fn two() {
3363                value::<2>()
3364            }
3365
3366            pub fn three() {
3367                value::<3>()
3368            }
3369            "#
3370            .to_vec(),
3371        )?;
3372
3373        let compiled = vm.get_fn("vm_generic_const_variants::two", &[])?;
3374        assert_eq!(compiled.ret_ty(), &Type::I32);
3375        let two: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3376        assert_eq!(two(), 2);
3377
3378        let compiled = vm.get_fn("vm_generic_const_variants::three", &[])?;
3379        assert_eq!(compiled.ret_ty(), &Type::I32);
3380        let three: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3381        assert_eq!(three(), 3);
3382        Ok(())
3383    }
3384
3385    #[test]
3386    fn generic_function_body_resolves_private_generic_helper_after_import() -> anyhow::Result<()> {
3387        let vm = Vm::with_all()?;
3388        vm.import_code(
3389            "vm_generic_private_helper",
3390            br#"
3391            fn helper<N>() {
3392                N
3393            }
3394
3395            pub fn bench<N>() {
3396                helper::<N>()
3397            }
3398            "#
3399            .to_vec(),
3400        )?;
3401
3402        let compiled = vm.get_fn_with_params("vm_generic_private_helper::bench", &[], &[Type::ConstInt(7)])?;
3403        assert_eq!(compiled.ret_ty(), &Type::I32);
3404        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3405        assert_eq!(run(), 7);
3406        Ok(())
3407    }
3408
3409    #[test]
3410    fn const_generic_repeat_array_initializes_all_items() -> anyhow::Result<()> {
3411        let vm = Vm::with_all()?;
3412        vm.import_code(
3413            "vm_generic_repeat_array",
3414            br#"
3415            fn bench<N>() {
3416                let is_prime = [true; N];
3417                is_prime[0] = false;
3418                is_prime[1] = false;
3419                let count = 0i64;
3420                for p in 2i64..N {
3421                    if is_prime[p] == true {
3422                        count = count + 1;
3423                        let step = p;
3424                        let j = p * p;
3425                        while j < N {
3426                            is_prime[j] = false;
3427                            j = j + step;
3428                        }
3429                    }
3430                }
3431                count
3432            }
3433
3434            pub fn run() {
3435                bench::<10>()
3436            }
3437
3438            pub fn run_1000() {
3439                bench::<1000>()
3440            }
3441
3442            pub fn run_100000() {
3443                bench::<100000>()
3444            }
3445            "#
3446            .to_vec(),
3447        )?;
3448
3449        let compiled = vm.get_fn("vm_generic_repeat_array::run", &[])?;
3450        assert_eq!(compiled.ret_ty(), &Type::I64);
3451        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3452        assert_eq!(run(), 4);
3453
3454        let compiled = vm.get_fn("vm_generic_repeat_array::run_1000", &[])?;
3455        assert_eq!(compiled.ret_ty(), &Type::I64);
3456        let run_1000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3457        assert_eq!(run_1000(), 168);
3458
3459        let compiled = vm.get_fn("vm_generic_repeat_array::run_100000", &[])?;
3460        assert_eq!(compiled.ret_ty(), &Type::I64);
3461        let run_100000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3462        assert_eq!(run_100000(), 9592);
3463        Ok(())
3464    }
3465
3466    #[test]
3467    fn repeat_array_initializes_scalar_patterns() -> anyhow::Result<()> {
3468        let vm = Vm::with_all()?;
3469        vm.import_code(
3470            "vm_repeat_scalar_patterns",
3471            br#"
3472            pub fn count_true() {
3473                let items = [true; 100000];
3474                let count = 0i64;
3475                for idx in 0i64..100000 {
3476                    if items[idx] == true {
3477                        count = count + 1;
3478                    }
3479                }
3480                count
3481            }
3482
3483            pub fn i32_pair() {
3484                let items = [-7i32; 1000];
3485                items[0i64] + items[999i64]
3486            }
3487
3488            pub fn i64_pair() {
3489                let items = [1234567890123i64; 1000];
3490                items[0i64] + items[999i64]
3491            }
3492
3493            pub fn f64_pair() {
3494                let items = [1.5f64; 1000];
3495                items[0i64] + items[999i64]
3496            }
3497            "#
3498            .to_vec(),
3499        )?;
3500
3501        let compiled = vm.get_fn("vm_repeat_scalar_patterns::count_true", &[])?;
3502        assert_eq!(compiled.ret_ty(), &Type::I64);
3503        let count_true: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3504        assert_eq!(count_true(), 100000);
3505
3506        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i32_pair", &[])?;
3507        assert_eq!(compiled.ret_ty(), &Type::I32);
3508        let i32_pair: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3509        assert_eq!(i32_pair(), -14);
3510
3511        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i64_pair", &[])?;
3512        assert_eq!(compiled.ret_ty(), &Type::I64);
3513        let i64_pair: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3514        assert_eq!(i64_pair(), 2469135780246);
3515
3516        let compiled = vm.get_fn("vm_repeat_scalar_patterns::f64_pair", &[])?;
3517        assert_eq!(compiled.ret_ty(), &Type::F64);
3518        let f64_pair: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
3519        assert_eq!(f64_pair(), 3.0);
3520        Ok(())
3521    }
3522
3523    #[test]
3524    fn bool_array_store_normalizes_condition_values() -> anyhow::Result<()> {
3525        let vm = Vm::with_all()?;
3526        vm.import_code(
3527            "vm_bool_array_store",
3528            br#"
3529            pub fn run() {
3530                let items = [false; 4];
3531                items[1] = 3i64 > 2i64;
3532                items[2] = 3i64 < 2i64;
3533                if items[1] == true && items[2] == false {
3534                    1i64
3535                } else {
3536                    0i64
3537                }
3538            }
3539            "#
3540            .to_vec(),
3541        )?;
3542
3543        let compiled = vm.get_fn("vm_bool_array_store::run", &[])?;
3544        assert_eq!(compiled.ret_ty(), &Type::I64);
3545        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3546        assert_eq!(run(), 1);
3547        Ok(())
3548    }
3549
3550    #[test]
3551    fn bool_array_large_sequential_writes() -> anyhow::Result<()> {
3552        let vm = Vm::with_all()?;
3553        vm.import_code(
3554            "vm_bool_array_large_writes",
3555            br#"
3556            pub fn run() {
3557                let items = [true; 100000];
3558                for idx in 0i64..100000 {
3559                    items[idx] = false;
3560                }
3561                let count = 0i64;
3562                for idx in 0i64..100000 {
3563                    if items[idx] == false {
3564                        count = count + 1;
3565                    }
3566                }
3567                count
3568            }
3569            "#
3570            .to_vec(),
3571        )?;
3572
3573        let compiled = vm.get_fn("vm_bool_array_large_writes::run", &[])?;
3574        assert_eq!(compiled.ret_ty(), &Type::I64);
3575        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3576        assert_eq!(run(), 100000);
3577        Ok(())
3578    }
3579
3580    #[test]
3581    fn bool_array_sieve_style_indices_stay_in_bounds() -> anyhow::Result<()> {
3582        let vm = Vm::with_all()?;
3583        vm.import_code(
3584            "vm_bool_array_sieve_indices",
3585            br#"
3586            pub fn run() {
3587                let items = [true; 100000];
3588                let writes = 0i64;
3589                for p in 2i64..100000 {
3590                    let step = p;
3591                    let j = p * p;
3592                    while j < 100000 {
3593                        items[j] = false;
3594                        writes = writes + 1;
3595                        j = j + step;
3596                    }
3597                }
3598                writes
3599            }
3600            "#
3601            .to_vec(),
3602        )?;
3603
3604        let compiled = vm.get_fn("vm_bool_array_sieve_indices::run", &[])?;
3605        assert_eq!(compiled.ret_ty(), &Type::I64);
3606        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3607        assert!(run() > 0);
3608        Ok(())
3609    }
3610
3611    #[test]
3612    fn sieve_style_indices_compute_in_bounds_without_array_write() -> anyhow::Result<()> {
3613        let vm = Vm::with_all()?;
3614        vm.import_code(
3615            "vm_sieve_indices_no_write",
3616            br#"
3617            pub fn run() {
3618                let max_j = 0i64;
3619                for p in 2i64..100000 {
3620                    let step = p;
3621                    let j = p * p;
3622                    while j < 100000 {
3623                        if j < 0i64 {
3624                            return -1i64;
3625                        }
3626                        if j > max_j {
3627                            max_j = j;
3628                        }
3629                        j = j + step;
3630                    }
3631                }
3632                max_j
3633            }
3634            "#
3635            .to_vec(),
3636        )?;
3637
3638        let compiled = vm.get_fn("vm_sieve_indices_no_write::run", &[])?;
3639        assert_eq!(compiled.ret_ty(), &Type::I64);
3640        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3641        assert_eq!(run(), 99999);
3642        Ok(())
3643    }
3644
3645    #[test]
3646    fn dynamic_list_index_sum_uses_static_accumulator_type() -> anyhow::Result<()> {
3647        let vm = Vm::with_all()?;
3648        vm.import_code(
3649            "vm_dynamic_index_sum",
3650            br#"
3651            pub fn sum_list(n: i64) {
3652                let l = [];
3653                for i in 0..n {
3654                    l.push(i);
3655                }
3656                let sum = 0i64;
3657                for j in 0..n {
3658                    sum = sum + l[j];
3659                }
3660                sum
3661            }
3662            "#
3663            .to_vec(),
3664        )?;
3665
3666        let compiled = vm.get_fn("vm_dynamic_index_sum::sum_list", &[Type::I64])?;
3667        let sum_list_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_dynamic_index_sum::sum_list")?;
3668        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(sum_list_id, &[], &[Type::I64]);
3669        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I64)), "local type hints: {:?}", hints);
3670        assert_eq!(compiled.ret_ty(), &Type::I64);
3671        let sum_list: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3672        assert_eq!(sum_list(1000), 499500);
3673        Ok(())
3674    }
3675
3676    #[test]
3677    fn inferred_empty_list_uses_typed_dynamic_vector() -> anyhow::Result<()> {
3678        let vm = Vm::with_all()?;
3679        vm.import_code(
3680            "vm_inferred_typed_list",
3681            br#"
3682            pub fn make() {
3683                let l = [];
3684                l.push(1i64);
3685                l
3686            }
3687            "#
3688            .to_vec(),
3689        )?;
3690
3691        let compiled = vm.get_fn("vm_inferred_typed_list::make", &[])?;
3692        assert_eq!(compiled.ret_ty(), &Type::Any);
3693        let make: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3694        let result = unsafe { &*make() };
3695        assert!(matches!(result, Dynamic::VecI64(values) if values == &vec![1]), "result: {:?}", result);
3696        Ok(())
3697    }
3698
3699    #[test]
3700    fn inferred_list_shortcuts_cover_scalar_types() -> anyhow::Result<()> {
3701        let vm = Vm::with_all()?;
3702        vm.import_code(
3703            "vm_inferred_list_shortcuts",
3704            br#"
3705            pub fn second_bool() {
3706                let l = [];
3707                l.push(true);
3708                l.push(false);
3709                l[1]
3710            }
3711
3712            pub fn first_u8() {
3713                let l = [];
3714                l.push(7u8);
3715                l[0]
3716            }
3717
3718            pub fn sum_i32(n: i64) {
3719                let l = [];
3720                for i in 0..n {
3721                    l.push(i as i32);
3722                }
3723                let sum = 0i32;
3724                for j in 0..n {
3725                    sum = sum + l[j];
3726                }
3727                sum
3728            }
3729
3730            pub fn sum_f32(n: i64) {
3731                let l = [];
3732                for i in 0..n {
3733                    l.push(i as f32);
3734                }
3735                let sum = 0f32;
3736                for j in 0..n {
3737                    sum = sum + l[j];
3738                }
3739                sum
3740            }
3741
3742            pub fn second_str() {
3743                let l = [];
3744                l.push("first");
3745                l.push("second");
3746                l[1]
3747            }
3748            "#
3749            .to_vec(),
3750        )?;
3751
3752        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_bool", &[])?;
3753        let second_bool_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::second_bool")?;
3754        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(second_bool_id, &[], &[]);
3755        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Bool)), "bool local type hints: {:?}", hints);
3756        assert_eq!(compiled.ret_ty(), &Type::Bool);
3757        let second_bool: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3758        assert!(!second_bool());
3759
3760        let compiled = vm.get_fn("vm_inferred_list_shortcuts::first_u8", &[])?;
3761        let first_u8_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::first_u8")?;
3762        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(first_u8_id, &[], &[]);
3763        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::U8)), "u8 local type hints: {:?}", hints);
3764        assert_eq!(compiled.ret_ty(), &Type::U8);
3765        let first_u8: extern "C" fn() -> u8 = unsafe { std::mem::transmute(compiled.ptr()) };
3766        assert_eq!(first_u8(), 7);
3767
3768        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_i32", &[Type::I64])?;
3769        let sum_i32_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::sum_i32")?;
3770        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(sum_i32_id, &[], &[Type::I64]);
3771        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I32)), "i32 local type hints: {:?}", hints);
3772        assert_eq!(compiled.ret_ty(), &Type::I32);
3773        let sum_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3774        assert_eq!(sum_i32(100), 4950);
3775
3776        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_f32", &[Type::I64])?;
3777        let sum_f32_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::sum_f32")?;
3778        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(sum_f32_id, &[], &[Type::I64]);
3779        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::F32)), "f32 local type hints: {:?}", hints);
3780        assert_eq!(compiled.ret_ty(), &Type::F32);
3781        let sum_f32: extern "C" fn(i64) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
3782        assert_eq!(sum_f32(10), 45.0);
3783
3784        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_str", &[])?;
3785        let second_str_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::second_str")?;
3786        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(second_str_id, &[], &[]);
3787        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Str)), "str local type hints: {:?}", hints);
3788        assert_eq!(compiled.ret_ty(), &Type::Str);
3789        let second_str: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3790        let result = unsafe { &*second_str() };
3791        assert_eq!(result.as_str(), "second");
3792        Ok(())
3793    }
3794
3795    #[test]
3796    fn inferred_list_supports_bracket_set_idx() -> anyhow::Result<()> {
3797        let vm = Vm::with_all()?;
3798        vm.import_code(
3799            "vm_inferred_list_set_idx",
3800            br#"
3801            pub fn swap_first_two() {
3802                let items = [];
3803                items.push(1i64);
3804                items.push(2i64);
3805                let j = 0i64;
3806                let a = items[j];
3807                let b = items[j + 1];
3808                items[j] = b;
3809                items[j + 1] = a;
3810                items[0] * 10i64 + items[1]
3811            }
3812
3813            pub fn replace_string() {
3814                let items = [];
3815                items.push("old");
3816                items[0] = "new";
3817                items[0]
3818            }
3819            "#
3820            .to_vec(),
3821        )?;
3822
3823        let compiled = vm.get_fn("vm_inferred_list_set_idx::swap_first_two", &[])?;
3824        assert_eq!(compiled.ret_ty(), &Type::I64);
3825        let swap_first_two: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3826        assert_eq!(swap_first_two(), 21);
3827
3828        let compiled = vm.get_fn("vm_inferred_list_set_idx::replace_string", &[])?;
3829        assert_eq!(compiled.ret_ty(), &Type::Str);
3830        let replace_string: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3831        let result = unsafe { &*replace_string() };
3832        assert_eq!(result.as_str(), "new");
3833        Ok(())
3834    }
3835
3836    #[test]
3837    fn root_get_returns_null_for_missing_key_which_compares_correctly() -> anyhow::Result<()> {
3838        let vm = Vm::with_all()?;
3839        vm.import_code(
3840            "vm_root_get_missing",
3841            br#"
3842            pub fn check_missing() {
3843                let existing = root::get("local/vm_root_get_missing_test");
3844                if existing.is_map() {
3845                    return false;
3846                }
3847                true
3848            }
3849            "#
3850            .to_vec(),
3851        )?;
3852
3853        let compiled = vm.get_fn("vm_root_get_missing::check_missing", &[])?;
3854        assert_eq!(compiled.ret_ty(), &Type::Bool);
3855        let check_missing: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3856        assert!(check_missing());
3857        Ok(())
3858    }
3859
3860    #[test]
3861    fn map_get_key_on_null_map_returns_null() -> anyhow::Result<()> {
3862        let vm = Vm::with_all()?;
3863        vm.import_code(
3864            "vm_get_key_null_map",
3865            br#"
3866            pub fn get_key_null(data) {
3867                data.get_key("missing")
3868            }
3869            "#
3870            .to_vec(),
3871        )?;
3872
3873        let compiled = vm.get_fn("vm_get_key_null_map::get_key_null", &[Type::Any])?;
3874        assert_eq!(compiled.ret_ty(), &Type::Any);
3875        let get_key_null: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3876
3877        let data_map = dynamic::map!("exists"=> 1i64);
3878        let missing = unsafe { &*get_key_null(&data_map) };
3879        assert!(missing.is_null());
3880
3881        let null = Dynamic::Null;
3882        let result = unsafe { &*get_key_null(&null) };
3883        assert!(result.is_null());
3884        Ok(())
3885    }
3886
3887    #[test]
3888    fn keys_on_empty_map_returns_empty_list() -> anyhow::Result<()> {
3889        let vm = Vm::with_all()?;
3890        vm.import_code(
3891            "vm_keys_empty_map",
3892            br#"
3893            pub fn empty_map_keys() {
3894                let data = {};
3895                data.keys().len()
3896            }
3897            "#
3898            .to_vec(),
3899        )?;
3900
3901        let compiled = vm.get_fn("vm_keys_empty_map::empty_map_keys", &[])?;
3902        assert_eq!(compiled.ret_ty(), &Type::I32);
3903        let empty_map_keys: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3904        assert_eq!(empty_map_keys(), 0);
3905        Ok(())
3906    }
3907
3908    #[test]
3909    fn cast_between_all_integer_widths() -> anyhow::Result<()> {
3910        let vm = Vm::with_all()?;
3911        vm.import_code(
3912            "vm_cast_integer_widths",
3913            br#"
3914            pub fn i64_to_i32(value: i64) {
3915                value as i32
3916            }
3917
3918            pub fn i32_to_i64(value: i32) {
3919                value as i64
3920            }
3921
3922            pub fn u32_to_i64(value: u32) {
3923                value as i64
3924            }
3925            "#
3926            .to_vec(),
3927        )?;
3928
3929        let compiled = vm.get_fn("vm_cast_integer_widths::i64_to_i32", &[Type::I64])?;
3930        assert_eq!(compiled.ret_ty(), &Type::I32);
3931        let i64_to_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3932        assert_eq!(i64_to_i32(42), 42);
3933
3934        let compiled = vm.get_fn("vm_cast_integer_widths::i32_to_i64", &[Type::I32])?;
3935        assert_eq!(compiled.ret_ty(), &Type::I64);
3936        let i32_to_i64: extern "C" fn(i32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3937        assert_eq!(i32_to_i64(-1), -1);
3938
3939        let compiled = vm.get_fn("vm_cast_integer_widths::u32_to_i64", &[Type::U32])?;
3940        assert_eq!(compiled.ret_ty(), &Type::I64);
3941        let u32_to_i64: extern "C" fn(u32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3942        assert_eq!(u32_to_i64(42), 42);
3943        Ok(())
3944    }
3945
3946    #[test]
3947    fn boolean_literals_in_complex_expression_trees() -> anyhow::Result<()> {
3948        let vm = Vm::with_all()?;
3949        vm.import_code(
3950            "vm_complex_boolean",
3951            br#"
3952            pub fn exclusive_or(a: bool, b: bool) {
3953                (a && !b) || (!a && b)
3954            }
3955
3956            pub fn implies(a: bool, b: bool) {
3957                !a || b
3958            }
3959            "#
3960            .to_vec(),
3961        )?;
3962
3963        let compiled = vm.get_fn("vm_complex_boolean::exclusive_or", &[Type::Bool, Type::Bool])?;
3964        assert_eq!(compiled.ret_ty(), &Type::Bool);
3965        let exclusive_or: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3966        assert!(exclusive_or(true, false));
3967        assert!(exclusive_or(false, true));
3968        assert!(!exclusive_or(true, true));
3969        assert!(!exclusive_or(false, false));
3970
3971        let compiled = vm.get_fn("vm_complex_boolean::implies", &[Type::Bool, Type::Bool])?;
3972        assert_eq!(compiled.ret_ty(), &Type::Bool);
3973        let implies: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3974        assert!(implies(false, true));
3975        assert!(implies(false, false));
3976        assert!(implies(true, true));
3977        assert!(!implies(true, false));
3978        Ok(())
3979    }
3980
3981    #[test]
3982    fn concrete_struct_method_returning_self_type() -> anyhow::Result<()> {
3983        let vm = Vm::with_all()?;
3984        vm.import_code(
3985            "vm_struct_method_self",
3986            br#"
3987            pub struct Vec3 {
3988                x: f64,
3989                y: f64,
3990                z: f64,
3991            }
3992
3993            impl Vec3 {
3994                pub fn add(self: Vec3, other: Vec3) {
3995                    Vec3{x: self.x + other.x, y: self.y + other.y, z: self.z + other.z}
3996                }
3997            }
3998
3999            pub fn run() {
4000                let v1 = Vec3{x: 1.0f64, y: 2.0f64, z: 3.0f64};
4001                let v2 = Vec3{x: 4.0f64, y: 5.0f64, z: 6.0f64};
4002                let sum = v1.add(v2);
4003                sum.x + sum.y + sum.z
4004            }
4005            "#
4006            .to_vec(),
4007        )?;
4008
4009        let compiled = vm.get_fn("vm_struct_method_self::run", &[])?;
4010        assert_eq!(compiled.ret_ty(), &Type::F64);
4011        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
4012        assert_eq!(run(), 21.0);
4013        Ok(())
4014    }
4015
4016    #[test]
4017    fn deep_nested_struct_access_with_multiple_field_levels() -> anyhow::Result<()> {
4018        let vm = Vm::with_all()?;
4019        vm.import_code(
4020            "vm_deep_nested_struct",
4021            br#"
4022            pub struct A {
4023                value: i64,
4024            }
4025
4026            pub struct B {
4027                a: A,
4028            }
4029
4030            pub struct C {
4031                b: B,
4032            }
4033
4034            pub fn direct_access() {
4035                let c = C{b: B{a: A{value: 99}}};
4036                c.b.a.value
4037            }
4038
4039            pub fn via_variable() {
4040                let c = C{b: B{a: A{value: 77}}};
4041                let b = c.b;
4042                let a = b.a;
4043                a.value
4044            }
4045            "#
4046            .to_vec(),
4047        )?;
4048
4049        let compiled = vm.get_fn("vm_deep_nested_struct::direct_access", &[])?;
4050        assert_eq!(compiled.ret_ty(), &Type::I64);
4051        let direct_access: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4052        assert_eq!(direct_access(), 99);
4053
4054        let compiled = vm.get_fn("vm_deep_nested_struct::via_variable", &[])?;
4055        assert_eq!(compiled.ret_ty(), &Type::I64);
4056        let via_variable: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4057        assert_eq!(via_variable(), 77);
4058        Ok(())
4059    }
4060
4061    #[test]
4062    fn array_index_with_dynamic_value_via_method() -> anyhow::Result<()> {
4063        let vm = Vm::with_all()?;
4064        vm.import_code(
4065            "vm_array_idx_dynamic",
4066            br#"
4067            pub fn get_by_idx(list, idx) {
4068                list.get_idx(idx)
4069            }
4070            "#
4071            .to_vec(),
4072        )?;
4073
4074        let compiled = vm.get_fn("vm_array_idx_dynamic::get_by_idx", &[Type::Any, Type::I64])?;
4075        assert_eq!(compiled.ret_ty(), &Type::Any);
4076        let get_by_idx: extern "C" fn(*const Dynamic, i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4077
4078        let list = Dynamic::list(vec!["a".into(), "b".into()]);
4079        let first = unsafe { &*get_by_idx(&list, 0) };
4080        assert_eq!(first.as_str(), "a");
4081
4082        let out = unsafe { &*get_by_idx(&list, 10) };
4083        assert!(out.is_null());
4084        Ok(())
4085    }
4086
4087    #[test]
4088    fn dynamic_field_access_with_optional_or_fallback() -> anyhow::Result<()> {
4089        let vm = Vm::with_all()?;
4090        vm.import_code(
4091            "vm_dynamic_or_fallback",
4092            br#"
4093            pub fn with_fallback(data) {
4094                if data.contains("name") { data.name } else { "unknown" }
4095            }
4096
4097            pub fn with_fallback_missing(data) {
4098                if data.contains("nickname") { data.nickname } else { "unnamed" }
4099            }
4100            "#
4101            .to_vec(),
4102        )?;
4103
4104        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback", &[Type::Any])?;
4105        assert_eq!(compiled.ret_ty(), &Type::Any);
4106        let with_fallback: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4107        let data = dynamic::map!("name"=> "Alice");
4108        let result = unsafe { &*with_fallback(&data) };
4109        assert_eq!(result.as_str(), "Alice");
4110
4111        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback_missing", &[Type::Any])?;
4112        let with_fallback_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4113        let result = unsafe { &*with_fallback_missing(&data) };
4114        assert_eq!(result.as_str(), "unnamed");
4115        Ok(())
4116    }
4117
4118    #[test]
4119    fn for_in_loop_iterates_over_list_and_map_directly() -> anyhow::Result<()> {
4120        let vm = Vm::with_all()?;
4121        vm.import_code(
4122            "vm_for_in_collection",
4123            br#"
4124            pub fn sum_list(items) {
4125                let total = 0i64;
4126                for item in items {
4127                    total = total + 1;
4128                }
4129                total
4130            }
4131
4132            pub fn count_map_keys(data) {
4133                let count = 0i64;
4134                for key in data.keys() {
4135                    count = count + 1;
4136                }
4137                count
4138            }
4139
4140            pub fn for_in_list_works(items) {
4141                let exists = false;
4142                for item in items {
4143                    exists = true;
4144                }
4145                exists
4146            }
4147
4148            pub fn for_in_map_values_works(data) {
4149                let exists = false;
4150                for value in data {
4151                    exists = true;
4152                }
4153                exists
4154            }
4155            "#
4156            .to_vec(),
4157        )?;
4158
4159        let compiled = vm.get_fn("vm_for_in_collection::sum_list", &[Type::Any])?;
4160        assert_eq!(compiled.ret_ty(), &Type::I64);
4161        let sum_list: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4162        let items = Dynamic::list(vec![Dynamic::from(1i64), Dynamic::from(2i64), Dynamic::from(3i64)]);
4163        assert_eq!(sum_list(&items), 3);
4164
4165        let data = dynamic::map!("x"=> 1i64, "y"=> 2i64);
4166        let compiled = vm.get_fn("vm_for_in_collection::count_map_keys", &[Type::Any])?;
4167        assert_eq!(compiled.ret_ty(), &Type::I64);
4168        let count_map_keys: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4169        assert_eq!(count_map_keys(&data), 2);
4170
4171        let compiled = vm.get_fn("vm_for_in_collection::for_in_list_works", &[Type::Any])?;
4172        assert_eq!(compiled.ret_ty(), &Type::Bool);
4173        let for_in_list_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4174        let empty = Dynamic::list(Vec::new());
4175        assert!(!for_in_list_works(&empty));
4176        assert!(for_in_list_works(&items));
4177
4178        let compiled = vm.get_fn("vm_for_in_collection::for_in_map_values_works", &[Type::Any])?;
4179        assert_eq!(compiled.ret_ty(), &Type::Bool);
4180        let for_in_map_values_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4181        let empty_map = dynamic::map!();
4182        assert!(!for_in_map_values_works(&empty_map));
4183        assert!(for_in_map_values_works(&data));
4184
4185        Ok(())
4186    }
4187
4188    #[test]
4189    fn concurrent_100_threads_no_memory_leak() -> anyhow::Result<()> {
4190        let vm = Vm::with_all()?;
4191        vm.import_code(
4192            "vm_stress",
4193            br#"
4194            pub fn heavy_alloc(idx: i64) {
4195                let items = [];
4196                let i = 0;
4197                while i < 50 {
4198                    items.push({
4199                        id: i + idx,
4200                        name: "item-" + i,
4201                        tags: ["tag-a", "tag-b", "tag-c"],
4202                        meta: {
4203                            created: 1234567890i64,
4204                            score: (i * 3.14f64) as i64,
4205                            extra: "prefix/" + i + "/" + idx
4206                        }
4207                    });
4208                    i = i + 1;
4209                }
4210                items
4211            }
4212
4213            pub fn string_concat_stress() {
4214                let i = 0;
4215                let result = "";
4216                while i < 200 {
4217                    result = result + "data-" + i + ",";
4218                    i = i + 1;
4219                }
4220                result
4221            }
4222            "#
4223            .to_vec(),
4224        )?;
4225
4226        let (heavy_ptr, _) = vm.get_fn_ptr("vm_stress::heavy_alloc", &[Type::I64])?;
4227        let (concat_ptr, _) = vm.get_fn_ptr("vm_stress::string_concat_stress", &[])?;
4228
4229        let threads: usize = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).max(100);
4230        let iters_per_thread = 200;
4231        let total_calls = threads * iters_per_thread * 2;
4232
4233        let before = current_rss_kb();
4234        eprintln!("threads={threads} iters_per_thread={iters_per_thread} total_calls={total_calls} rss_before={before}KB");
4235
4236        // Round 1: first concurrent execution (arena warm-up)
4237        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4238        let r1 = current_rss_kb();
4239        eprintln!("rss_after_round1={r1}KB");
4240
4241        // Round 2: should stabilize (no unbounded growth)
4242        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4243        let r2 = current_rss_kb();
4244        eprintln!("rss_after_round2={r2}KB");
4245
4246        // Round 3: final check
4247        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4248        let r3 = current_rss_kb();
4249        eprintln!("rss_after_round3={r3}KB");
4250
4251        // Round 4: confirm that any one-time allocator growth has settled.
4252        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4253        let r4 = current_rss_kb();
4254        eprintln!("rss_after_round4={r4}KB");
4255
4256        // Allocator/arena growth is allowed during warm-up, but it must settle.
4257        let d12 = r2.saturating_sub(r1);
4258        let d23 = r3.saturating_sub(r2);
4259        let d34 = r4.saturating_sub(r3);
4260        eprintln!("delta_r1→r2={d12}KB delta_r2→r3={d23}KB delta_r3→r4={d34}KB");
4261
4262        // The last interval must be small to prove the growth is not continuing.
4263        let max_growth_kb = 20 * 1024;
4264        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)");
4265
4266        Ok(())
4267    }
4268
4269    fn run_stress_round(threads: usize, iters: usize, heavy_ptr: usize, concat_ptr: usize) {
4270        std::thread::scope(|scope| {
4271            let mut handles = Vec::with_capacity(threads);
4272            for t in 0..threads {
4273                let heavy_ptr = heavy_ptr;
4274                let concat_ptr = concat_ptr;
4275                handles.push(scope.spawn(move || {
4276                    let heavy_fn: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(heavy_ptr as *const u8) };
4277                    let concat_fn: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(concat_ptr as *const u8) };
4278                    for i in 0..iters {
4279                        // heavy_alloc: drop returned value to free heap allocation
4280                        let r_ptr = heavy_fn((t * iters + i) as i64);
4281                        assert!(!r_ptr.is_null());
4282                        unsafe {
4283                            let r = &*r_ptr;
4284                            assert!(r.len() > 0, "heavy_alloc returned empty list");
4285                            drop(Box::from_raw(r_ptr as *mut Dynamic));
4286                        }
4287
4288                        // concat: same, drop returned value
4289                        let s_ptr = concat_fn();
4290                        assert!(!s_ptr.is_null());
4291                        unsafe {
4292                            let s = &*s_ptr;
4293                            assert!(s.len() > 0, "string_concat_stress returned empty");
4294                            drop(Box::from_raw(s_ptr as *mut Dynamic));
4295                        }
4296                    }
4297                }));
4298            }
4299            for h in handles {
4300                h.join().unwrap();
4301            }
4302        });
4303    }
4304
4305    fn current_rss_kb() -> u64 {
4306        // macOS: use ps
4307        let pid = std::process::id();
4308        if let Ok(output) = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "rss="]).output() {
4309            if let Ok(s) = String::from_utf8(output.stdout) {
4310                if let Some(kb) = s.trim().parse::<u64>().ok() {
4311                    return kb;
4312                }
4313            }
4314        }
4315        // Linux fallback: /proc/self/statm
4316        if let Ok(statm) = std::fs::read_to_string("/proc/self/statm") {
4317            let parts: Vec<&str> = statm.split_whitespace().collect();
4318            if let Some(rss_pages) = parts.get(1).and_then(|s| s.parse::<u64>().ok()) {
4319                return rss_pages * 4; // pages (4KB) → KB
4320            }
4321        }
4322        0
4323    }
4324}