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 nested_closure_captures_outer_closure_arg() -> anyhow::Result<()> {
1496        let vm = Vm::with_all()?;
1497        vm.import_code(
1498            "vm_nested_closure_capture",
1499            br#"
1500            pub fn run() {
1501                |path: string| {
1502                    let upload_done = |uploaded: bool| {
1503                        if uploaded {
1504                            path
1505                        } else {
1506                            "missing"
1507                        }
1508                    };
1509                    upload_done(true)
1510                }("reference.png")
1511            }
1512            "#
1513            .to_vec(),
1514        )?;
1515
1516        let compiled = vm.get_fn("vm_nested_closure_capture::run", &[])?;
1517        assert_eq!(compiled.ret_ty(), &Type::Any);
1518        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1519        let result = unsafe { &*run() };
1520        assert_eq!(result.as_str(), "reference.png");
1521        Ok(())
1522    }
1523
1524    #[test]
1525    fn semicolon_tail_call_makes_function_void() -> anyhow::Result<()> {
1526        let vm = Vm::with_all()?;
1527        vm.import_code(
1528            "vm_semicolon_tail_void",
1529            br#"
1530            pub fn send_role_select(idx, account_id, selected_slot) {
1531                root::send("local/ui/send_dialog", {
1532                    idx: idx,
1533                    account_id: account_id,
1534                    selected_slot: selected_slot
1535                });
1536            }
1537            "#
1538            .to_vec(),
1539        )?;
1540
1541        let compiled = vm.get_fn("vm_semicolon_tail_void::send_role_select", &[Type::Any, Type::Any, Type::Any])?;
1542        assert_eq!(compiled.ret_ty(), &Type::Void);
1543        Ok(())
1544    }
1545
1546    #[test]
1547    fn bare_return_conflicts_with_non_void_return() -> anyhow::Result<()> {
1548        let vm = Vm::with_all()?;
1549        vm.import_code(
1550            "vm_bare_return_conflict",
1551            br#"
1552            pub fn run(flag) {
1553                if flag {
1554                    return;
1555                }
1556                1
1557            }
1558            "#
1559            .to_vec(),
1560        )?;
1561
1562        let err = match vm.get_fn("vm_bare_return_conflict::run", &[Type::Bool]) {
1563            Ok(_) => panic!("expected mismatched return types to fail"),
1564            Err(err) => err,
1565        };
1566        assert!(format!("{err:#}").contains("返回类型不一致"));
1567        Ok(())
1568    }
1569
1570    #[test]
1571    fn root_get_accepts_string_concat_with_dynamic_field() -> anyhow::Result<()> {
1572        let vm = Vm::with_all()?;
1573        vm.import_code(
1574            "vm_root_get_dynamic_concat",
1575            br#"
1576            pub fn get_action(req) {
1577                root::get("local/game/panel_actions/" + req.idx)
1578            }
1579            "#
1580            .to_vec(),
1581        )?;
1582
1583        root::add("local/game/panel_actions/7", dynamic::map!("id"=> "action-7").into())?;
1584        let compiled = vm.get_fn("vm_root_get_dynamic_concat::get_action", &[Type::Any])?;
1585        assert_eq!(compiled.ret_ty(), &Type::Any);
1586        let get_action: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1587        let req = dynamic::map!("idx"=> 7i64);
1588        let result = unsafe { &*get_action(&req) };
1589
1590        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("action-7".to_string()));
1591        Ok(())
1592    }
1593
1594    #[test]
1595    fn root_add_fn_registers_handler_with_dynamic_field_path_concat() -> anyhow::Result<()> {
1596        let vm = Vm::with_all()?;
1597        vm.import_code(
1598            "vm_registered_panel_action",
1599            br#"
1600            pub fn panel_action(req) {
1601                root::get("local/game/panel_actions/" + req.idx)
1602            }
1603
1604            pub fn register() {
1605                root::add_fn("local/ui/panel_action", "vm_registered_panel_action::panel_action")
1606            }
1607            "#
1608            .to_vec(),
1609        )?;
1610
1611        let compiled = vm.get_fn("vm_registered_panel_action::register", &[])?;
1612        assert_eq!(compiled.ret_ty(), &Type::Bool);
1613        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1614        assert!(register());
1615        Ok(())
1616    }
1617
1618    #[test]
1619    fn std_spawn_runs_named_function_with_tuple_args() -> anyhow::Result<()> {
1620        let zero_path = "local/vm_std_spawn/zero";
1621        let sum_path = "local/vm_std_spawn/sum";
1622        let closure_path = "local/vm_std_spawn/closure";
1623        let closure_vars_path = "local/vm_std_spawn/closure_vars";
1624        let _ = root::remove(zero_path);
1625        let _ = root::remove(sum_path);
1626        let _ = root::remove(closure_path);
1627        let _ = root::remove(closure_vars_path);
1628        let vm = Vm::with_all()?;
1629        vm.import_code(
1630            "vm_std_spawn",
1631            br#"
1632            pub fn zero() {
1633                root::add("local/vm_std_spawn/zero", 1);
1634            }
1635
1636            pub fn job(left, right) {
1637                root::add("local/vm_std_spawn/sum", left + right);
1638            }
1639
1640            pub fn start_zero() {
1641                spawn("vm_std_spawn::zero", ())
1642            }
1643
1644            pub fn start_sum() {
1645                spawn("vm_std_spawn::job", (10, 20))
1646            }
1647
1648            pub fn start_closure() {
1649                spawn(|x, y| {
1650                    root::add("local/vm_std_spawn/closure", x + y);
1651                }, (3, 4))
1652            }
1653
1654            pub fn start_closure_vars() {
1655                let x = 5;
1656                let y = 6;
1657                spawn(|left, right| {
1658                    root::add("local/vm_std_spawn/closure_vars", left + right);
1659                }, (x, y))
1660            }
1661            "#
1662            .to_vec(),
1663        )?;
1664
1665        let compiled = vm.get_fn("vm_std_spawn::start_zero", &[])?;
1666        assert_eq!(compiled.ret_ty(), &Type::Bool);
1667        let start_zero: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1668        assert!(start_zero());
1669
1670        let compiled = vm.get_fn("vm_std_spawn::start_sum", &[])?;
1671        assert_eq!(compiled.ret_ty(), &Type::Bool);
1672        let start_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1673        assert!(start_sum());
1674
1675        let compiled = vm.get_fn("vm_std_spawn::start_closure", &[])?;
1676        assert_eq!(compiled.ret_ty(), &Type::Bool);
1677        let start_closure: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1678        assert!(start_closure());
1679
1680        let compiled = vm.get_fn("vm_std_spawn::start_closure_vars", &[])?;
1681        assert_eq!(compiled.ret_ty(), &Type::Bool);
1682        let start_closure_vars: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1683        assert!(start_closure_vars());
1684
1685        for _ in 0..50 {
1686            let zero_done = root::get(zero_path).ok().and_then(|value| value.as_int()) == Some(1);
1687            let sum_done = root::get(sum_path).ok().and_then(|value| value.as_int()) == Some(30);
1688            let closure_done = root::get(closure_path).ok().and_then(|value| value.as_int()) == Some(7);
1689            let closure_vars_done = root::get(closure_vars_path).ok().and_then(|value| value.as_int()) == Some(11);
1690            if zero_done && sum_done && closure_done && closure_vars_done {
1691                return Ok(());
1692            }
1693            std::thread::sleep(std::time::Duration::from_millis(10));
1694        }
1695
1696        anyhow::bail!("spawned jobs did not write expected results");
1697    }
1698
1699    #[test]
1700    fn native_can_save_and_later_call_closure_callback() -> anyhow::Result<()> {
1701        static SAVED_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1702
1703        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
1704            if callback.is_null() {
1705                return false;
1706            }
1707            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1708                return false;
1709            };
1710            *SAVED_CALLBACK.lock().unwrap() = Some(callback);
1711            true
1712        }
1713
1714        let path = "local/vm_callback/result";
1715        let _ = root::remove(path);
1716        *SAVED_CALLBACK.lock().unwrap() = None;
1717
1718        let vm = Vm::with_all()?;
1719        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
1720        vm.import_code(
1721            "vm_callback",
1722            br#"
1723            pub fn register() {
1724                let n = 41;
1725                callback_test::save(|| {
1726                    root::add("local/vm_callback/result", n + 1);
1727                    true
1728                })
1729            }
1730            "#
1731            .to_vec(),
1732        )?;
1733
1734        let compiled = vm.get_fn("vm_callback::register", &[])?;
1735        assert_eq!(compiled.ret_ty(), &Type::Bool);
1736        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
1737        assert!(register());
1738        assert!(root::get(path).is_err());
1739
1740        let callback = SAVED_CALLBACK.lock().unwrap().clone().expect("callback should be saved");
1741        let result = callback.call0()?;
1742        assert_eq!(result.as_bool(), Some(true));
1743        assert_eq!(root::get(path)?.as_int(), Some(42));
1744        Ok(())
1745    }
1746
1747    #[test]
1748    fn native_can_save_and_later_call_named_function_callback() -> anyhow::Result<()> {
1749        static SAVED_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1750
1751        extern "C" fn save_callback(callback: *const Dynamic) -> bool {
1752            if callback.is_null() {
1753                return false;
1754            }
1755            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1756                return false;
1757            };
1758            *SAVED_CALLBACK.lock().unwrap() = Some(callback);
1759            true
1760        }
1761
1762        let path = "local/vm_named_callback/result";
1763        let _ = root::remove(path);
1764        *SAVED_CALLBACK.lock().unwrap() = None;
1765
1766        let vm = Vm::with_all()?;
1767        vm.add_native_module_ptr("callback_test", "save", &[Type::Any], Type::Bool, save_callback as *const u8)?;
1768        vm.import_code(
1769            "vm_named_callback",
1770            br#"
1771            pub fn on_result() {
1772                root::add("local/vm_named_callback/result", "done");
1773                true
1774            }
1775
1776            pub fn register() {
1777                callback_test::save(on_result)
1778            }
1779            "#
1780            .to_vec(),
1781        )?;
1782
1783        let register = vm.get_fn("vm_named_callback::register", &[])?;
1784        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(register.ptr()) };
1785        assert!(register());
1786        assert!(root::get(path).is_err());
1787
1788        let callback = SAVED_CALLBACK.lock().unwrap().clone().expect("callback should be saved");
1789        assert_eq!(callback.call1(dynamic::map!("text"=> "done"))?.as_bool(), Some(true));
1790        assert_eq!(root::get(path)?.as_str(), "done");
1791        Ok(())
1792    }
1793
1794    #[test]
1795    fn native_callback_can_receive_later_dynamic_args() -> anyhow::Result<()> {
1796        static SAVED_PATH_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1797        static SAVED_SUM_CALLBACK: Mutex<Option<ZustCallback>> = Mutex::new(None);
1798
1799        extern "C" fn save_path_callback(callback: *const Dynamic) -> bool {
1800            if callback.is_null() {
1801                return false;
1802            }
1803            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1804                return false;
1805            };
1806            *SAVED_PATH_CALLBACK.lock().unwrap() = Some(callback);
1807            true
1808        }
1809
1810        extern "C" fn save_sum_callback(callback: *const Dynamic) -> bool {
1811            if callback.is_null() {
1812                return false;
1813            }
1814            let Some(callback) = (unsafe { &*callback }).as_custom::<ZustCallback>().cloned() else {
1815                return false;
1816            };
1817            *SAVED_SUM_CALLBACK.lock().unwrap() = Some(callback);
1818            true
1819        }
1820
1821        let path_result = "local/vm_callback/path";
1822        let sum_result = "local/vm_callback/sum8";
1823        let _ = root::remove(path_result);
1824        let _ = root::remove(sum_result);
1825        *SAVED_PATH_CALLBACK.lock().unwrap() = None;
1826        *SAVED_SUM_CALLBACK.lock().unwrap() = None;
1827
1828        let vm = Vm::with_all()?;
1829        vm.add_native_module_ptr("callback_test", "save_path", &[Type::Any], Type::Bool, save_path_callback as *const u8)?;
1830        vm.add_native_module_ptr("callback_test", "save_sum", &[Type::Any], Type::Bool, save_sum_callback as *const u8)?;
1831        vm.import_code(
1832            "vm_callback_args",
1833            br#"
1834            pub fn register_path() {
1835                let key = "local/vm_callback/path";
1836                callback_test::save_path(|path| {
1837                    root::add(key, path);
1838                    true
1839                })
1840            }
1841
1842            pub fn register_sum() {
1843                callback_test::save_sum(|a, b, c, d, e, f, g, h| {
1844                    root::add("local/vm_callback/sum8", a + b + c + d + e + f + g + h);
1845                    true
1846                })
1847            }
1848            "#
1849            .to_vec(),
1850        )?;
1851
1852        let register_path = vm.get_fn("vm_callback_args::register_path", &[])?;
1853        let register_path: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_path.ptr()) };
1854        assert!(register_path());
1855
1856        let register_sum = vm.get_fn("vm_callback_args::register_sum", &[])?;
1857        let register_sum: extern "C" fn() -> bool = unsafe { std::mem::transmute(register_sum.ptr()) };
1858        assert!(register_sum());
1859
1860        let path_callback = SAVED_PATH_CALLBACK.lock().unwrap().clone().expect("path callback should be saved");
1861        assert_eq!(path_callback.call1(Dynamic::from("picked.txt"))?.as_bool(), Some(true));
1862        assert_eq!(root::get(path_result)?.as_str(), "picked.txt");
1863
1864        let sum_callback = SAVED_SUM_CALLBACK.lock().unwrap().clone().expect("sum callback should be saved");
1865        let sum_args = (1i64..=8).map(Dynamic::from).collect();
1866        assert_eq!(sum_callback.call(sum_args)?.as_bool(), Some(true));
1867        assert_eq!(root::get(sum_result)?.as_int(), Some(36));
1868        Ok(())
1869    }
1870
1871    #[test]
1872    fn root_add_fn_accepts_string_concat_in_registered_handler() -> anyhow::Result<()> {
1873        let vm = Vm::with_all()?;
1874        vm.import_code(
1875            "vm_registered_string_concat",
1876            br#"
1877            pub fn send_panel(idx: i64) {
1878                let idx_key = "" + idx;
1879                idx_key
1880            }
1881            "#
1882            .to_vec(),
1883        )?;
1884
1885        assert!(vm.get_fn_ptr("vm_registered_string_concat::send_panel", &[Type::Any]).is_ok());
1886        Ok(())
1887    }
1888
1889    #[test]
1890    fn root_send_idx_returns_handler_value() -> anyhow::Result<()> {
1891        fn echo_handler(msg: Dynamic) -> Dynamic {
1892            dynamic::map!("type"=> "echo", "id"=> msg.get_dynamic("id").unwrap_or(Dynamic::Null))
1893        }
1894
1895        let vm = Vm::with_all()?;
1896        vm.import_code(
1897            "vm_root_send_idx_return",
1898            br#"
1899            pub fn call(req) {
1900                root::send_idx("local/send_idx_return_handlers", 0, req)
1901            }
1902            "#
1903            .to_vec(),
1904        )?;
1905
1906        root::add_list("local/send_idx_return_handlers")?;
1907        let (mount, name) = root::get_mount("local/send_idx_return_handlers")?;
1908        mount.push(name, root::Object::Native(echo_handler))?;
1909
1910        assert_eq!(vm.infer("root::send_idx", &[Type::Any, Type::I64, Type::Any])?, Type::Any);
1911        let compiled = vm.get_fn("vm_root_send_idx_return::call", &[Type::Any])?;
1912        assert_eq!(compiled.ret_ty(), &Type::Any);
1913        let call: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1914        let req = dynamic::map!("id"=> 42i64);
1915        let result = unsafe { &*call(&req) };
1916
1917        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("echo".to_string()));
1918        assert_eq!(result.get_dynamic("id").and_then(|value| value.as_int()), Some(42));
1919        Ok(())
1920    }
1921
1922    #[test]
1923    fn compiles_public_hotspots_with_string_paths_and_keys() -> anyhow::Result<()> {
1924        let vm = Vm::with_all()?;
1925        vm.import_code(
1926            "vm_public_hotspots",
1927            br#"
1928            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
1929                {
1930                    path: action_map_path,
1931                    panel_id: panel_id,
1932                    action_id: action_id,
1933                    id: hotspot.id
1934                }
1935            }
1936
1937            pub fn public_hotspots(idx, panel_id, hotspots) {
1938                let idx_key = "" + idx;
1939                let action_map_path = "local/game/panel_actions/" + idx_key;
1940
1941                let existing_action_map = root::get(action_map_path);
1942                if !existing_action_map.is_map() {
1943                    root::add_map(action_map_path);
1944                }
1945
1946                if hotspots.is_map() {
1947                    let public_items = {};
1948                    for action_id in hotspots.keys() {
1949                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
1950                    }
1951                    return public_items;
1952                }
1953
1954                let public_items = [];
1955                let i = 0;
1956                while i < hotspots.len() {
1957                    let hotspot = hotspots.get_idx(i);
1958                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
1959                    public_items.push(item);
1960                    i = i + 1;
1961                }
1962
1963                public_items
1964            }
1965            "#
1966            .to_vec(),
1967        )?;
1968
1969        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::I64, Type::Any, Type::Any]).is_ok());
1970        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::Any, Type::Any, Type::Any]).is_ok());
1971        Ok(())
1972    }
1973
1974    #[test]
1975    fn send_panel_calls_public_hotspots_with_dynamic_request() -> anyhow::Result<()> {
1976        let vm = Vm::with_all()?;
1977        vm.import_code(
1978            "vm_send_panel_public_hotspots",
1979            br#"
1980            pub fn ok(value) {
1981                value
1982            }
1983
1984            pub fn panel_from_node(req) {
1985                {
1986                    panel_id: req.panel_id,
1987                    hotspots: req.hotspots
1988                }
1989            }
1990
1991            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
1992                {
1993                    path: action_map_path,
1994                    panel_id: panel_id,
1995                    action_id: action_id,
1996                    id: hotspot.id
1997                }
1998            }
1999
2000            pub fn public_hotspots(idx, panel_id, hotspots) {
2001                let idx_key = "" + idx;
2002                let action_map_path = "local/game/panel_actions/" + idx_key;
2003
2004                let existing_action_map = root::get(action_map_path);
2005                if !existing_action_map.is_map() {
2006                    root::add_map(action_map_path);
2007                }
2008
2009                if hotspots.is_map() {
2010                    let public_items = {};
2011                    for action_id in hotspots.keys() {
2012                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
2013                    }
2014                    return public_items;
2015                }
2016
2017                let public_items = [];
2018                let i = 0;
2019                while i < hotspots.len() {
2020                    let hotspot = hotspots.get_idx(i);
2021                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
2022                    public_items.push(item);
2023                    i = i + 1;
2024                }
2025
2026                public_items
2027            }
2028
2029            pub fn send_panel(req) {
2030                let panel = req.panel;
2031                if !panel.is_map() {
2032                    panel = panel_from_node(req);
2033                }
2034                if !panel.is_map() {
2035                    return ok({
2036                        id: 4,
2037                        type: "panel_rejected",
2038                        reason: "invalid panel"
2039                    });
2040                }
2041                panel.id = 4;
2042                panel.idx = req.idx;
2043                if !panel.contains("type") {
2044                    panel.type = "panel";
2045                }
2046                if panel.contains("hotspots") {
2047                    panel.hotspots = public_hotspots(req.idx, panel.panel_id, panel.hotspots);
2048                }
2049                root::send_idx("local/ws", req.idx, panel);
2050                ok({
2051                    id: 4,
2052                    type: "panel",
2053                    panel_id: panel.panel_id
2054                })
2055            }
2056            "#
2057            .to_vec(),
2058        )?;
2059
2060        let compiled = vm.get_fn("vm_send_panel_public_hotspots::send_panel", &[Type::Any])?;
2061        assert_eq!(compiled.ret_ty(), &Type::Any);
2062        let send_panel: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2063        let req = dynamic::map!(
2064            "idx"=> 7i64,
2065            "panel"=> dynamic::map!(
2066                "panel_id"=> "main",
2067                "hotspots"=> dynamic::map!(
2068                    "open"=> dynamic::map!("id"=> "open")
2069                )
2070            )
2071        );
2072        let result = unsafe { &*send_panel(&req) };
2073
2074        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("panel".to_string()));
2075        assert_eq!(result.get_dynamic("panel_id").map(|value| value.as_str().to_string()), Some("main".to_string()));
2076        Ok(())
2077    }
2078
2079    #[test]
2080    fn map_assignment_accepts_string_concat_key() -> anyhow::Result<()> {
2081        let vm = Vm::with_all()?;
2082        vm.import_code(
2083            "vm_string_concat_map_key",
2084            br##"
2085            pub fn write_action(action_map, panel_id, action_id, action) {
2086                action_map[panel_id + "#" + action_id] = action;
2087                action_map[panel_id + "#" + action_id]
2088            }
2089            "##
2090            .to_vec(),
2091        )?;
2092
2093        let compiled = vm.get_fn("vm_string_concat_map_key::write_action", &[Type::Any, Type::Any, Type::Any, Type::Any])?;
2094        let write_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2095        let action_map = dynamic::map!();
2096        let panel_id: Dynamic = "panel".into();
2097        let action_id: Dynamic = "open".into();
2098        let action = dynamic::map!("id"=> "open");
2099
2100        let result = unsafe { &*write_action(&action_map, &panel_id, &action_id, &action) };
2101
2102        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2103        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()));
2104        Ok(())
2105    }
2106
2107    #[test]
2108    fn map_get_key_accepts_string_concat_key_variable() -> anyhow::Result<()> {
2109        let vm = Vm::with_all()?;
2110        vm.import_code(
2111            "vm_get_key_string_concat_key",
2112            br##"
2113            pub fn read_action(action_map, panel_id, action_id) {
2114                let action_key = panel_id + "#" + action_id;
2115                action_map.get_key(action_key)
2116            }
2117            "##
2118            .to_vec(),
2119        )?;
2120
2121        let compiled = vm.get_fn("vm_get_key_string_concat_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
2122        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2123        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2124        let panel_id: Dynamic = "panel".into();
2125        let action_id: Dynamic = "open".into();
2126
2127        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
2128
2129        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2130        Ok(())
2131    }
2132
2133    #[test]
2134    fn map_get_key_accepts_helper_string_key() -> anyhow::Result<()> {
2135        let vm = Vm::with_all()?;
2136        vm.import_code(
2137            "vm_get_key_helper_string_key",
2138            br##"
2139            pub fn make_action_key(panel_id, action_id) {
2140                panel_id + "#" + action_id
2141            }
2142
2143            pub fn read_action(action_map, panel_id, action_id) {
2144                let action_key = make_action_key(panel_id, action_id);
2145                let action = action_map.get_key(action_key);
2146                action
2147            }
2148            "##
2149            .to_vec(),
2150        )?;
2151
2152        let compiled = vm.get_fn("vm_get_key_helper_string_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
2153        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2154        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2155        let panel_id: Dynamic = "panel".into();
2156        let action_id: Dynamic = "open".into();
2157
2158        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
2159
2160        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
2161        Ok(())
2162    }
2163
2164    #[test]
2165    fn map_del_key_removes_string_key_and_returns_removed_value() -> anyhow::Result<()> {
2166        let vm = Vm::with_all()?;
2167        vm.import_code(
2168            "vm_del_key_string_key",
2169            br##"
2170            pub fn remove_action(action_map, panel_id, action_id) {
2171                let action_key = panel_id + "#" + action_id;
2172                let removed = action_map.del_key(action_key);
2173                [removed, action_map.get_key(action_key)]
2174            }
2175            "##
2176            .to_vec(),
2177        )?;
2178
2179        let compiled = vm.get_fn("vm_del_key_string_key::remove_action", &[Type::Any, Type::Any, Type::Any])?;
2180        let remove_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2181        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
2182        let panel_id: Dynamic = "panel".into();
2183        let action_id: Dynamic = "open".into();
2184
2185        let result = unsafe { &*remove_action(&action_map, &panel_id, &action_id) };
2186
2187        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("id")).map(|value| value.as_str().to_string()), Some("open".to_string()));
2188        assert!(result.get_idx(1).is_some_and(|value| value.is_null()));
2189        assert!(action_map.get_dynamic("panel#open").is_none());
2190        Ok(())
2191    }
2192
2193    #[test]
2194    fn dynamic_field_value_participates_in_or_expression() -> anyhow::Result<()> {
2195        let vm = Vm::with_all()?;
2196        vm.import_code(
2197            "vm_dynamic_field_or",
2198            r#"
2199            pub fn direct_next() {
2200                let choice = {
2201                    label: "颜色",
2202                    next: "color"
2203                };
2204                choice.next
2205            }
2206
2207            pub fn bracket_next() {
2208                let choice = {
2209                    label: "颜色",
2210                    next: "color"
2211                };
2212                choice["next"]
2213            }
2214            "#
2215            .as_bytes()
2216            .to_vec(),
2217        )?;
2218
2219        let compiled = vm.get_fn("vm_dynamic_field_or::direct_next", &[])?;
2220        assert_eq!(compiled.ret_ty(), &Type::Any);
2221        let direct_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2222        assert_eq!(unsafe { &*direct_next() }.as_str(), "color");
2223
2224        let compiled = vm.get_fn("vm_dynamic_field_or::bracket_next", &[])?;
2225        assert_eq!(compiled.ret_ty(), &Type::Any);
2226        let bracket_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2227        assert_eq!(unsafe { &*bracket_next() }.as_str(), "color");
2228        Ok(())
2229    }
2230
2231    #[test]
2232    fn empty_object_literal_in_if_branch_stays_dynamic() -> anyhow::Result<()> {
2233        let vm = Vm::with_all()?;
2234        vm.import_code(
2235            "vm_if_empty_object_branch",
2236            r#"
2237            pub fn first_note(steps) {
2238                let first = if steps.len() > 0 { steps[0] } else { {} };
2239                let first_note = if first.contains("note") { first.note } else { "fallback" };
2240                first_note
2241            }
2242
2243            pub fn first_ja(steps) {
2244                let first = if steps.len() > 0 { steps[0] } else { {} };
2245                if first.contains("ja") { first.ja } else { "すみません" }
2246            }
2247
2248            pub fn assign_first_note(steps) {
2249                let first = {};
2250                first = if steps.len() > 0 { steps[0] } else { {} };
2251                if first.contains("note") { first.note } else { "fallback" }
2252            }
2253            "#
2254            .as_bytes()
2255            .to_vec(),
2256        )?;
2257
2258        let compiled = vm.get_fn("vm_if_empty_object_branch::first_note", &[Type::Any])?;
2259        assert_eq!(compiled.ret_ty(), &Type::Str);
2260        let first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2261
2262        let empty_steps = Dynamic::list(Vec::new());
2263        assert_eq!(unsafe { &*first_note(&empty_steps) }.as_str(), "fallback");
2264
2265        let mut step = std::collections::BTreeMap::new();
2266        step.insert("note".into(), "hello".into());
2267        let steps = Dynamic::list(vec![Dynamic::map(step)]);
2268        assert_eq!(unsafe { &*first_note(&steps) }.as_str(), "hello");
2269
2270        let compiled = vm.get_fn("vm_if_empty_object_branch::first_ja", &[Type::Any])?;
2271        assert_eq!(compiled.ret_ty(), &Type::Any);
2272        let first_ja: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2273        assert_eq!(unsafe { &*first_ja(&empty_steps) }.as_str(), "すみません");
2274
2275        let compiled = vm.get_fn("vm_if_empty_object_branch::assign_first_note", &[Type::Any])?;
2276        assert_eq!(compiled.ret_ty(), &Type::Any);
2277        let assign_first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2278        assert_eq!(unsafe { &*assign_first_note(&empty_steps) }.as_str(), "fallback");
2279        assert_eq!(unsafe { &*assign_first_note(&steps) }.as_str(), "hello");
2280        Ok(())
2281    }
2282
2283    #[test]
2284    fn list_literal_can_be_function_tail_expression() -> anyhow::Result<()> {
2285        let vm = Vm::with_all()?;
2286        vm.import_code(
2287            "vm_tail_list_literal",
2288            r#"
2289            pub fn numbers() {
2290                [1, 2, 3]
2291            }
2292
2293            pub fn maps() {
2294                [
2295                    {note: "first"},
2296                    {note: "second"}
2297                ]
2298            }
2299
2300            pub fn object_with_maps() {
2301                {
2302                    steps: [
2303                        {note: "first"},
2304                        {note: "second"}
2305                    ]
2306                }
2307            }
2308
2309            pub fn return_maps() {
2310                return [
2311                    {note: "first"},
2312                    {note: "second"}
2313                ];
2314            }
2315
2316            pub fn return_maps_without_semicolon() {
2317                return [
2318                    {note: "first"},
2319                    {note: "second"}
2320                ]
2321            }
2322
2323            pub fn tail_bare_variable() {
2324                let value = [
2325                    {note: "first"},
2326                    {note: "second"}
2327                ];
2328                value
2329            }
2330
2331            pub fn return_bare_variable_without_semicolon() {
2332                let value = [
2333                    {note: "first"},
2334                    {note: "second"}
2335                ];
2336                return value
2337            }
2338
2339            pub fn tail_object_variable() {
2340                let result = {
2341                    steps: [
2342                        {note: "first"},
2343                        {note: "second"}
2344                    ]
2345                };
2346                result
2347            }
2348            "#
2349            .as_bytes()
2350            .to_vec(),
2351        )?;
2352
2353        let compiled = vm.get_fn("vm_tail_list_literal::numbers", &[])?;
2354        assert_eq!(compiled.ret_ty(), &Type::Any);
2355        let numbers: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2356        let result = unsafe { &*numbers() };
2357        assert_eq!(result.len(), 3);
2358        assert_eq!(result.get_idx(1).and_then(|value| value.as_int()), Some(2));
2359
2360        let compiled = vm.get_fn("vm_tail_list_literal::maps", &[])?;
2361        assert_eq!(compiled.ret_ty(), &Type::Any);
2362        let maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2363        let result = unsafe { &*maps() };
2364        assert_eq!(result.len(), 2);
2365        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2366
2367        let compiled = vm.get_fn("vm_tail_list_literal::object_with_maps", &[])?;
2368        assert_eq!(compiled.ret_ty(), &Type::Any);
2369        let object_with_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2370        let result = unsafe { &*object_with_maps() };
2371        let steps = result.get_dynamic("steps").expect("steps");
2372        assert_eq!(steps.len(), 2);
2373        assert_eq!(steps.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
2374
2375        let compiled = vm.get_fn("vm_tail_list_literal::return_maps", &[])?;
2376        assert_eq!(compiled.ret_ty(), &Type::Any);
2377        let return_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2378        let result = unsafe { &*return_maps() };
2379        assert_eq!(result.len(), 2);
2380        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2381
2382        let compiled = vm.get_fn("vm_tail_list_literal::return_maps_without_semicolon", &[])?;
2383        assert_eq!(compiled.ret_ty(), &Type::Any);
2384        let return_maps_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2385        let result = unsafe { &*return_maps_without_semicolon() };
2386        assert_eq!(result.len(), 2);
2387        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
2388
2389        let compiled = vm.get_fn("vm_tail_list_literal::tail_bare_variable", &[])?;
2390        assert_eq!(compiled.ret_ty(), &Type::Any);
2391        let tail_bare_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2392        let result = unsafe { &*tail_bare_variable() };
2393        assert_eq!(result.len(), 2);
2394        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2395
2396        let compiled = vm.get_fn("vm_tail_list_literal::return_bare_variable_without_semicolon", &[])?;
2397        assert_eq!(compiled.ret_ty(), &Type::Any);
2398        let return_bare_variable_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2399        let result = unsafe { &*return_bare_variable_without_semicolon() };
2400        assert_eq!(result.len(), 2);
2401        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
2402
2403        let compiled = vm.get_fn("vm_tail_list_literal::tail_object_variable", &[])?;
2404        assert_eq!(compiled.ret_ty(), &Type::Any);
2405        let tail_object_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2406        let result = unsafe { &*tail_object_variable() };
2407        let steps = result.get_dynamic("steps").expect("steps");
2408        assert_eq!(steps.len(), 2);
2409        assert_eq!(steps.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
2410        Ok(())
2411    }
2412
2413    #[test]
2414    fn list_return_value_supports_get_idx_method_call() -> anyhow::Result<()> {
2415        let vm = Vm::with_all()?;
2416        vm.import_code(
2417            "vm_returned_list_get_idx",
2418            r#"
2419            pub fn ids() {
2420                [
2421                    "base",
2422                    "2",
2423                    "3"
2424                ]
2425            }
2426
2427            pub fn combinations() {
2428                let result = [];
2429                let values = ids();
2430                let idx = 0;
2431                while idx < values.len() {
2432                    result.push(values.get_idx(idx));
2433                    idx = idx + 1;
2434                }
2435                result
2436            }
2437            "#
2438            .as_bytes()
2439            .to_vec(),
2440        )?;
2441
2442        let compiled = vm.get_fn("vm_returned_list_get_idx::combinations", &[])?;
2443        assert_eq!(compiled.ret_ty(), &Type::Any);
2444        let combinations: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2445        let result = unsafe { &*combinations() };
2446
2447        assert_eq!(result.len(), 3);
2448        assert_eq!(result.get_idx(0).map(|value| value.as_str().to_string()), Some("base".to_string()));
2449        assert_eq!(result.get_idx(2).map(|value| value.as_str().to_string()), Some("3".to_string()));
2450        Ok(())
2451    }
2452
2453    #[test]
2454    fn repeated_deep_step_literals_import_successfully() -> anyhow::Result<()> {
2455        fn extra_page_literal(depth: usize) -> String {
2456            let mut value = "{leaf: \"done\"}".to_string();
2457            for idx in 0..depth {
2458                value = format!("{{kind: \"page\", idx: {idx}, children: [{value}], meta: {{title: \"extra\", visible: true}}}}");
2459            }
2460            value
2461        }
2462
2463        let extra = extra_page_literal(48);
2464        let code = format!(
2465            r#"
2466            pub fn script() {{
2467                return [
2468                    {{ja: "一つ目", note: "first", extra: {extra}}},
2469                    {{ja: "二つ目", note: "second", extra: {extra}}},
2470                    {{ja: "三つ目", note: "third", extra: {extra}}}
2471                ]
2472            }}
2473            "#
2474        );
2475
2476        let vm = Vm::with_all()?;
2477        vm.import_code("vm_repeated_deep_step_literals", code.into_bytes())?;
2478        let compiled = vm.get_fn("vm_repeated_deep_step_literals::script", &[])?;
2479        assert_eq!(compiled.ret_ty(), &Type::Any);
2480        let script: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2481        let result = unsafe { &*script() };
2482        assert_eq!(result.len(), 3);
2483        assert_eq!(result.get_idx(2).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("third".to_string()));
2484        Ok(())
2485    }
2486
2487    #[test]
2488    fn native_import_uses_owning_vm() -> anyhow::Result<()> {
2489        let module_path = std::env::temp_dir().join(format!("zust_vm_import_owner_{}.zs", std::process::id()));
2490        std::fs::write(&module_path, "pub fn value() { 41 }")?;
2491        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
2492
2493        let vm1 = Vm::with_all()?;
2494        vm1.import_code(
2495            "vm_import_owner",
2496            format!(
2497                r#"
2498                pub fn run() {{
2499                    import("vm_imported_owner", "{module_path}");
2500                }}
2501                "#
2502            )
2503            .into_bytes(),
2504        )?;
2505        let compiled = vm1.get_fn("vm_import_owner::run", &[])?;
2506
2507        let vm2 = Vm::with_all()?;
2508        vm2.import_code("vm_import_other", b"pub fn run() { 0 }".to_vec())?;
2509        let _ = vm2.get_fn("vm_import_other::run", &[])?;
2510
2511        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
2512        run();
2513
2514        assert!(vm1.get_fn("vm_imported_owner::value", &[]).is_ok());
2515        assert!(vm2.get_fn("vm_imported_owner::value", &[]).is_err());
2516        Ok(())
2517    }
2518
2519    #[test]
2520    fn object_last_field_call_does_not_need_trailing_comma() -> anyhow::Result<()> {
2521        let vm = Vm::with_all()?;
2522        vm.import_code(
2523            "vm_object_last_call_field",
2524            r#"
2525            pub fn extra_page() {
2526                {
2527                    title: "extra",
2528                    pages: [
2529                        {note: "nested"}
2530                    ]
2531                }
2532            }
2533
2534            pub fn data() {
2535                return [
2536                    {
2537                        note: "first",
2538                        choices: ["a", "b"],
2539                        extras: extra_page()
2540                    },
2541                    {
2542                        note: "second",
2543                        choices: ["c"],
2544                        extras: extra_page()
2545                    }
2546                ]
2547            }
2548            "#
2549            .as_bytes()
2550            .to_vec(),
2551        )?;
2552
2553        let compiled = vm.get_fn("vm_object_last_call_field::data", &[])?;
2554        assert_eq!(compiled.ret_ty(), &Type::Any);
2555        let data: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2556        let result = unsafe { &*data() };
2557        assert_eq!(result.len(), 2);
2558        let first = result.get_idx(0).expect("first step");
2559        assert_eq!(first.get_dynamic("extras").and_then(|extras| extras.get_dynamic("title")).map(|title| title.as_str().to_string()), Some("extra".to_string()));
2560        Ok(())
2561    }
2562
2563    #[test]
2564    fn string_return_survives_scope_exit() -> anyhow::Result<()> {
2565        let vm = Vm::with_all()?;
2566        vm.import_code(
2567            "vm_string_return_scope",
2568            r#"
2569            pub fn source_root() {
2570                "../assets/character/男主角换装"
2571            }
2572
2573            pub fn binary_root() {
2574                "character_binary/男主角换装"
2575            }
2576
2577            pub fn runtime_binary_url() {
2578                "/" + binary_root()
2579            }
2580
2581            pub fn action_groups() {
2582                let root = source_root();
2583                let binary_url = runtime_binary_url();
2584                let binary_root = binary_root();
2585                [
2586                    {
2587                        id: "field_bottom",
2588                        source_spine: root + "/战斗外/boy_b.spine",
2589                        skeleton: binary_url + "/战斗外/boy_b/boy_b.skel.bytes",
2590                        export_skeleton: binary_root + "/战斗外/boy_b/boy_b.skel.bytes"
2591                    }
2592                ]
2593            }
2594            "#
2595            .as_bytes()
2596            .to_vec(),
2597        )?;
2598
2599        let compiled = vm.get_fn("vm_string_return_scope::source_root", &[])?;
2600        assert_eq!(compiled.ret_ty(), &Type::Str);
2601        let source_root: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2602        let source_root = unsafe { &*source_root() };
2603        assert_eq!(source_root.as_str(), "../assets/character/男主角换装");
2604
2605        let compiled = vm.get_fn("vm_string_return_scope::action_groups", &[])?;
2606        assert_eq!(compiled.ret_ty(), &Type::Any);
2607        let action_groups: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2608        let groups = unsafe { &*action_groups() };
2609        let first = groups.get_idx(0).expect("first action group");
2610        assert_eq!(first.get_dynamic("source_spine").map(|value| value.as_str().to_string()), Some("../assets/character/男主角换装/战斗外/boy_b.spine".to_string()));
2611        assert_eq!(first.get_dynamic("skeleton").map(|value| value.as_str().to_string()), Some("/character_binary/男主角换装/战斗外/boy_b/boy_b.skel.bytes".to_string()));
2612        Ok(())
2613    }
2614
2615    #[test]
2616    fn dynamic_string_add_uses_any_binary_fast_path() -> anyhow::Result<()> {
2617        let vm = Vm::with_all()?;
2618        vm.import_code(
2619            "vm_dynamic_string_add",
2620            br#"
2621            pub fn concat(left, right) {
2622                left + right
2623            }
2624            "#
2625            .to_vec(),
2626        )?;
2627
2628        let compiled = vm.get_fn("vm_dynamic_string_add::concat", &[Type::Any, Type::Any])?;
2629        assert_eq!(compiled.ret_ty(), &Type::Any);
2630        let concat: extern "C" fn(*const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2631        let left = Dynamic::from("hello");
2632        let right = Dynamic::from(" world");
2633        let result = unsafe { &*concat(&left, &right) };
2634        assert_eq!(result.as_str(), "hello world");
2635        Ok(())
2636    }
2637
2638    #[test]
2639    fn large_dynamic_object_accepts_inline_call_fields() -> anyhow::Result<()> {
2640        let vm = Vm::with_all()?;
2641        let model_count = 180;
2642        let combination_count = 90;
2643        let models = (0..model_count)
2644            .map(|idx| {
2645                format!(
2646                    r#"{{id: "model_{idx}", name: "模型_{idx}", source: "/美术资源/角色/少年/套装_{idx}/模型_{idx}.model.json", parts: [
2647                        {{slot: "hair", path: "/模型/头发/颜色_{idx}/默认.png", z: 10}},
2648                        {{slot: "body", path: "/模型/身体/套装_{idx}/默认.png", z: 1}},
2649                        {{slot: "face", path: "/模型/表情/表情_{idx}/默认.png", z: 20}}
2650                    ]}}"#
2651                )
2652            })
2653            .collect::<Vec<_>>()
2654            .join(",\n");
2655        let combinations = (0..combination_count).map(|idx| format!(r#"{{hair: "color_{idx}", body: "set_{idx}", face: "face_{idx}"}}"#)).collect::<Vec<_>>().join(",\n");
2656        let code = format!(
2657            r#"
2658            pub fn source_root() {{
2659                "/美术资源/角色/少年/默认"
2660            }}
2661
2662            pub fn runtime_boy_url() {{
2663                "/cdn/runtime/角色/少年/少年.model.json"
2664            }}
2665
2666            pub fn parts() {{
2667                [
2668                    {{id: "hair", path: "/模型/头发/黑色/默认.png", z: 10}},
2669                    {{id: "body", path: "/模型/身体/校服/默认.png", z: 1}},
2670                    {{id: "face", path: "/模型/表情/微笑/默认.png", z: 20}}
2671                ]
2672            }}
2673
2674            pub fn action_groups() {{
2675                {{
2676                    idle: [
2677                        {{id: "stand", name: "站立", frames: ["待机/0001.png", "待机/0002.png"]}},
2678                        {{id: "blink", name: "眨眼", frames: ["表情/眨眼/0001.png", "表情/眨眼/0002.png"]}}
2679                    ],
2680                    move: [
2681                        {{id: "walk", name: "行走", frames: ["行走/0001.png", "行走/0002.png"]}},
2682                        {{id: "run", name: "奔跑", frames: ["奔跑/0001.png", "奔跑/0002.png"]}}
2683                    ]
2684                }}
2685            }}
2686
2687            pub fn default_model() {{
2688                {{
2689                    id: "runtime_boy",
2690                    name: "运行时少年",
2691                    skins: [
2692                        {{id: "school", title: "校服", source: "/套装/校服/model.json"}},
2693                        {{id: "casual", title: "便服", source: "/套装/便服/model.json"}}
2694                    ],
2695                    models: [
2696                        {models}
2697                    ]
2698                }}
2699            }}
2700
2701            pub fn first_nine_combinations() {{
2702                [
2703                    {combinations}
2704                ]
2705            }}
2706
2707            pub fn config() {{
2708                {{
2709                    source_root: source_root(),
2710                    runtime_boy_url: runtime_boy_url(),
2711                    parts: parts(),
2712                    action_groups: action_groups(),
2713                    default_model: default_model(),
2714                    first_nine_combinations: first_nine_combinations()
2715                }}
2716            }}
2717
2718            pub fn start() {{
2719                root::add("local/vm_large_inline_call_object/config", {{
2720                    source_root: source_root(),
2721                    runtime_boy_url: runtime_boy_url(),
2722                    parts: parts(),
2723                    action_groups: action_groups(),
2724                    default_model: default_model(),
2725                    first_nine_combinations: first_nine_combinations()
2726                }})
2727            }}
2728            "#
2729        );
2730        vm.import_code("vm_large_inline_call_object", code.into_bytes())?;
2731
2732        let compiled = vm.get_fn("vm_large_inline_call_object::config", &[])?;
2733        assert_eq!(compiled.ret_ty(), &Type::Any);
2734        let config: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2735        let result = unsafe { &*config() };
2736        assert_eq!(result.get_dynamic("source_root").map(|value| value.as_str().to_string()), Some("/美术资源/角色/少年/默认".to_string()));
2737        assert_eq!(result.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
2738
2739        let compiled = vm.get_fn("vm_large_inline_call_object::start", &[])?;
2740        assert_eq!(compiled.ret_ty(), &Type::Bool);
2741        let start: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
2742        assert!(start());
2743        let saved = root::get("local/vm_large_inline_call_object/config")?;
2744        assert_eq!(saved.get_dynamic("first_nine_combinations").map(|value| value.len()), Some(combination_count));
2745        Ok(())
2746    }
2747
2748    #[test]
2749    fn http_serve_accepts_inline_config_map() -> anyhow::Result<()> {
2750        let vm = Vm::with_all()?;
2751        vm.import_code(
2752            "vm_http_serve_inline_config",
2753            br#"
2754            pub fn start() {
2755                let server = http::serve({host: "127.0.0.1:5192"});
2756                server
2757            }
2758            "#
2759            .to_vec(),
2760        )?;
2761
2762        let compiled = vm.get_fn("vm_http_serve_inline_config::start", &[])?;
2763        assert_eq!(compiled.ret_ty(), &Type::Any);
2764        Ok(())
2765    }
2766
2767    #[test]
2768    fn http_serve_accepts_variable_and_quoted_static_key() -> anyhow::Result<()> {
2769        let vm = Vm::with_all()?;
2770        vm.import_code(
2771            "vm_http_serve_quoted_static",
2772            br#"
2773            pub fn start(server_addr) {
2774                let http_server = http::serve({
2775                    host: server_addr,
2776                    ws: true,
2777                    upload: "upload",
2778                    "static": {
2779                        path: "/",
2780                        dir: "public/local"
2781                    }
2782                });
2783                http_server
2784            }
2785            "#
2786            .to_vec(),
2787        )?;
2788
2789        let compiled = vm.get_fn("vm_http_serve_quoted_static::start", &[Type::Any])?;
2790        assert_eq!(compiled.ret_ty(), &Type::Any);
2791        Ok(())
2792    }
2793
2794    #[test]
2795    fn oss_helpers_accept_explicit_config() -> anyhow::Result<()> {
2796        let vm = Vm::with_all()?;
2797        vm.import_code(
2798            "vm_oss_explicit_config",
2799            br#"
2800            pub fn upload(oss, bytes) {
2801                oss::upload(oss, "llm/input/audio.wav", bytes)
2802            }
2803
2804            pub fn http_upload(oss, bytes) {
2805                http::upload(oss, "uploads/input.bin", bytes)
2806            }
2807
2808            pub fn link(oss, uploaded) {
2809                oss::signed_url(oss, {oss_url: uploaded, expires: 3600})
2810            }
2811            "#
2812            .to_vec(),
2813        )?;
2814
2815        assert_eq!(vm.get_fn("vm_oss_explicit_config::upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
2816        assert_eq!(vm.get_fn("vm_oss_explicit_config::http_upload", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
2817        assert_eq!(vm.get_fn("vm_oss_explicit_config::link", &[Type::Any, Type::Any])?.ret_ty(), &Type::Any);
2818        Ok(())
2819    }
2820
2821    #[test]
2822    fn load_script_accepts_http_serve_inline_config() -> anyhow::Result<()> {
2823        let vm = Vm::with_all()?;
2824        let (_fn_ptr, ty) = vm.load(
2825            br#"
2826            let server_addr = "127.0.0.1:5192";
2827            let http_server = http::serve({
2828                host: server_addr,
2829                ws: true,
2830                upload: "upload",
2831                "static": {
2832                    path: "/",
2833                    dir: "public/local"
2834                }
2835            });
2836            http_server
2837            "#
2838            .to_vec(),
2839            "arg".into(),
2840        )?;
2841
2842        assert_eq!(ty, Type::Any);
2843        Ok(())
2844    }
2845
2846    #[test]
2847    fn load_script_resolves_import_before_compile() -> anyhow::Result<()> {
2848        let module_path = std::env::temp_dir().join(format!("zust_vm_load_import_{}.zs", std::process::id()));
2849        std::fs::write(&module_path, "pub fn init() { return {ok: true}; }")?;
2850        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
2851
2852        let vm = Vm::with_all()?;
2853        let (_fn_ptr, ty) = vm.load(
2854            format!(
2855                r#"
2856                import("create_scene", "{module_path}");
2857                create_scene::init();
2858                "#
2859            )
2860            .into_bytes(),
2861            "req".into(),
2862        )?;
2863
2864        assert_eq!(ty, Type::Void);
2865        Ok(())
2866    }
2867
2868    #[test]
2869    fn gpu_struct_layout_packs_and_unpacks_dynamic_maps() -> anyhow::Result<()> {
2870        let vm = Vm::with_all()?;
2871        vm.import_code(
2872            "vm_gpu_layout",
2873            br#"
2874            pub struct Params {
2875                a: u32,
2876                b: u32,
2877                c: u32,
2878            }
2879            "#
2880            .to_vec(),
2881        )?;
2882
2883        let layout = vm.gpu_struct_layout("vm_gpu_layout::Params", &[])?;
2884        assert_eq!(layout.size, 16);
2885        assert_eq!(layout.fields.iter().map(|field| (field.name.as_str(), field.offset)).collect::<Vec<_>>(), vec![("a", 0), ("b", 4), ("c", 8)]);
2886
2887        let value = dynamic::map!("a"=> 1u32, "b"=> 2u32, "c"=> 3u32);
2888        let bytes = layout.pack_map(&value)?;
2889        assert_eq!(bytes.len(), 16);
2890        assert_eq!(&bytes[0..4], &1u32.to_ne_bytes());
2891        assert_eq!(&bytes[4..8], &2u32.to_ne_bytes());
2892        assert_eq!(&bytes[8..12], &3u32.to_ne_bytes());
2893
2894        let read = layout.unpack_map(&bytes)?;
2895        assert_eq!(read.get_dynamic("a").and_then(|value| value.as_uint()), Some(1));
2896        assert_eq!(read.get_dynamic("b").and_then(|value| value.as_uint()), Some(2));
2897        assert_eq!(read.get_dynamic("c").and_then(|value| value.as_uint()), Some(3));
2898        Ok(())
2899    }
2900
2901    #[test]
2902    fn root_native_calls_do_not_take_ownership_of_dynamic_args() -> anyhow::Result<()> {
2903        let vm = Vm::with_all()?;
2904        vm.import_code(
2905            "vm_root_clone_bridge",
2906            br#"
2907            pub fn add_then_reuse(arg) {
2908                let user = {
2909                    address: "test-wallet",
2910                    points: 20
2911                };
2912                root::add("local/root-clone-bridge-user", user);
2913                user.points = user.points - 7;
2914                root::add("local/root-clone-bridge-user", user);
2915                {
2916                    user: user,
2917                    points: user.points
2918                }
2919            }
2920
2921            pub fn clone_then_mutate(arg) {
2922                let user = {
2923                    profile: {
2924                        points: 20
2925                    }
2926                };
2927                let copied = user.clone();
2928                copied.profile.points = 13;
2929                user
2930            }
2931            "#
2932            .to_vec(),
2933        )?;
2934
2935        let compiled = vm.get_fn("vm_root_clone_bridge::add_then_reuse", &[Type::Any])?;
2936        assert_eq!(compiled.ret_ty(), &Type::Any);
2937        let add_then_reuse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
2938        let arg = Dynamic::Null;
2939        let result = add_then_reuse(&arg);
2940        let result = unsafe { &*result };
2941
2942        assert_eq!(result.get_dynamic("points").and_then(|value| value.as_int()), Some(13));
2943        let mut json = String::new();
2944        result.to_json(&mut json);
2945        assert!(json.contains("\"points\": 13"));
2946
2947        let clone_then_mutate = vm.get_fn("vm_root_clone_bridge::clone_then_mutate", &[Type::Any])?;
2948        let clone_then_mutate: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(clone_then_mutate.ptr()) };
2949        let result = clone_then_mutate(&arg);
2950        let result = unsafe { &*result };
2951        assert_eq!(result.get_dynamic("profile").unwrap().get_dynamic("points").and_then(|value| value.as_int()), Some(20));
2952        Ok(())
2953    }
2954
2955    struct CounterForTypedReceiver {
2956        value: i64,
2957    }
2958
2959    extern "C" fn counter_for_typed_receiver_get(value: *const Dynamic) -> i64 {
2960        unsafe { &*value }.as_custom::<CounterForTypedReceiver>().map(|counter| counter.value).unwrap_or(-1)
2961    }
2962
2963    struct NavMapForFunctionArg;
2964
2965    extern "C" fn nav_map_for_function_arg_new() -> *const Dynamic {
2966        Box::into_raw(Box::new(Dynamic::custom(NavMapForFunctionArg)))
2967    }
2968
2969    #[derive(Debug, Default)]
2970    struct PropertyForwardingObject {
2971        values: RwLock<BTreeMap<String, Dynamic>>,
2972    }
2973
2974    impl CustomProperty for PropertyForwardingObject {
2975        fn get_key(&self, key: &str) -> Option<Dynamic> {
2976            self.values.read().unwrap().get(key).cloned()
2977        }
2978
2979        fn set_key(&self, key: &str, value: Dynamic) -> bool {
2980            self.values.write().unwrap().insert(key.to_string(), value);
2981            true
2982        }
2983    }
2984
2985    extern "C" fn property_forwarding_object_new() -> *const Dynamic {
2986        Box::into_raw(Box::new(Dynamic::custom_with_properties(PropertyForwardingObject::default())))
2987    }
2988
2989    #[test]
2990    fn typed_receiver_method_call_dispatches_with_type_hint() -> anyhow::Result<()> {
2991        let vm = Vm::with_all()?;
2992        vm.add_empty_type("Counter")?;
2993        let counter_ty = vm.get_symbol("Counter", Vec::new())?;
2994        vm.add_native_method_ptr("Counter", "get", &[counter_ty], Type::I64, counter_for_typed_receiver_get as *const u8)?;
2995        vm.import_code(
2996            "vm_typed_receiver_method",
2997            br#"
2998            pub fn run(value) {
2999                value::<Counter>::get()
3000            }
3001            "#
3002            .to_vec(),
3003        )?;
3004
3005        let compiled = vm.get_fn("vm_typed_receiver_method::run", &[Type::Any])?;
3006        assert_eq!(compiled.ret_ty(), &Type::I64);
3007        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3008        let value = Dynamic::custom(CounterForTypedReceiver { value: 42 });
3009
3010        assert_eq!(run(&value), 42);
3011        Ok(())
3012    }
3013
3014    #[test]
3015    fn native_custom_object_can_be_passed_to_zs_function() -> anyhow::Result<()> {
3016        let vm = Vm::with_all()?;
3017        vm.add_empty_type("NavMap")?;
3018        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
3019        vm.import_code(
3020            "vm_native_custom_arg",
3021            br#"
3022            pub fn add_nav_spawns(world, navmap) {
3023                navmap
3024            }
3025
3026            pub fn run(world) {
3027                let navmap = NavMap::new();
3028                let with_spawns = add_nav_spawns(world, navmap);
3029                with_spawns
3030            }
3031            "#
3032            .to_vec(),
3033        )?;
3034
3035        let compiled = vm.get_fn("vm_native_custom_arg::run", &[Type::Any])?;
3036        assert_eq!(compiled.ret_ty(), &Type::Any);
3037        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3038        let world = Dynamic::Null;
3039        let result = run(&world);
3040        let result = unsafe { &*result };
3041
3042        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
3043        Ok(())
3044    }
3045
3046    #[test]
3047    fn any_field_assignment_forwards_to_custom_properties() -> anyhow::Result<()> {
3048        let vm = Vm::with_all()?;
3049        vm.add_empty_type("Dialog")?;
3050        vm.add_native_method_ptr("Dialog", "new", &[], Type::Any, property_forwarding_object_new as *const u8)?;
3051        vm.import_code(
3052            "vm_custom_property_forwarding",
3053            br#"
3054            pub fn run() {
3055                let dialog = Dialog::new();
3056                dialog.file_mode = 3;
3057                dialog.file_mode
3058            }
3059            "#
3060            .to_vec(),
3061        )?;
3062
3063        let compiled = vm.get_fn("vm_custom_property_forwarding::run", &[])?;
3064        assert_eq!(compiled.ret_ty(), &Type::Any);
3065        let run: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3066        let result = unsafe { &*run() };
3067
3068        assert_eq!(result.as_int(), Some(3));
3069        Ok(())
3070    }
3071
3072    #[test]
3073    fn native_custom_object_typed_local_can_be_passed_to_zs_function() -> anyhow::Result<()> {
3074        let vm = Vm::with_all()?;
3075        vm.add_empty_type("NavMap")?;
3076        let _nav_map_ty = vm.get_symbol("NavMap", Vec::new())?;
3077        vm.add_native_method_ptr("NavMap", "new", &[], Type::Any, nav_map_for_function_arg_new as *const u8)?;
3078        vm.import_code(
3079            "vm_native_custom_typed_arg",
3080            br#"
3081            pub fn add_nav_spawns(world, navmap) {
3082                navmap
3083            }
3084
3085            pub fn run(world) {
3086                let navmap: NavMap = NavMap::new();
3087                let with_spawns = add_nav_spawns(world, navmap);
3088                with_spawns
3089            }
3090            "#
3091            .to_vec(),
3092        )?;
3093
3094        let compiled = vm.get_fn("vm_native_custom_typed_arg::run", &[Type::Any])?;
3095        let run: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3096        let world = Dynamic::Null;
3097        let result = run(&world);
3098        let result = unsafe { &*result };
3099
3100        assert!(result.as_custom::<NavMapForFunctionArg>().is_some());
3101        Ok(())
3102    }
3103
3104    // ---- 新增边界条件测试 ----
3105
3106    #[test]
3107    fn dynamic_type_checks_on_null_and_primitive_values() -> anyhow::Result<()> {
3108        let vm = Vm::with_all()?;
3109        vm.import_code(
3110            "vm_dynamic_type_checks",
3111            br#"
3112            pub fn is_list_on_int() {
3113                let x = 42i64;
3114                x.is_list()
3115            }
3116
3117            pub fn is_map_on_int() {
3118                let x = 42i64;
3119                x.is_map()
3120            }
3121
3122            pub fn is_null_on_int() {
3123                let x = 42i64;
3124                x.is_null()
3125            }
3126            "#
3127            .to_vec(),
3128        )?;
3129
3130        let compiled = vm.get_fn("vm_dynamic_type_checks::is_list_on_int", &[])?;
3131        assert_eq!(compiled.ret_ty(), &Type::Bool);
3132        let is_list_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3133        assert!(!is_list_on_int());
3134
3135        let compiled = vm.get_fn("vm_dynamic_type_checks::is_map_on_int", &[])?;
3136        assert_eq!(compiled.ret_ty(), &Type::Bool);
3137        let is_map_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3138        assert!(!is_map_on_int());
3139
3140        let compiled = vm.get_fn("vm_dynamic_type_checks::is_null_on_int", &[])?;
3141        assert_eq!(compiled.ret_ty(), &Type::Bool);
3142        let is_null_on_int: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3143        assert!(!is_null_on_int());
3144        Ok(())
3145    }
3146
3147    #[test]
3148    fn empty_for_loop_range_has_zero_iterations() -> anyhow::Result<()> {
3149        let vm = Vm::with_all()?;
3150        vm.import_code(
3151            "vm_empty_for_range",
3152            br#"
3153            pub fn empty_exclusive() {
3154                let count = 0i32;
3155                for i in 0..0 {
3156                    count += i;
3157                }
3158                count
3159            }
3160
3161            pub fn single_inclusive_iteration() {
3162                let count = 0i32;
3163                for i in 5..=5 {
3164                    count += i;
3165                }
3166                count
3167            }
3168            "#
3169            .to_vec(),
3170        )?;
3171
3172        let compiled = vm.get_fn("vm_empty_for_range::empty_exclusive", &[])?;
3173        assert_eq!(compiled.ret_ty(), &Type::I32);
3174        let empty_exclusive: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3175        assert_eq!(empty_exclusive(), 0);
3176
3177        let compiled = vm.get_fn("vm_empty_for_range::single_inclusive_iteration", &[])?;
3178        assert_eq!(compiled.ret_ty(), &Type::I32);
3179        let single_inclusive: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3180        assert_eq!(single_inclusive(), 5);
3181        Ok(())
3182    }
3183
3184    #[test]
3185    fn map_contains_key_on_non_existent_and_nested_keys() -> anyhow::Result<()> {
3186        let vm = Vm::with_all()?;
3187        vm.import_code(
3188            "vm_map_contains",
3189            br#"
3190            pub fn contains_existing(data) {
3191                data.contains("name")
3192            }
3193
3194            pub fn contains_missing(data) {
3195                data.contains("nothing")
3196            }
3197            "#
3198            .to_vec(),
3199        )?;
3200
3201        let compiled = vm.get_fn("vm_map_contains::contains_existing", &[Type::Any])?;
3202        assert_eq!(compiled.ret_ty(), &Type::Bool);
3203        let contains_existing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3204        let data = dynamic::map!("name"=> "test");
3205        assert!(contains_existing(&data));
3206
3207        let compiled = vm.get_fn("vm_map_contains::contains_missing", &[Type::Any])?;
3208        assert_eq!(compiled.ret_ty(), &Type::Bool);
3209        let contains_missing: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3210        assert!(!contains_missing(&data));
3211        Ok(())
3212    }
3213
3214    #[test]
3215    fn list_pop_on_empty_list_returns_null() -> anyhow::Result<()> {
3216        let vm = Vm::with_all()?;
3217        vm.import_code(
3218            "vm_pop_empty",
3219            br#"
3220            pub fn pop_new_list() {
3221                let items = [];
3222                let value = items.pop();
3223                let still_empty = items.len() == 0;
3224                {value: value, empty: still_empty}
3225            }
3226
3227            pub fn pop_until_empty() {
3228                let items = [1i64, 2i64];
3229                items.pop();
3230                let last = items.pop();
3231                let drained = items.pop();
3232                {last: last, drained: drained}
3233            }
3234            "#
3235            .to_vec(),
3236        )?;
3237
3238        let compiled = vm.get_fn("vm_pop_empty::pop_new_list", &[])?;
3239        assert_eq!(compiled.ret_ty(), &Type::Any);
3240        let pop_new_list: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3241        let result = unsafe { &*pop_new_list() };
3242        assert!(result.get_dynamic("value").is_some_and(|v| v.is_null()));
3243        assert_eq!(result.get_dynamic("empty").and_then(|v| v.as_bool()), Some(true));
3244
3245        let compiled = vm.get_fn("vm_pop_empty::pop_until_empty", &[])?;
3246        assert_eq!(compiled.ret_ty(), &Type::Any);
3247        let pop_until_empty: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3248        let result = unsafe { &*pop_until_empty() };
3249        assert_eq!(result.get_dynamic("last").and_then(|v| v.as_int()), Some(1));
3250        assert!(result.get_dynamic("drained").is_some_and(|v| v.is_null()));
3251        Ok(())
3252    }
3253
3254    #[test]
3255    fn void_function_with_multiple_code_paths() -> anyhow::Result<()> {
3256        let vm = Vm::with_all()?;
3257        vm.import_code(
3258            "vm_void_multi_path",
3259            br#"
3260            pub fn log_if_positive(value: i64) {
3261                if value > 0 {
3262                    print(value);
3263                    return;
3264                }
3265                if value < 0 {
3266                    print(-value);
3267                    return;
3268                }
3269                print(0);
3270            }
3271            "#
3272            .to_vec(),
3273        )?;
3274
3275        let compiled = vm.get_fn("vm_void_multi_path::log_if_positive", &[Type::I64])?;
3276        assert!(compiled.ret_ty().is_void());
3277        Ok(())
3278    }
3279
3280    #[test]
3281    fn any_method_call_chain_on_returned_dynamic_value() -> anyhow::Result<()> {
3282        let vm = Vm::with_all()?;
3283        vm.import_code(
3284            "vm_any_method_chain",
3285            br#"
3286            pub fn get_tags(data) {
3287                let tags = data.tags;
3288                if tags.is_list() {
3289                    return tags.len();
3290                }
3291                0
3292            }
3293            "#
3294            .to_vec(),
3295        )?;
3296
3297        let compiled = vm.get_fn("vm_any_method_chain::get_tags", &[Type::Any])?;
3298        assert_eq!(compiled.ret_ty(), &Type::I32);
3299        let get_tags: extern "C" fn(*const Dynamic) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3300        let data = dynamic::map!("tags"=> Dynamic::list(vec!["a".into(), "b".into(), "c".into()]));
3301        assert_eq!(get_tags(&data), 3);
3302
3303        let empty_data = Dynamic::Null;
3304        assert_eq!(get_tags(&empty_data), 0);
3305        Ok(())
3306    }
3307
3308    #[test]
3309    fn infers_any_arg_function_return_before_body_compile() -> anyhow::Result<()> {
3310        let vm = Vm::with_all()?;
3311        vm.import_code(
3312            "vm_infer_any_arg_return",
3313            br#"
3314            pub fn caller(candidate) {
3315                let center = polygon_center(candidate.visualPolygon);
3316                center[0]
3317            }
3318
3319            pub fn polygon_center(point_list) {
3320                let total_x = 0;
3321                let total_y = 0;
3322                let count = 0;
3323                if point_list.is_list() {
3324                    for point in point_list {
3325                        if point.is_list() && point.len() >= 2 {
3326                            total_x += point[0];
3327                            total_y += point[1];
3328                            count += 1;
3329                        }
3330                    }
3331                }
3332                if count == 0 {
3333                    return [0, 0];
3334                }
3335                [total_x / count, total_y / count]
3336            }
3337            "#
3338            .to_vec(),
3339        )?;
3340
3341        let compiled = vm.get_fn("vm_infer_any_arg_return::caller", &[Type::Any])?;
3342        assert_eq!(compiled.ret_ty(), &Type::Any);
3343        let caller: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3344        let candidate = dynamic::map!(
3345            "visualPolygon"=> Dynamic::list(vec![
3346                Dynamic::list(vec![2i64.into(), 4i64.into()]),
3347                Dynamic::list(vec![6i64.into(), 8i64.into()]),
3348            ])
3349        );
3350        let result = unsafe { &*caller(&candidate) };
3351        assert_eq!(result.as_int(), Some(4));
3352        Ok(())
3353    }
3354
3355    #[test]
3356    fn recursive_factorial_keeps_static_return_type() -> anyhow::Result<()> {
3357        let vm = Vm::with_all()?;
3358        vm.import_code(
3359            "vm_recursive_factorial",
3360            br#"
3361            fn factorial(n: i64) {
3362                if n <= 1 {
3363                    return 1;
3364                }
3365                n * factorial(n - 1)
3366            }
3367
3368            pub fn run(n: i64) {
3369                factorial(n)
3370            }
3371            "#
3372            .to_vec(),
3373        )?;
3374
3375        let compiled = vm.get_fn("vm_recursive_factorial::run", &[Type::I64])?;
3376        assert_eq!(compiled.ret_ty(), &Type::I64);
3377        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3378        assert_eq!(run(5), 120);
3379        Ok(())
3380    }
3381
3382    #[test]
3383    fn explicit_const_generic_function_calls_generate_distinct_variants() -> anyhow::Result<()> {
3384        let vm = Vm::with_all()?;
3385        vm.import_code(
3386            "vm_generic_const_variants",
3387            br#"
3388            fn value<N>() {
3389                N
3390            }
3391
3392            pub fn two() {
3393                value::<2>()
3394            }
3395
3396            pub fn three() {
3397                value::<3>()
3398            }
3399            "#
3400            .to_vec(),
3401        )?;
3402
3403        let compiled = vm.get_fn("vm_generic_const_variants::two", &[])?;
3404        assert_eq!(compiled.ret_ty(), &Type::I32);
3405        let two: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3406        assert_eq!(two(), 2);
3407
3408        let compiled = vm.get_fn("vm_generic_const_variants::three", &[])?;
3409        assert_eq!(compiled.ret_ty(), &Type::I32);
3410        let three: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3411        assert_eq!(three(), 3);
3412        Ok(())
3413    }
3414
3415    #[test]
3416    fn generic_function_body_resolves_private_generic_helper_after_import() -> anyhow::Result<()> {
3417        let vm = Vm::with_all()?;
3418        vm.import_code(
3419            "vm_generic_private_helper",
3420            br#"
3421            fn helper<N>() {
3422                N
3423            }
3424
3425            pub fn bench<N>() {
3426                helper::<N>()
3427            }
3428            "#
3429            .to_vec(),
3430        )?;
3431
3432        let compiled = vm.get_fn_with_params("vm_generic_private_helper::bench", &[], &[Type::ConstInt(7)])?;
3433        assert_eq!(compiled.ret_ty(), &Type::I32);
3434        let run: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3435        assert_eq!(run(), 7);
3436        Ok(())
3437    }
3438
3439    #[test]
3440    fn const_generic_repeat_array_initializes_all_items() -> anyhow::Result<()> {
3441        let vm = Vm::with_all()?;
3442        vm.import_code(
3443            "vm_generic_repeat_array",
3444            br#"
3445            fn bench<N>() {
3446                let is_prime = [true; N];
3447                is_prime[0] = false;
3448                is_prime[1] = false;
3449                let count = 0i64;
3450                for p in 2i64..N {
3451                    if is_prime[p] == true {
3452                        count = count + 1;
3453                        let step = p;
3454                        let j = p * p;
3455                        while j < N {
3456                            is_prime[j] = false;
3457                            j = j + step;
3458                        }
3459                    }
3460                }
3461                count
3462            }
3463
3464            pub fn run() {
3465                bench::<10>()
3466            }
3467
3468            pub fn run_1000() {
3469                bench::<1000>()
3470            }
3471
3472            pub fn run_100000() {
3473                bench::<100000>()
3474            }
3475            "#
3476            .to_vec(),
3477        )?;
3478
3479        let compiled = vm.get_fn("vm_generic_repeat_array::run", &[])?;
3480        assert_eq!(compiled.ret_ty(), &Type::I64);
3481        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3482        assert_eq!(run(), 4);
3483
3484        let compiled = vm.get_fn("vm_generic_repeat_array::run_1000", &[])?;
3485        assert_eq!(compiled.ret_ty(), &Type::I64);
3486        let run_1000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3487        assert_eq!(run_1000(), 168);
3488
3489        let compiled = vm.get_fn("vm_generic_repeat_array::run_100000", &[])?;
3490        assert_eq!(compiled.ret_ty(), &Type::I64);
3491        let run_100000: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3492        assert_eq!(run_100000(), 9592);
3493        Ok(())
3494    }
3495
3496    #[test]
3497    fn repeat_array_initializes_scalar_patterns() -> anyhow::Result<()> {
3498        let vm = Vm::with_all()?;
3499        vm.import_code(
3500            "vm_repeat_scalar_patterns",
3501            br#"
3502            pub fn count_true() {
3503                let items = [true; 100000];
3504                let count = 0i64;
3505                for idx in 0i64..100000 {
3506                    if items[idx] == true {
3507                        count = count + 1;
3508                    }
3509                }
3510                count
3511            }
3512
3513            pub fn i32_pair() {
3514                let items = [-7i32; 1000];
3515                items[0i64] + items[999i64]
3516            }
3517
3518            pub fn i64_pair() {
3519                let items = [1234567890123i64; 1000];
3520                items[0i64] + items[999i64]
3521            }
3522
3523            pub fn f64_pair() {
3524                let items = [1.5f64; 1000];
3525                items[0i64] + items[999i64]
3526            }
3527            "#
3528            .to_vec(),
3529        )?;
3530
3531        let compiled = vm.get_fn("vm_repeat_scalar_patterns::count_true", &[])?;
3532        assert_eq!(compiled.ret_ty(), &Type::I64);
3533        let count_true: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3534        assert_eq!(count_true(), 100000);
3535
3536        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i32_pair", &[])?;
3537        assert_eq!(compiled.ret_ty(), &Type::I32);
3538        let i32_pair: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3539        assert_eq!(i32_pair(), -14);
3540
3541        let compiled = vm.get_fn("vm_repeat_scalar_patterns::i64_pair", &[])?;
3542        assert_eq!(compiled.ret_ty(), &Type::I64);
3543        let i64_pair: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3544        assert_eq!(i64_pair(), 2469135780246);
3545
3546        let compiled = vm.get_fn("vm_repeat_scalar_patterns::f64_pair", &[])?;
3547        assert_eq!(compiled.ret_ty(), &Type::F64);
3548        let f64_pair: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
3549        assert_eq!(f64_pair(), 3.0);
3550        Ok(())
3551    }
3552
3553    #[test]
3554    fn bool_array_store_normalizes_condition_values() -> anyhow::Result<()> {
3555        let vm = Vm::with_all()?;
3556        vm.import_code(
3557            "vm_bool_array_store",
3558            br#"
3559            pub fn run() {
3560                let items = [false; 4];
3561                items[1] = 3i64 > 2i64;
3562                items[2] = 3i64 < 2i64;
3563                if items[1] == true && items[2] == false {
3564                    1i64
3565                } else {
3566                    0i64
3567                }
3568            }
3569            "#
3570            .to_vec(),
3571        )?;
3572
3573        let compiled = vm.get_fn("vm_bool_array_store::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(), 1);
3577        Ok(())
3578    }
3579
3580    #[test]
3581    fn bool_array_large_sequential_writes() -> anyhow::Result<()> {
3582        let vm = Vm::with_all()?;
3583        vm.import_code(
3584            "vm_bool_array_large_writes",
3585            br#"
3586            pub fn run() {
3587                let items = [true; 100000];
3588                for idx in 0i64..100000 {
3589                    items[idx] = false;
3590                }
3591                let count = 0i64;
3592                for idx in 0i64..100000 {
3593                    if items[idx] == false {
3594                        count = count + 1;
3595                    }
3596                }
3597                count
3598            }
3599            "#
3600            .to_vec(),
3601        )?;
3602
3603        let compiled = vm.get_fn("vm_bool_array_large_writes::run", &[])?;
3604        assert_eq!(compiled.ret_ty(), &Type::I64);
3605        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3606        assert_eq!(run(), 100000);
3607        Ok(())
3608    }
3609
3610    #[test]
3611    fn bool_array_sieve_style_indices_stay_in_bounds() -> anyhow::Result<()> {
3612        let vm = Vm::with_all()?;
3613        vm.import_code(
3614            "vm_bool_array_sieve_indices",
3615            br#"
3616            pub fn run() {
3617                let items = [true; 100000];
3618                let writes = 0i64;
3619                for p in 2i64..100000 {
3620                    let step = p;
3621                    let j = p * p;
3622                    while j < 100000 {
3623                        items[j] = false;
3624                        writes = writes + 1;
3625                        j = j + step;
3626                    }
3627                }
3628                writes
3629            }
3630            "#
3631            .to_vec(),
3632        )?;
3633
3634        let compiled = vm.get_fn("vm_bool_array_sieve_indices::run", &[])?;
3635        assert_eq!(compiled.ret_ty(), &Type::I64);
3636        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3637        assert!(run() > 0);
3638        Ok(())
3639    }
3640
3641    #[test]
3642    fn sieve_style_indices_compute_in_bounds_without_array_write() -> anyhow::Result<()> {
3643        let vm = Vm::with_all()?;
3644        vm.import_code(
3645            "vm_sieve_indices_no_write",
3646            br#"
3647            pub fn run() {
3648                let max_j = 0i64;
3649                for p in 2i64..100000 {
3650                    let step = p;
3651                    let j = p * p;
3652                    while j < 100000 {
3653                        if j < 0i64 {
3654                            return -1i64;
3655                        }
3656                        if j > max_j {
3657                            max_j = j;
3658                        }
3659                        j = j + step;
3660                    }
3661                }
3662                max_j
3663            }
3664            "#
3665            .to_vec(),
3666        )?;
3667
3668        let compiled = vm.get_fn("vm_sieve_indices_no_write::run", &[])?;
3669        assert_eq!(compiled.ret_ty(), &Type::I64);
3670        let run: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3671        assert_eq!(run(), 99999);
3672        Ok(())
3673    }
3674
3675    #[test]
3676    fn dynamic_list_index_sum_uses_static_accumulator_type() -> anyhow::Result<()> {
3677        let vm = Vm::with_all()?;
3678        vm.import_code(
3679            "vm_dynamic_index_sum",
3680            br#"
3681            pub fn sum_list(n: i64) {
3682                let l = [];
3683                for i in 0..n {
3684                    l.push(i);
3685                }
3686                let sum = 0i64;
3687                for j in 0..n {
3688                    sum = sum + l[j];
3689                }
3690                sum
3691            }
3692            "#
3693            .to_vec(),
3694        )?;
3695
3696        let compiled = vm.get_fn("vm_dynamic_index_sum::sum_list", &[Type::I64])?;
3697        let sum_list_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_dynamic_index_sum::sum_list")?;
3698        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(sum_list_id, &[], &[Type::I64]);
3699        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I64)), "local type hints: {:?}", hints);
3700        assert_eq!(compiled.ret_ty(), &Type::I64);
3701        let sum_list: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3702        assert_eq!(sum_list(1000), 499500);
3703        Ok(())
3704    }
3705
3706    #[test]
3707    fn inferred_empty_list_uses_typed_dynamic_vector() -> anyhow::Result<()> {
3708        let vm = Vm::with_all()?;
3709        vm.import_code(
3710            "vm_inferred_typed_list",
3711            br#"
3712            pub fn make() {
3713                let l = [];
3714                l.push(1i64);
3715                l
3716            }
3717            "#
3718            .to_vec(),
3719        )?;
3720
3721        let compiled = vm.get_fn("vm_inferred_typed_list::make", &[])?;
3722        assert_eq!(compiled.ret_ty(), &Type::Any);
3723        let make: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3724        let result = unsafe { &*make() };
3725        assert!(matches!(result, Dynamic::VecI64(values) if values == &vec![1]), "result: {:?}", result);
3726        Ok(())
3727    }
3728
3729    #[test]
3730    fn inferred_list_shortcuts_cover_scalar_types() -> anyhow::Result<()> {
3731        let vm = Vm::with_all()?;
3732        vm.import_code(
3733            "vm_inferred_list_shortcuts",
3734            br#"
3735            pub fn second_bool() {
3736                let l = [];
3737                l.push(true);
3738                l.push(false);
3739                l[1]
3740            }
3741
3742            pub fn first_u8() {
3743                let l = [];
3744                l.push(7u8);
3745                l[0]
3746            }
3747
3748            pub fn sum_i32(n: i64) {
3749                let l = [];
3750                for i in 0..n {
3751                    l.push(i as i32);
3752                }
3753                let sum = 0i32;
3754                for j in 0..n {
3755                    sum = sum + l[j];
3756                }
3757                sum
3758            }
3759
3760            pub fn sum_f32(n: i64) {
3761                let l = [];
3762                for i in 0..n {
3763                    l.push(i as f32);
3764                }
3765                let sum = 0f32;
3766                for j in 0..n {
3767                    sum = sum + l[j];
3768                }
3769                sum
3770            }
3771
3772            pub fn second_str() {
3773                let l = [];
3774                l.push("first");
3775                l.push("second");
3776                l[1]
3777            }
3778            "#
3779            .to_vec(),
3780        )?;
3781
3782        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_bool", &[])?;
3783        let second_bool_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::second_bool")?;
3784        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(second_bool_id, &[], &[]);
3785        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Bool)), "bool local type hints: {:?}", hints);
3786        assert_eq!(compiled.ret_ty(), &Type::Bool);
3787        let second_bool: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3788        assert!(!second_bool());
3789
3790        let compiled = vm.get_fn("vm_inferred_list_shortcuts::first_u8", &[])?;
3791        let first_u8_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::first_u8")?;
3792        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(first_u8_id, &[], &[]);
3793        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::U8)), "u8 local type hints: {:?}", hints);
3794        assert_eq!(compiled.ret_ty(), &Type::U8);
3795        let first_u8: extern "C" fn() -> u8 = unsafe { std::mem::transmute(compiled.ptr()) };
3796        assert_eq!(first_u8(), 7);
3797
3798        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_i32", &[Type::I64])?;
3799        let sum_i32_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::sum_i32")?;
3800        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(sum_i32_id, &[], &[Type::I64]);
3801        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::I32)), "i32 local type hints: {:?}", hints);
3802        assert_eq!(compiled.ret_ty(), &Type::I32);
3803        let sum_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3804        assert_eq!(sum_i32(100), 4950);
3805
3806        let compiled = vm.get_fn("vm_inferred_list_shortcuts::sum_f32", &[Type::I64])?;
3807        let sum_f32_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::sum_f32")?;
3808        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(sum_f32_id, &[], &[Type::I64]);
3809        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::F32)), "f32 local type hints: {:?}", hints);
3810        assert_eq!(compiled.ret_ty(), &Type::F32);
3811        let sum_f32: extern "C" fn(i64) -> f32 = unsafe { std::mem::transmute(compiled.ptr()) };
3812        assert_eq!(sum_f32(10), 45.0);
3813
3814        let compiled = vm.get_fn("vm_inferred_list_shortcuts::second_str", &[])?;
3815        let second_str_id = vm.jit.lock().unwrap().compiler.symbols.get_id("vm_inferred_list_shortcuts::second_str")?;
3816        let hints = vm.jit.lock().unwrap().compiler.inferred_local_type_hints(second_str_id, &[], &[]);
3817        assert!(hints.iter().any(|ty| matches!(ty, Some(Type::List(elem)) if elem.as_ref() == &Type::Str)), "str local type hints: {:?}", hints);
3818        assert_eq!(compiled.ret_ty(), &Type::Str);
3819        let second_str: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3820        let result = unsafe { &*second_str() };
3821        assert_eq!(result.as_str(), "second");
3822        Ok(())
3823    }
3824
3825    #[test]
3826    fn inferred_list_supports_bracket_set_idx() -> anyhow::Result<()> {
3827        let vm = Vm::with_all()?;
3828        vm.import_code(
3829            "vm_inferred_list_set_idx",
3830            br#"
3831            pub fn swap_first_two() {
3832                let items = [];
3833                items.push(1i64);
3834                items.push(2i64);
3835                let j = 0i64;
3836                let a = items[j];
3837                let b = items[j + 1];
3838                items[j] = b;
3839                items[j + 1] = a;
3840                items[0] * 10i64 + items[1]
3841            }
3842
3843            pub fn replace_string() {
3844                let items = [];
3845                items.push("old");
3846                items[0] = "new";
3847                items[0]
3848            }
3849            "#
3850            .to_vec(),
3851        )?;
3852
3853        let compiled = vm.get_fn("vm_inferred_list_set_idx::swap_first_two", &[])?;
3854        assert_eq!(compiled.ret_ty(), &Type::I64);
3855        let swap_first_two: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3856        assert_eq!(swap_first_two(), 21);
3857
3858        let compiled = vm.get_fn("vm_inferred_list_set_idx::replace_string", &[])?;
3859        assert_eq!(compiled.ret_ty(), &Type::Str);
3860        let replace_string: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3861        let result = unsafe { &*replace_string() };
3862        assert_eq!(result.as_str(), "new");
3863        Ok(())
3864    }
3865
3866    #[test]
3867    fn root_get_returns_null_for_missing_key_which_compares_correctly() -> anyhow::Result<()> {
3868        let vm = Vm::with_all()?;
3869        vm.import_code(
3870            "vm_root_get_missing",
3871            br#"
3872            pub fn check_missing() {
3873                let existing = root::get("local/vm_root_get_missing_test");
3874                if existing.is_map() {
3875                    return false;
3876                }
3877                true
3878            }
3879            "#
3880            .to_vec(),
3881        )?;
3882
3883        let compiled = vm.get_fn("vm_root_get_missing::check_missing", &[])?;
3884        assert_eq!(compiled.ret_ty(), &Type::Bool);
3885        let check_missing: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3886        assert!(check_missing());
3887        Ok(())
3888    }
3889
3890    #[test]
3891    fn map_get_key_on_null_map_returns_null() -> anyhow::Result<()> {
3892        let vm = Vm::with_all()?;
3893        vm.import_code(
3894            "vm_get_key_null_map",
3895            br#"
3896            pub fn get_key_null(data) {
3897                data.get_key("missing")
3898            }
3899            "#
3900            .to_vec(),
3901        )?;
3902
3903        let compiled = vm.get_fn("vm_get_key_null_map::get_key_null", &[Type::Any])?;
3904        assert_eq!(compiled.ret_ty(), &Type::Any);
3905        let get_key_null: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
3906
3907        let data_map = dynamic::map!("exists"=> 1i64);
3908        let missing = unsafe { &*get_key_null(&data_map) };
3909        assert!(missing.is_null());
3910
3911        let null = Dynamic::Null;
3912        let result = unsafe { &*get_key_null(&null) };
3913        assert!(result.is_null());
3914        Ok(())
3915    }
3916
3917    #[test]
3918    fn keys_on_empty_map_returns_empty_list() -> anyhow::Result<()> {
3919        let vm = Vm::with_all()?;
3920        vm.import_code(
3921            "vm_keys_empty_map",
3922            br#"
3923            pub fn empty_map_keys() {
3924                let data = {};
3925                data.keys().len()
3926            }
3927            "#
3928            .to_vec(),
3929        )?;
3930
3931        let compiled = vm.get_fn("vm_keys_empty_map::empty_map_keys", &[])?;
3932        assert_eq!(compiled.ret_ty(), &Type::I32);
3933        let empty_map_keys: extern "C" fn() -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3934        assert_eq!(empty_map_keys(), 0);
3935        Ok(())
3936    }
3937
3938    #[test]
3939    fn cast_between_all_integer_widths() -> anyhow::Result<()> {
3940        let vm = Vm::with_all()?;
3941        vm.import_code(
3942            "vm_cast_integer_widths",
3943            br#"
3944            pub fn i64_to_i32(value: i64) {
3945                value as i32
3946            }
3947
3948            pub fn i32_to_i64(value: i32) {
3949                value as i64
3950            }
3951
3952            pub fn u32_to_i64(value: u32) {
3953                value as i64
3954            }
3955            "#
3956            .to_vec(),
3957        )?;
3958
3959        let compiled = vm.get_fn("vm_cast_integer_widths::i64_to_i32", &[Type::I64])?;
3960        assert_eq!(compiled.ret_ty(), &Type::I32);
3961        let i64_to_i32: extern "C" fn(i64) -> i32 = unsafe { std::mem::transmute(compiled.ptr()) };
3962        assert_eq!(i64_to_i32(42), 42);
3963
3964        let compiled = vm.get_fn("vm_cast_integer_widths::i32_to_i64", &[Type::I32])?;
3965        assert_eq!(compiled.ret_ty(), &Type::I64);
3966        let i32_to_i64: extern "C" fn(i32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3967        assert_eq!(i32_to_i64(-1), -1);
3968
3969        let compiled = vm.get_fn("vm_cast_integer_widths::u32_to_i64", &[Type::U32])?;
3970        assert_eq!(compiled.ret_ty(), &Type::I64);
3971        let u32_to_i64: extern "C" fn(u32) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
3972        assert_eq!(u32_to_i64(42), 42);
3973        Ok(())
3974    }
3975
3976    #[test]
3977    fn boolean_literals_in_complex_expression_trees() -> anyhow::Result<()> {
3978        let vm = Vm::with_all()?;
3979        vm.import_code(
3980            "vm_complex_boolean",
3981            br#"
3982            pub fn exclusive_or(a: bool, b: bool) {
3983                (a && !b) || (!a && b)
3984            }
3985
3986            pub fn implies(a: bool, b: bool) {
3987                !a || b
3988            }
3989            "#
3990            .to_vec(),
3991        )?;
3992
3993        let compiled = vm.get_fn("vm_complex_boolean::exclusive_or", &[Type::Bool, Type::Bool])?;
3994        assert_eq!(compiled.ret_ty(), &Type::Bool);
3995        let exclusive_or: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
3996        assert!(exclusive_or(true, false));
3997        assert!(exclusive_or(false, true));
3998        assert!(!exclusive_or(true, true));
3999        assert!(!exclusive_or(false, false));
4000
4001        let compiled = vm.get_fn("vm_complex_boolean::implies", &[Type::Bool, Type::Bool])?;
4002        assert_eq!(compiled.ret_ty(), &Type::Bool);
4003        let implies: extern "C" fn(bool, bool) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4004        assert!(implies(false, true));
4005        assert!(implies(false, false));
4006        assert!(implies(true, true));
4007        assert!(!implies(true, false));
4008        Ok(())
4009    }
4010
4011    #[test]
4012    fn concrete_struct_method_returning_self_type() -> anyhow::Result<()> {
4013        let vm = Vm::with_all()?;
4014        vm.import_code(
4015            "vm_struct_method_self",
4016            br#"
4017            pub struct Vec3 {
4018                x: f64,
4019                y: f64,
4020                z: f64,
4021            }
4022
4023            impl Vec3 {
4024                pub fn add(self: Vec3, other: Vec3) {
4025                    Vec3{x: self.x + other.x, y: self.y + other.y, z: self.z + other.z}
4026                }
4027            }
4028
4029            pub fn run() {
4030                let v1 = Vec3{x: 1.0f64, y: 2.0f64, z: 3.0f64};
4031                let v2 = Vec3{x: 4.0f64, y: 5.0f64, z: 6.0f64};
4032                let sum = v1.add(v2);
4033                sum.x + sum.y + sum.z
4034            }
4035            "#
4036            .to_vec(),
4037        )?;
4038
4039        let compiled = vm.get_fn("vm_struct_method_self::run", &[])?;
4040        assert_eq!(compiled.ret_ty(), &Type::F64);
4041        let run: extern "C" fn() -> f64 = unsafe { std::mem::transmute(compiled.ptr()) };
4042        assert_eq!(run(), 21.0);
4043        Ok(())
4044    }
4045
4046    #[test]
4047    fn deep_nested_struct_access_with_multiple_field_levels() -> anyhow::Result<()> {
4048        let vm = Vm::with_all()?;
4049        vm.import_code(
4050            "vm_deep_nested_struct",
4051            br#"
4052            pub struct A {
4053                value: i64,
4054            }
4055
4056            pub struct B {
4057                a: A,
4058            }
4059
4060            pub struct C {
4061                b: B,
4062            }
4063
4064            pub fn direct_access() {
4065                let c = C{b: B{a: A{value: 99}}};
4066                c.b.a.value
4067            }
4068
4069            pub fn via_variable() {
4070                let c = C{b: B{a: A{value: 77}}};
4071                let b = c.b;
4072                let a = b.a;
4073                a.value
4074            }
4075            "#
4076            .to_vec(),
4077        )?;
4078
4079        let compiled = vm.get_fn("vm_deep_nested_struct::direct_access", &[])?;
4080        assert_eq!(compiled.ret_ty(), &Type::I64);
4081        let direct_access: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4082        assert_eq!(direct_access(), 99);
4083
4084        let compiled = vm.get_fn("vm_deep_nested_struct::via_variable", &[])?;
4085        assert_eq!(compiled.ret_ty(), &Type::I64);
4086        let via_variable: extern "C" fn() -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4087        assert_eq!(via_variable(), 77);
4088        Ok(())
4089    }
4090
4091    #[test]
4092    fn array_index_with_dynamic_value_via_method() -> anyhow::Result<()> {
4093        let vm = Vm::with_all()?;
4094        vm.import_code(
4095            "vm_array_idx_dynamic",
4096            br#"
4097            pub fn get_by_idx(list, idx) {
4098                list.get_idx(idx)
4099            }
4100            "#
4101            .to_vec(),
4102        )?;
4103
4104        let compiled = vm.get_fn("vm_array_idx_dynamic::get_by_idx", &[Type::Any, Type::I64])?;
4105        assert_eq!(compiled.ret_ty(), &Type::Any);
4106        let get_by_idx: extern "C" fn(*const Dynamic, i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4107
4108        let list = Dynamic::list(vec!["a".into(), "b".into()]);
4109        let first = unsafe { &*get_by_idx(&list, 0) };
4110        assert_eq!(first.as_str(), "a");
4111
4112        let out = unsafe { &*get_by_idx(&list, 10) };
4113        assert!(out.is_null());
4114        Ok(())
4115    }
4116
4117    #[test]
4118    fn dynamic_field_access_with_optional_or_fallback() -> anyhow::Result<()> {
4119        let vm = Vm::with_all()?;
4120        vm.import_code(
4121            "vm_dynamic_or_fallback",
4122            br#"
4123            pub fn with_fallback(data) {
4124                if data.contains("name") { data.name } else { "unknown" }
4125            }
4126
4127            pub fn with_fallback_missing(data) {
4128                if data.contains("nickname") { data.nickname } else { "unnamed" }
4129            }
4130            "#
4131            .to_vec(),
4132        )?;
4133
4134        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback", &[Type::Any])?;
4135        assert_eq!(compiled.ret_ty(), &Type::Any);
4136        let with_fallback: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4137        let data = dynamic::map!("name"=> "Alice");
4138        let result = unsafe { &*with_fallback(&data) };
4139        assert_eq!(result.as_str(), "Alice");
4140
4141        let compiled = vm.get_fn("vm_dynamic_or_fallback::with_fallback_missing", &[Type::Any])?;
4142        let with_fallback_missing: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
4143        let result = unsafe { &*with_fallback_missing(&data) };
4144        assert_eq!(result.as_str(), "unnamed");
4145        Ok(())
4146    }
4147
4148    #[test]
4149    fn for_in_loop_iterates_over_list_and_map_directly() -> anyhow::Result<()> {
4150        let vm = Vm::with_all()?;
4151        vm.import_code(
4152            "vm_for_in_collection",
4153            br#"
4154            pub fn sum_list(items) {
4155                let total = 0i64;
4156                for item in items {
4157                    total = total + 1;
4158                }
4159                total
4160            }
4161
4162            pub fn count_map_keys(data) {
4163                let count = 0i64;
4164                for key in data.keys() {
4165                    count = count + 1;
4166                }
4167                count
4168            }
4169
4170            pub fn for_in_list_works(items) {
4171                let exists = false;
4172                for item in items {
4173                    exists = true;
4174                }
4175                exists
4176            }
4177
4178            pub fn for_in_map_values_works(data) {
4179                let exists = false;
4180                for value in data {
4181                    exists = true;
4182                }
4183                exists
4184            }
4185            "#
4186            .to_vec(),
4187        )?;
4188
4189        let compiled = vm.get_fn("vm_for_in_collection::sum_list", &[Type::Any])?;
4190        assert_eq!(compiled.ret_ty(), &Type::I64);
4191        let sum_list: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4192        let items = Dynamic::list(vec![Dynamic::from(1i64), Dynamic::from(2i64), Dynamic::from(3i64)]);
4193        assert_eq!(sum_list(&items), 3);
4194
4195        let data = dynamic::map!("x"=> 1i64, "y"=> 2i64);
4196        let compiled = vm.get_fn("vm_for_in_collection::count_map_keys", &[Type::Any])?;
4197        assert_eq!(compiled.ret_ty(), &Type::I64);
4198        let count_map_keys: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
4199        assert_eq!(count_map_keys(&data), 2);
4200
4201        let compiled = vm.get_fn("vm_for_in_collection::for_in_list_works", &[Type::Any])?;
4202        assert_eq!(compiled.ret_ty(), &Type::Bool);
4203        let for_in_list_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4204        let empty = Dynamic::list(Vec::new());
4205        assert!(!for_in_list_works(&empty));
4206        assert!(for_in_list_works(&items));
4207
4208        let compiled = vm.get_fn("vm_for_in_collection::for_in_map_values_works", &[Type::Any])?;
4209        assert_eq!(compiled.ret_ty(), &Type::Bool);
4210        let for_in_map_values_works: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
4211        let empty_map = dynamic::map!();
4212        assert!(!for_in_map_values_works(&empty_map));
4213        assert!(for_in_map_values_works(&data));
4214
4215        Ok(())
4216    }
4217
4218    #[test]
4219    fn concurrent_100_threads_no_memory_leak() -> anyhow::Result<()> {
4220        let vm = Vm::with_all()?;
4221        vm.import_code(
4222            "vm_stress",
4223            br#"
4224            pub fn heavy_alloc(idx: i64) {
4225                let items = [];
4226                let i = 0;
4227                while i < 50 {
4228                    items.push({
4229                        id: i + idx,
4230                        name: "item-" + i,
4231                        tags: ["tag-a", "tag-b", "tag-c"],
4232                        meta: {
4233                            created: 1234567890i64,
4234                            score: (i * 3.14f64) as i64,
4235                            extra: "prefix/" + i + "/" + idx
4236                        }
4237                    });
4238                    i = i + 1;
4239                }
4240                items
4241            }
4242
4243            pub fn string_concat_stress() {
4244                let i = 0;
4245                let result = "";
4246                while i < 200 {
4247                    result = result + "data-" + i + ",";
4248                    i = i + 1;
4249                }
4250                result
4251            }
4252            "#
4253            .to_vec(),
4254        )?;
4255
4256        let (heavy_ptr, _) = vm.get_fn_ptr("vm_stress::heavy_alloc", &[Type::I64])?;
4257        let (concat_ptr, _) = vm.get_fn_ptr("vm_stress::string_concat_stress", &[])?;
4258
4259        let threads: usize = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4).max(100);
4260        let iters_per_thread = 200;
4261        let total_calls = threads * iters_per_thread * 2;
4262
4263        let before = current_rss_kb();
4264        eprintln!("threads={threads} iters_per_thread={iters_per_thread} total_calls={total_calls} rss_before={before}KB");
4265
4266        // Round 1: first concurrent execution (arena warm-up)
4267        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4268        let r1 = current_rss_kb();
4269        eprintln!("rss_after_round1={r1}KB");
4270
4271        // Round 2: should stabilize (no unbounded growth)
4272        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4273        let r2 = current_rss_kb();
4274        eprintln!("rss_after_round2={r2}KB");
4275
4276        // Round 3: final check
4277        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4278        let r3 = current_rss_kb();
4279        eprintln!("rss_after_round3={r3}KB");
4280
4281        // Round 4: confirm that any one-time allocator growth has settled.
4282        run_stress_round(threads, iters_per_thread, heavy_ptr as usize, concat_ptr as usize);
4283        let r4 = current_rss_kb();
4284        eprintln!("rss_after_round4={r4}KB");
4285
4286        // Allocator/arena growth is allowed during warm-up, but it must settle.
4287        let d12 = r2.saturating_sub(r1);
4288        let d23 = r3.saturating_sub(r2);
4289        let d34 = r4.saturating_sub(r3);
4290        eprintln!("delta_r1→r2={d12}KB delta_r2→r3={d23}KB delta_r3→r4={d34}KB");
4291
4292        // The last interval must be small to prove the growth is not continuing.
4293        let max_growth_kb = 20 * 1024;
4294        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)");
4295
4296        Ok(())
4297    }
4298
4299    fn run_stress_round(threads: usize, iters: usize, heavy_ptr: usize, concat_ptr: usize) {
4300        std::thread::scope(|scope| {
4301            let mut handles = Vec::with_capacity(threads);
4302            for t in 0..threads {
4303                let heavy_ptr = heavy_ptr;
4304                let concat_ptr = concat_ptr;
4305                handles.push(scope.spawn(move || {
4306                    let heavy_fn: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(heavy_ptr as *const u8) };
4307                    let concat_fn: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(concat_ptr as *const u8) };
4308                    for i in 0..iters {
4309                        // heavy_alloc: drop returned value to free heap allocation
4310                        let r_ptr = heavy_fn((t * iters + i) as i64);
4311                        assert!(!r_ptr.is_null());
4312                        unsafe {
4313                            let r = &*r_ptr;
4314                            assert!(r.len() > 0, "heavy_alloc returned empty list");
4315                            drop(Box::from_raw(r_ptr as *mut Dynamic));
4316                        }
4317
4318                        // concat: same, drop returned value
4319                        let s_ptr = concat_fn();
4320                        assert!(!s_ptr.is_null());
4321                        unsafe {
4322                            let s = &*s_ptr;
4323                            assert!(s.len() > 0, "string_concat_stress returned empty");
4324                            drop(Box::from_raw(s_ptr as *mut Dynamic));
4325                        }
4326                    }
4327                }));
4328            }
4329            for h in handles {
4330                h.join().unwrap();
4331            }
4332        });
4333    }
4334
4335    fn current_rss_kb() -> u64 {
4336        // macOS: use ps
4337        let pid = std::process::id();
4338        if let Ok(output) = std::process::Command::new("ps").args(["-p", &pid.to_string(), "-o", "rss="]).output() {
4339            if let Ok(s) = String::from_utf8(output.stdout) {
4340                if let Some(kb) = s.trim().parse::<u64>().ok() {
4341                    return kb;
4342                }
4343            }
4344        }
4345        // Linux fallback: /proc/self/statm
4346        if let Ok(statm) = std::fs::read_to_string("/proc/self/statm") {
4347            let parts: Vec<&str> = statm.split_whitespace().collect();
4348            if let Some(rss_pages) = parts.get(1).and_then(|s| s.parse::<u64>().ok()) {
4349                return rss_pages * 4; // pages (4KB) → KB
4350            }
4351        }
4352        0
4353    }
4354}