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