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