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