Skip to main content

vm/
lib.rs

1//使用 cranelift 作为后端 直接 jit 解释脚本
2mod binary;
3mod native;
4pub use native::{ANY, STD};
5
6mod fns;
7use anyhow::{Result, anyhow};
8pub use fns::{FnInfo, FnVariant};
9mod context;
10pub use context::BuildContext;
11
12mod rt;
13use cranelift::prelude::types;
14use dynamic::Type;
15pub use rt::JITRunTime;
16use smol_str::SmolStr;
17mod db_module;
18mod gpu_layout;
19mod gpu_module;
20mod http_module;
21mod llm_module;
22mod root_module;
23pub use gpu_layout::{GpuFieldLayout, GpuStructLayout};
24
25use std::sync::{Mutex, OnceLock, Weak};
26static PTR_TYPE: OnceLock<types::Type> = OnceLock::new();
27pub fn ptr_type() -> types::Type {
28    PTR_TYPE.get().cloned().unwrap()
29}
30
31pub fn get_type(ty: &Type) -> Result<types::Type> {
32    if ty.is_f64() {
33        Ok(types::F64)
34    } else if ty.is_f32() {
35        Ok(types::F32)
36    } else if ty.is_int() | ty.is_uint() {
37        match ty.width() {
38            1 => Ok(types::I8),
39            2 => Ok(types::I16),
40            4 => Ok(types::I32),
41            8 => Ok(types::I64),
42            _ => Err(anyhow!("非法类型 {:?}", ty)),
43        }
44    } else if let Type::Bool = ty {
45        Ok(types::I8)
46    } else {
47        Ok(ptr_type())
48    }
49}
50
51use compiler::Symbol;
52use cranelift::prelude::*;
53
54pub fn init_jit(mut jit: JITRunTime) -> Result<JITRunTime> {
55    jit.add_all()?;
56    Ok(jit)
57}
58
59use std::sync::Arc;
60unsafe impl Send for JITRunTime {}
61unsafe impl Sync for JITRunTime {}
62
63pub(crate) fn with_vm_context<T>(context: *const Weak<Mutex<JITRunTime>>, f: impl FnOnce(&Vm) -> Result<T>) -> Result<T> {
64    if context.is_null() {
65        return Err(anyhow!("VM context is null"));
66    }
67    let jit = unsafe { &*context }.upgrade().ok_or_else(|| anyhow!("VM context has expired"))?;
68    let vm = Vm { jit };
69    f(&vm)
70}
71
72fn add_method_field(jit: &mut JITRunTime, def: &str, method: &str, id: u32) -> Result<()> {
73    let def_id = jit.get_id(def)?;
74    if let Some((_, define)) = jit.compiler.symbols.get_symbol_mut(def_id) {
75        if let Symbol::Struct(Type::Struct { params, fields }, _) = define {
76            fields.push((method.into(), Type::Symbol { id, params: params.clone() }));
77        }
78    }
79    Ok(())
80}
81
82fn add_native_module_fns(jit: &mut JITRunTime, module: &str, fns: &[(&str, &[Type], Type, *const u8)]) -> Result<()> {
83    jit.add_module(module);
84    for (name, arg_tys, ret_ty, fn_ptr) in fns {
85        let full_name = format!("{}::{}", module, name);
86        jit.add_native_ptr(&full_name, name, arg_tys, ret_ty.clone(), *fn_ptr)?;
87    }
88    jit.pop_module();
89    Ok(())
90}
91
92impl JITRunTime {
93    pub fn add_module(&mut self, name: &str) {
94        self.compiler.symbols.add_module(name.into());
95    }
96
97    pub fn pop_module(&mut self) {
98        self.compiler.symbols.pop_module();
99    }
100
101    pub fn add_type(&mut self, name: &str, ty: Type, is_pub: bool) -> u32 {
102        self.compiler.add_symbol(name, Symbol::Struct(ty, is_pub))
103    }
104
105    pub fn add_empty_type(&mut self, name: &str) -> Result<u32> {
106        match self.get_id(name) {
107            Ok(id) => Ok(id),
108            Err(_) => Ok(self.add_type(name, Type::Struct { params: Vec::new(), fields: Vec::new() }, true)),
109        }
110    }
111
112    pub fn add_native_module_ptr(&mut self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
113        self.add_module(module);
114        let full_name = format!("{}::{}", module, name);
115        let result = self.add_native_ptr(&full_name, name, arg_tys, ret_ty, fn_ptr);
116        self.pop_module();
117        result
118    }
119
120    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> {
121        self.add_module(module);
122        let full_name = format!("{}::{}", module, name);
123        let result = self.add_context_native_ptr(&full_name, name, arg_tys, ret_ty, fn_ptr);
124        self.pop_module();
125        result
126    }
127
128    pub fn add_native_method_ptr(&mut self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
129        self.add_empty_type(def)?;
130        let full_name = format!("{}::{}", def, method);
131        let id = self.add_native_ptr(&full_name, &full_name, arg_tys, ret_ty, fn_ptr)?;
132        add_method_field(self, def, method, id)?;
133        Ok(id)
134    }
135
136    pub fn add_std(&mut self) -> Result<()> {
137        self.add_module("std");
138        for (name, arg_tys, ret_ty, fn_ptr) in STD {
139            self.add_native_ptr(name, name, arg_tys, ret_ty, fn_ptr)?;
140        }
141        self.add_context_native_ptr("import", "import", &[Type::Any, Type::Any], Type::Bool, native::import_with_vm as *const u8)?;
142        Ok(())
143    }
144
145    pub fn add_any(&mut self) -> Result<()> {
146        for (name, arg_tys, ret_ty, fn_ptr) in ANY {
147            let (_, method) = name.split_once("::").ok_or_else(|| anyhow!("非法 Any 方法名 {}", name))?;
148            self.add_native_method_ptr("Any", method, arg_tys, ret_ty, fn_ptr)?;
149        }
150        Ok(())
151    }
152
153    pub fn add_vec(&mut self) -> Result<()> {
154        self.add_empty_type("Vec")?;
155        let vec_def = Type::Symbol { id: self.get_id("Vec")?, params: Vec::new() };
156        self.add_inline("Vec::swap", vec![vec_def.clone(), Type::I64, Type::I64], Type::Void, |ctx: Option<&mut BuildContext>, args: Vec<Value>| {
157            if let Some(ctx) = ctx {
158                let width = ctx.builder.ins().iconst(types::I64, 4);
159                let offset_val = ctx.builder.ins().imul(args[1], width); // i * 4 i32大小四字节
160                let final_addr = ctx.builder.ins().iadd(args[0], offset_val); // base + (i*4)
161                let dest = ctx.builder.ins().imul(args[2], width);
162                let dest_addr = ctx.builder.ins().iadd(args[0], dest); // base + (i*4)
163                let dest_val = ctx.builder.ins().load(types::I32, MemFlags::trusted(), dest_addr, 0);
164                let v = ctx.builder.ins().load(types::I32, MemFlags::trusted(), final_addr, 0);
165                ctx.builder.ins().store(MemFlags::trusted(), v, dest_addr, 0);
166                ctx.builder.ins().store(MemFlags::trusted(), dest_val, final_addr, 0);
167            }
168            Err(anyhow!("无返回值"))
169        })?;
170
171        self.add_inline("Vec::get_idx", vec![vec_def.clone(), Type::I64], Type::I32, |ctx: Option<&mut BuildContext>, args: Vec<Value>| {
172            if let Some(ctx) = ctx {
173                let width = ctx.builder.ins().iconst(types::I64, 4);
174                let offset_val = ctx.builder.ins().imul(args[1], width); // i * 4 i32大小四字节
175                let final_addr = ctx.builder.ins().iadd(args[0], offset_val);
176                Ok((Some(ctx.builder.ins().load(types::I32, MemFlags::trusted(), final_addr, 0)), Type::I32))
177            } else {
178                Ok((None, Type::I32))
179            }
180        })?;
181        Ok(())
182    }
183
184    pub fn add_llm(&mut self) -> Result<()> {
185        add_native_module_fns(self, "llm", &llm_module::LLM_NATIVE)
186    }
187
188    pub fn add_root(&mut self) -> Result<()> {
189        add_native_module_fns(self, "root", &root_module::ROOT_NATIVE)?;
190        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)?;
191        Ok(())
192    }
193
194    pub fn add_http(&mut self) -> Result<()> {
195        add_native_module_fns(self, "http", &http_module::HTTP_NATIVE)
196    }
197
198    pub fn add_db(&mut self) -> Result<()> {
199        add_native_module_fns(self, "db", &db_module::DB_NATIVE)
200    }
201
202    pub fn add_gpu(&mut self) -> Result<()> {
203        add_native_module_fns(self, "gpu", &gpu_module::GPU_NATIVE)
204    }
205
206    pub fn add_all(&mut self) -> Result<()> {
207        self.add_std()?;
208        self.add_any()?;
209        self.add_vec()?;
210        self.add_llm()?;
211        self.add_root()?;
212        self.add_http()?;
213        self.add_db()?;
214        self.add_gpu()?;
215        Ok(())
216    }
217}
218
219#[derive(Clone)]
220pub struct Vm {
221    jit: Arc<Mutex<JITRunTime>>,
222}
223
224#[derive(Clone)]
225pub struct CompiledFn {
226    ptr: usize,
227    ret: Type,
228    owner: Vm,
229}
230
231impl CompiledFn {
232    pub fn ptr(&self) -> *const u8 {
233        self.ptr as *const u8
234    }
235
236    pub fn ret_ty(&self) -> &Type {
237        &self.ret
238    }
239
240    pub fn owner(&self) -> &Vm {
241        &self.owner
242    }
243}
244
245impl Vm {
246    pub fn new() -> Self {
247        let jit = Arc::new(Mutex::new(JITRunTime::new(|_| {})));
248        jit.lock().unwrap().set_owner(Arc::downgrade(&jit));
249        Self { jit }
250    }
251
252    pub fn with_all() -> Result<Self> {
253        let vm = Self::new();
254        vm.add_all()?;
255        Ok(vm)
256    }
257
258    pub fn add_module(&self, name: &str) {
259        self.jit.lock().unwrap().add_module(name)
260    }
261
262    pub fn pop_module(&self) {
263        self.jit.lock().unwrap().pop_module()
264    }
265
266    pub fn add_type(&self, name: &str, ty: Type, is_pub: bool) -> u32 {
267        self.jit.lock().unwrap().add_type(name, ty, is_pub)
268    }
269
270    pub fn add_empty_type(&self, name: &str) -> Result<u32> {
271        self.jit.lock().unwrap().add_empty_type(name)
272    }
273
274    pub fn add_std(&self) -> Result<()> {
275        self.jit.lock().unwrap().add_std()
276    }
277
278    pub fn add_any(&self) -> Result<()> {
279        self.jit.lock().unwrap().add_any()
280    }
281
282    pub fn add_vec(&self) -> Result<()> {
283        self.jit.lock().unwrap().add_vec()
284    }
285
286    pub fn add_llm(&self) -> Result<()> {
287        self.jit.lock().unwrap().add_llm()
288    }
289
290    pub fn add_root(&self) -> Result<()> {
291        self.jit.lock().unwrap().add_root()
292    }
293
294    pub fn add_http(&self) -> Result<()> {
295        self.jit.lock().unwrap().add_http()
296    }
297
298    pub fn add_db(&self) -> Result<()> {
299        self.jit.lock().unwrap().add_db()
300    }
301
302    pub fn add_gpu(&self) -> Result<()> {
303        self.jit.lock().unwrap().add_gpu()
304    }
305
306    pub fn add_all(&self) -> Result<()> {
307        self.jit.lock().unwrap().add_all()
308    }
309
310    pub fn add_native_ptr(&self, full_name: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
311        self.jit.lock().unwrap().add_native_ptr(full_name, name, arg_tys, ret_ty, fn_ptr)
312    }
313
314    pub fn add_native_module_ptr(&self, module: &str, name: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
315        self.jit.lock().unwrap().add_native_module_ptr(module, name, arg_tys, ret_ty, fn_ptr)
316    }
317
318    pub fn add_native_method_ptr(&self, def: &str, method: &str, arg_tys: &[Type], ret_ty: Type, fn_ptr: *const u8) -> Result<u32> {
319        self.jit.lock().unwrap().add_native_method_ptr(def, method, arg_tys, ret_ty, fn_ptr)
320    }
321
322    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> {
323        self.jit.lock().unwrap().add_inline(name, args, ret, f)
324    }
325
326    pub fn import_code(&self, name: &str, code: Vec<u8>) -> Result<()> {
327        self.jit.lock().unwrap().import_code(name, code)
328    }
329
330    pub fn import_file(&self, name: &str, path: &str) -> Result<()> {
331        self.jit.lock().unwrap().compiler.import_file(name, path)?;
332        Ok(())
333    }
334
335    pub fn import(&self, name: &str, path: &str) -> Result<()> {
336        if root::contains(path) {
337            let code = root::get(path).unwrap();
338            if code.is_str() {
339                self.import_code(name, code.as_str().as_bytes().to_vec())
340            } else {
341                self.import_code(name, code.get_dynamic("code").ok_or(anyhow!("{:?} 没有 code 成员", code))?.as_str().as_bytes().to_vec())
342            }
343        } else {
344            self.import_file(name, path)
345        }
346    }
347
348    pub fn infer(&self, name: &str, arg_tys: &[Type]) -> Result<Type> {
349        self.jit.lock().unwrap().get_type(name, arg_tys)
350    }
351
352    pub fn get_fn_ptr(&self, name: &str, arg_tys: &[Type]) -> Result<(*const u8, Type)> {
353        self.jit.lock().unwrap().get_fn_ptr(name, arg_tys)
354    }
355
356    pub fn get_fn(&self, name: &str, arg_tys: &[Type]) -> Result<CompiledFn> {
357        let (ptr, ret) = self.get_fn_ptr(name, arg_tys)?;
358        Ok(CompiledFn { ptr: ptr as usize, ret, owner: self.clone() })
359    }
360
361    pub fn load(&self, code: Vec<u8>, arg_name: SmolStr) -> Result<(i64, Type)> {
362        self.jit.lock().unwrap().load(code, arg_name)
363    }
364
365    pub fn get_symbol(&self, name: &str, params: Vec<Type>) -> Result<Type> {
366        Ok(Type::Symbol { id: self.jit.lock().unwrap().get_id(name)?, params })
367    }
368
369    pub fn gpu_struct_layout(&self, name: &str, params: &[Type]) -> Result<GpuStructLayout> {
370        let jit = self.jit.lock().unwrap();
371        GpuStructLayout::from_symbol_table(&jit.compiler.symbols, name, params)
372    }
373
374    pub fn disassemble(&self, name: &str) -> Result<String> {
375        self.jit.lock().unwrap().compiler.symbols.disassemble(name)
376    }
377
378    #[cfg(feature = "ir-disassembly")]
379    pub fn disassemble_ir(&self, name: &str) -> Result<String> {
380        self.jit.lock().unwrap().disassemble_ir(name)
381    }
382}
383
384impl Default for Vm {
385    fn default() -> Self {
386        Self::new()
387    }
388}
389
390#[cfg(test)]
391mod tests {
392    use super::Vm;
393    use dynamic::{Dynamic, ToJson, Type};
394
395    extern "C" fn math_double(value: i64) -> i64 {
396        value * 2
397    }
398
399    #[test]
400    fn vm_can_add_native_after_jit_creation() -> anyhow::Result<()> {
401        let vm = Vm::new();
402        vm.add_native_module_ptr("math", "double", &[Type::I64], Type::I64, math_double as *const u8)?;
403        vm.import_code(
404            "vm_dynamic_native",
405            br#"
406            pub fn run(value: i64) {
407                math::double(value)
408            }
409            "#
410            .to_vec(),
411        )?;
412
413        let compiled = vm.get_fn("vm_dynamic_native::run", &[Type::I64])?;
414        assert_eq!(compiled.ret_ty(), &Type::I64);
415        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
416        assert_eq!(run(21), 42);
417        Ok(())
418    }
419
420    #[test]
421    fn compares_any_with_string_literal_as_string() -> anyhow::Result<()> {
422        let vm = Vm::with_all()?;
423        vm.import_code(
424            "vm_string_compare_any",
425            br#"
426            pub fn any_ne_empty(chat_path) {
427                chat_path != ""
428            }
429            "#
430            .to_vec(),
431        )?;
432
433        let compiled = vm.get_fn("vm_string_compare_any::any_ne_empty", &[Type::Any])?;
434        assert_eq!(compiled.ret_ty(), &Type::Bool);
435
436        let any_ne_empty: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
437        let empty = Dynamic::from("");
438        let non_empty = Dynamic::from("chat");
439
440        assert!(!any_ne_empty(&empty));
441        assert!(any_ne_empty(&non_empty));
442        Ok(())
443    }
444
445    #[test]
446    fn parenthesized_expression_can_call_any_method() -> anyhow::Result<()> {
447        let vm = Vm::with_all()?;
448        vm.import_code(
449            "vm_parenthesized_method_call",
450            br#"
451            pub fn run(value) {
452                (value + 2).to_i64()
453            }
454            "#
455            .to_vec(),
456        )?;
457
458        let compiled = vm.get_fn("vm_parenthesized_method_call::run", &[Type::Any])?;
459        assert_eq!(compiled.ret_ty(), &Type::I64);
460        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
461        let value = Dynamic::from(40i64);
462
463        assert_eq!(run(&value), 42);
464        Ok(())
465    }
466
467    #[test]
468    fn any_keys_returns_map_keys_and_empty_list_for_other_values() -> anyhow::Result<()> {
469        let vm = Vm::with_all()?;
470        vm.import_code(
471            "vm_any_keys",
472            br#"
473            pub fn map_keys(value) {
474                let keys = value.keys();
475                keys.len() == 2 && keys.contains("alpha") && keys.contains("beta")
476            }
477
478            pub fn non_map_keys(value) {
479                value.keys().len() == 0
480            }
481            "#
482            .to_vec(),
483        )?;
484
485        let compiled = vm.get_fn("vm_any_keys::map_keys", &[Type::Any])?;
486        assert_eq!(compiled.ret_ty(), &Type::Bool);
487        let map_keys: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
488        let value = dynamic::map!("alpha"=> 1i64, "beta"=> 2i64);
489        assert!(map_keys(&value));
490
491        let compiled = vm.get_fn("vm_any_keys::non_map_keys", &[Type::Any])?;
492        assert_eq!(compiled.ret_ty(), &Type::Bool);
493        let non_map_keys: extern "C" fn(*const Dynamic) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
494        let value = Dynamic::from("alpha");
495        assert!(non_map_keys(&value));
496        Ok(())
497    }
498
499    #[test]
500    fn compares_concrete_value_with_string_literal_as_string() -> anyhow::Result<()> {
501        let vm = Vm::with_all()?;
502        vm.import_code(
503            "vm_string_compare_imm",
504            br#"
505            pub fn int_eq_str(value: i64) {
506                value == "42"
507            }
508
509            pub fn int_to_str(value: i64) {
510                value + ""
511            }
512            "#
513            .to_vec(),
514        )?;
515
516        let compiled = vm.get_fn("vm_string_compare_imm::int_eq_str", &[Type::I64])?;
517        assert_eq!(compiled.ret_ty(), &Type::Bool);
518
519        let int_eq_str: extern "C" fn(i64) -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
520
521        let compiled = vm.get_fn("vm_string_compare_imm::int_to_str", &[Type::I64])?;
522        assert_eq!(compiled.ret_ty(), &Type::Any);
523        let int_to_str: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
524        let text = int_to_str(42);
525        assert_eq!(unsafe { &*text }.as_str(), "42");
526
527        assert!(int_eq_str(42));
528        assert!(!int_eq_str(7));
529        Ok(())
530    }
531
532    #[test]
533    fn concatenates_string_with_integer_values() -> anyhow::Result<()> {
534        let vm = Vm::with_all()?;
535        vm.import_code(
536            "vm_string_concat_integer",
537            br#"
538            pub fn idx_key(idx: i64) {
539                "" + idx
540            }
541
542            pub fn level_text(level: i64) {
543                "" + level + " level"
544            }
545
546            pub fn gold_text(currency) {
547                "" + currency.gold
548            }
549            "#
550            .to_vec(),
551        )?;
552
553        let compiled = vm.get_fn("vm_string_concat_integer::idx_key", &[Type::I64])?;
554        let idx_key: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
555        let result = unsafe { &*idx_key(7) };
556        assert_eq!(result.as_str(), "7");
557
558        let compiled = vm.get_fn("vm_string_concat_integer::level_text", &[Type::I64])?;
559        let level_text: extern "C" fn(i64) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
560        let result = unsafe { &*level_text(12) };
561        assert_eq!(result.as_str(), "12 level");
562
563        let compiled = vm.get_fn("vm_string_concat_integer::gold_text", &[Type::Any])?;
564        let gold_text: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
565        let currency = dynamic::map!("gold"=> 345i64);
566        let result = unsafe { &*gold_text(&currency) };
567        assert_eq!(result.as_str(), "345");
568        Ok(())
569    }
570
571    #[test]
572    fn coerces_string_concat_to_i64_without_unimplemented_log() -> anyhow::Result<()> {
573        let vm = Vm::with_all()?;
574        vm.import_code(
575            "vm_string_concat_to_i64",
576            br#"
577            pub fn run(idx: i64) {
578                ("" + idx) as i64
579            }
580            "#
581            .to_vec(),
582        )?;
583
584        let compiled = vm.get_fn("vm_string_concat_to_i64::run", &[Type::I64])?;
585        assert_eq!(compiled.ret_ty(), &Type::I64);
586        let run: extern "C" fn(i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
587        assert_eq!(run(7), 0);
588        Ok(())
589    }
590
591    #[test]
592    fn unifies_explicit_return_and_tail_integer_widths() -> anyhow::Result<()> {
593        let vm = Vm::with_all()?;
594        vm.import_code(
595            "vm_return_integer_widths",
596            br#"
597            pub fn selected(flag, slot) {
598                if flag {
599                    return slot;
600                }
601                0
602            }
603            "#
604            .to_vec(),
605        )?;
606
607        let compiled = vm.get_fn("vm_return_integer_widths::selected", &[Type::Bool, Type::I64])?;
608        assert_eq!(compiled.ret_ty(), &Type::I64);
609        let selected: extern "C" fn(bool, i64) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
610
611        assert_eq!(selected(true, 7), 7);
612        assert_eq!(selected(false, 7), 0);
613        Ok(())
614    }
615
616    #[test]
617    fn root_contains_string_concat_is_bool_condition() -> anyhow::Result<()> {
618        let vm = Vm::with_all()?;
619        vm.import_code(
620            "vm_root_contains_condition",
621            br#"
622            pub fn exists(user_id) {
623                if root::contains("redis/user/" + user_id) {
624                    return 1;
625                }
626                0
627            }
628            "#
629            .to_vec(),
630        )?;
631
632        assert_eq!(vm.infer("root::contains", &[Type::Any])?, Type::Bool);
633        let compiled = vm.get_fn("vm_root_contains_condition::exists", &[Type::Any])?;
634        assert_eq!(compiled.ret_ty(), &Type::I32);
635        Ok(())
636    }
637
638    #[test]
639    fn semicolon_tail_call_makes_function_void() -> anyhow::Result<()> {
640        let vm = Vm::with_all()?;
641        vm.import_code(
642            "vm_semicolon_tail_void",
643            br#"
644            pub fn send_role_select(idx, account_id, selected_slot) {
645                root::send("local/ui/send_dialog", {
646                    idx: idx,
647                    account_id: account_id,
648                    selected_slot: selected_slot
649                });
650            }
651            "#
652            .to_vec(),
653        )?;
654
655        let compiled = vm.get_fn("vm_semicolon_tail_void::send_role_select", &[Type::Any, Type::Any, Type::Any])?;
656        assert_eq!(compiled.ret_ty(), &Type::Void);
657        Ok(())
658    }
659
660    #[test]
661    fn bare_return_conflicts_with_non_void_return() -> anyhow::Result<()> {
662        let vm = Vm::with_all()?;
663        vm.import_code(
664            "vm_bare_return_conflict",
665            br#"
666            pub fn run(flag) {
667                if flag {
668                    return;
669                }
670                1
671            }
672            "#
673            .to_vec(),
674        )?;
675
676        let err = match vm.get_fn("vm_bare_return_conflict::run", &[Type::Bool]) {
677            Ok(_) => panic!("expected mismatched return types to fail"),
678            Err(err) => err,
679        };
680        assert!(format!("{err:#}").contains("返回类型不一致"));
681        Ok(())
682    }
683
684    #[test]
685    fn root_get_accepts_string_concat_with_dynamic_field() -> anyhow::Result<()> {
686        let vm = Vm::with_all()?;
687        vm.import_code(
688            "vm_root_get_dynamic_concat",
689            br#"
690            pub fn get_action(req) {
691                root::get("local/game/panel_actions/" + req.idx)
692            }
693            "#
694            .to_vec(),
695        )?;
696
697        root::add("local/game/panel_actions/7", dynamic::map!("id"=> "action-7").into())?;
698        let compiled = vm.get_fn("vm_root_get_dynamic_concat::get_action", &[Type::Any])?;
699        assert_eq!(compiled.ret_ty(), &Type::Any);
700        let get_action: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
701        let req = dynamic::map!("idx"=> 7i64);
702        let result = unsafe { &*get_action(&req) };
703
704        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("action-7".to_string()));
705        Ok(())
706    }
707
708    #[test]
709    fn root_add_fn_registers_handler_with_dynamic_field_path_concat() -> anyhow::Result<()> {
710        let vm = Vm::with_all()?;
711        vm.import_code(
712            "vm_registered_panel_action",
713            br#"
714            pub fn panel_action(req) {
715                root::get("local/game/panel_actions/" + req.idx)
716            }
717
718            pub fn register() {
719                root::add_fn("local/ui/panel_action", "vm_registered_panel_action::panel_action")
720            }
721            "#
722            .to_vec(),
723        )?;
724
725        let compiled = vm.get_fn("vm_registered_panel_action::register", &[])?;
726        assert_eq!(compiled.ret_ty(), &Type::Bool);
727        let register: extern "C" fn() -> bool = unsafe { std::mem::transmute(compiled.ptr()) };
728        assert!(register());
729        Ok(())
730    }
731
732    #[test]
733    fn root_add_fn_accepts_string_concat_in_registered_handler() -> anyhow::Result<()> {
734        let vm = Vm::with_all()?;
735        vm.import_code(
736            "vm_registered_string_concat",
737            br#"
738            pub fn send_panel(idx: i64) {
739                let idx_key = "" + idx;
740                idx_key
741            }
742            "#
743            .to_vec(),
744        )?;
745
746        assert!(vm.get_fn_ptr("vm_registered_string_concat::send_panel", &[Type::Any]).is_ok());
747        Ok(())
748    }
749
750    #[test]
751    fn compiles_public_hotspots_with_string_paths_and_keys() -> anyhow::Result<()> {
752        let vm = Vm::with_all()?;
753        vm.import_code(
754            "vm_public_hotspots",
755            br#"
756            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
757                {
758                    path: action_map_path,
759                    panel_id: panel_id,
760                    action_id: action_id,
761                    id: hotspot.id
762                }
763            }
764
765            pub fn public_hotspots(idx, panel_id, hotspots) {
766                let idx_key = "" + idx;
767                let action_map_path = "local/game/panel_actions/" + idx_key;
768
769                let existing_action_map = root::get(action_map_path);
770                if !existing_action_map.is_map() {
771                    root::add_map(action_map_path);
772                }
773
774                if hotspots.is_map() {
775                    let public_items = {};
776                    for action_id in hotspots.keys() {
777                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
778                    }
779                    return public_items;
780                }
781
782                let public_items = [];
783                let i = 0;
784                while i < hotspots.len() {
785                    let hotspot = hotspots.get_idx(i);
786                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
787                    public_items.push(item);
788                    i = i + 1;
789                }
790
791                public_items
792            }
793            "#
794            .to_vec(),
795        )?;
796
797        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::I64, Type::Any, Type::Any]).is_ok());
798        assert!(vm.get_fn("vm_public_hotspots::public_hotspots", &[Type::Any, Type::Any, Type::Any]).is_ok());
799        Ok(())
800    }
801
802    #[test]
803    fn send_panel_calls_public_hotspots_with_dynamic_request() -> anyhow::Result<()> {
804        let vm = Vm::with_all()?;
805        vm.import_code(
806            "vm_send_panel_public_hotspots",
807            br#"
808            pub fn ok(value) {
809                value
810            }
811
812            pub fn panel_from_node(req) {
813                {
814                    panel_id: req.panel_id,
815                    hotspots: req.hotspots
816                }
817            }
818
819            pub fn public_hotspot(action_map_path, panel_id, action_id, hotspot) {
820                {
821                    path: action_map_path,
822                    panel_id: panel_id,
823                    action_id: action_id,
824                    id: hotspot.id
825                }
826            }
827
828            pub fn public_hotspots(idx, panel_id, hotspots) {
829                let idx_key = "" + idx;
830                let action_map_path = "local/game/panel_actions/" + idx_key;
831
832                let existing_action_map = root::get(action_map_path);
833                if !existing_action_map.is_map() {
834                    root::add_map(action_map_path);
835                }
836
837                if hotspots.is_map() {
838                    let public_items = {};
839                    for action_id in hotspots.keys() {
840                        public_items[action_id] = public_hotspot(action_map_path, panel_id, action_id, hotspots[action_id]);
841                    }
842                    return public_items;
843                }
844
845                let public_items = [];
846                let i = 0;
847                while i < hotspots.len() {
848                    let hotspot = hotspots.get_idx(i);
849                    let item = public_hotspot(action_map_path, panel_id, hotspot.id, hotspot);
850                    public_items.push(item);
851                    i = i + 1;
852                }
853
854                public_items
855            }
856
857            pub fn send_panel(req) {
858                let panel = req.panel;
859                if !panel.is_map() {
860                    panel = panel_from_node(req);
861                }
862                if !panel.is_map() {
863                    return ok({
864                        id: 4,
865                        type: "panel_rejected",
866                        reason: "invalid panel"
867                    });
868                }
869                panel.id = 4;
870                panel.idx = req.idx;
871                if !panel.contains("type") {
872                    panel.type = "panel";
873                }
874                if panel.contains("hotspots") {
875                    panel.hotspots = public_hotspots(req.idx, panel.panel_id, panel.hotspots);
876                }
877                root::send_idx("local/ws", req.idx, panel);
878                ok({
879                    id: 4,
880                    type: "panel",
881                    panel_id: panel.panel_id
882                })
883            }
884            "#
885            .to_vec(),
886        )?;
887
888        let compiled = vm.get_fn("vm_send_panel_public_hotspots::send_panel", &[Type::Any])?;
889        assert_eq!(compiled.ret_ty(), &Type::Any);
890        let send_panel: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
891        let req = dynamic::map!(
892            "idx"=> 7i64,
893            "panel"=> dynamic::map!(
894                "panel_id"=> "main",
895                "hotspots"=> dynamic::map!(
896                    "open"=> dynamic::map!("id"=> "open")
897                )
898            )
899        );
900        let result = unsafe { &*send_panel(&req) };
901
902        assert_eq!(result.get_dynamic("type").map(|value| value.as_str().to_string()), Some("panel".to_string()));
903        assert_eq!(result.get_dynamic("panel_id").map(|value| value.as_str().to_string()), Some("main".to_string()));
904        Ok(())
905    }
906
907    #[test]
908    fn map_assignment_accepts_string_concat_key() -> anyhow::Result<()> {
909        let vm = Vm::with_all()?;
910        vm.import_code(
911            "vm_string_concat_map_key",
912            br##"
913            pub fn write_action(action_map, panel_id, action_id, action) {
914                action_map[panel_id + "#" + action_id] = action;
915                action_map[panel_id + "#" + action_id]
916            }
917            "##
918            .to_vec(),
919        )?;
920
921        let compiled = vm.get_fn("vm_string_concat_map_key::write_action", &[Type::Any, Type::Any, Type::Any, Type::Any])?;
922        let write_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
923        let action_map = dynamic::map!();
924        let panel_id: Dynamic = "panel".into();
925        let action_id: Dynamic = "open".into();
926        let action = dynamic::map!("id"=> "open");
927
928        let result = unsafe { &*write_action(&action_map, &panel_id, &action_id, &action) };
929
930        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
931        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()));
932        Ok(())
933    }
934
935    #[test]
936    fn map_get_key_accepts_string_concat_key_variable() -> anyhow::Result<()> {
937        let vm = Vm::with_all()?;
938        vm.import_code(
939            "vm_get_key_string_concat_key",
940            br##"
941            pub fn read_action(action_map, panel_id, action_id) {
942                let action_key = panel_id + "#" + action_id;
943                action_map.get_key(action_key)
944            }
945            "##
946            .to_vec(),
947        )?;
948
949        let compiled = vm.get_fn("vm_get_key_string_concat_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
950        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
951        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
952        let panel_id: Dynamic = "panel".into();
953        let action_id: Dynamic = "open".into();
954
955        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
956
957        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
958        Ok(())
959    }
960
961    #[test]
962    fn map_get_key_accepts_helper_string_key() -> anyhow::Result<()> {
963        let vm = Vm::with_all()?;
964        vm.import_code(
965            "vm_get_key_helper_string_key",
966            br##"
967            pub fn make_action_key(panel_id, action_id) {
968                panel_id + "#" + action_id
969            }
970
971            pub fn read_action(action_map, panel_id, action_id) {
972                let action_key = make_action_key(panel_id, action_id);
973                let action = action_map.get_key(action_key);
974                action
975            }
976            "##
977            .to_vec(),
978        )?;
979
980        let compiled = vm.get_fn("vm_get_key_helper_string_key::read_action", &[Type::Any, Type::Any, Type::Any])?;
981        let read_action: extern "C" fn(*const Dynamic, *const Dynamic, *const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
982        let action_map = dynamic::map!("panel#open"=> dynamic::map!("id"=> "open"));
983        let panel_id: Dynamic = "panel".into();
984        let action_id: Dynamic = "open".into();
985
986        let result = unsafe { &*read_action(&action_map, &panel_id, &action_id) };
987
988        assert_eq!(result.get_dynamic("id").map(|value| value.as_str().to_string()), Some("open".to_string()));
989        Ok(())
990    }
991
992    #[test]
993    fn dynamic_field_value_participates_in_or_expression() -> anyhow::Result<()> {
994        let vm = Vm::with_all()?;
995        vm.import_code(
996            "vm_dynamic_field_or",
997            r#"
998            pub fn next_or_start() {
999                let choice = {
1000                    label: "颜色",
1001                    next: "color"
1002                };
1003                choice.next || "start"
1004            }
1005
1006            pub fn direct_next() {
1007                let choice = {
1008                    label: "颜色",
1009                    next: "color"
1010                };
1011                choice.next
1012            }
1013
1014            pub fn bracket_next() {
1015                let choice = {
1016                    label: "颜色",
1017                    next: "color"
1018                };
1019                choice["next"]
1020            }
1021
1022            pub fn assigned_preview() {
1023                let choice = {
1024                    next: "tax_free"
1025                };
1026                choice.preview = choice.next || "start";
1027                choice
1028            }
1029            "#
1030            .as_bytes()
1031            .to_vec(),
1032        )?;
1033
1034        let compiled = vm.get_fn("vm_dynamic_field_or::direct_next", &[])?;
1035        assert_eq!(compiled.ret_ty(), &Type::Any);
1036        let direct_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1037        assert_eq!(unsafe { &*direct_next() }.as_str(), "color");
1038
1039        let compiled = vm.get_fn("vm_dynamic_field_or::bracket_next", &[])?;
1040        assert_eq!(compiled.ret_ty(), &Type::Any);
1041        let bracket_next: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1042        assert_eq!(unsafe { &*bracket_next() }.as_str(), "color");
1043
1044        let compiled = vm.get_fn("vm_dynamic_field_or::next_or_start", &[])?;
1045        assert_eq!(compiled.ret_ty(), &Type::Any);
1046        let next_or_start: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1047        assert_eq!(unsafe { &*next_or_start() }.as_str(), "color");
1048
1049        let compiled = vm.get_fn("vm_dynamic_field_or::assigned_preview", &[])?;
1050        assert_eq!(compiled.ret_ty(), &Type::Any);
1051        let assigned_preview: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1052        let choice = unsafe { &*assigned_preview() };
1053        assert_eq!(choice.get_dynamic("preview").unwrap().as_str(), "tax_free");
1054        Ok(())
1055    }
1056
1057    #[test]
1058    fn empty_object_literal_in_if_branch_stays_dynamic() -> anyhow::Result<()> {
1059        let vm = Vm::with_all()?;
1060        vm.import_code(
1061            "vm_if_empty_object_branch",
1062            r#"
1063            pub fn first_note(steps) {
1064                let first = if steps.len() > 0 { steps[0] } else { {} };
1065                let first_note = first.note || "fallback";
1066                first_note
1067            }
1068
1069            pub fn first_ja(steps) {
1070                let first = if steps.len() > 0 { steps[0] } else { {} };
1071                first.ja || "すみません"
1072            }
1073
1074            pub fn assign_first_note(steps) {
1075                let first = {};
1076                first = if steps.len() > 0 { steps[0] } else { {} };
1077                first.note || "fallback"
1078            }
1079            "#
1080            .as_bytes()
1081            .to_vec(),
1082        )?;
1083
1084        let compiled = vm.get_fn("vm_if_empty_object_branch::first_note", &[Type::Any])?;
1085        assert_eq!(compiled.ret_ty(), &Type::Any);
1086        let first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1087
1088        let empty_steps = Dynamic::list(Vec::new());
1089        assert_eq!(unsafe { &*first_note(&empty_steps) }.as_str(), "fallback");
1090
1091        let mut step = std::collections::BTreeMap::new();
1092        step.insert("note".into(), "hello".into());
1093        let steps = Dynamic::list(vec![Dynamic::map(step)]);
1094        assert_eq!(unsafe { &*first_note(&steps) }.as_str(), "hello");
1095
1096        let compiled = vm.get_fn("vm_if_empty_object_branch::first_ja", &[Type::Any])?;
1097        assert_eq!(compiled.ret_ty(), &Type::Any);
1098        let first_ja: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1099        assert_eq!(unsafe { &*first_ja(&empty_steps) }.as_str(), "すみません");
1100
1101        let compiled = vm.get_fn("vm_if_empty_object_branch::assign_first_note", &[Type::Any])?;
1102        assert_eq!(compiled.ret_ty(), &Type::Any);
1103        let assign_first_note: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1104        assert_eq!(unsafe { &*assign_first_note(&empty_steps) }.as_str(), "fallback");
1105        assert_eq!(unsafe { &*assign_first_note(&steps) }.as_str(), "hello");
1106        Ok(())
1107    }
1108
1109    #[test]
1110    fn list_literal_can_be_function_tail_expression() -> anyhow::Result<()> {
1111        let vm = Vm::with_all()?;
1112        vm.import_code(
1113            "vm_tail_list_literal",
1114            r#"
1115            pub fn numbers() {
1116                [1, 2, 3]
1117            }
1118
1119            pub fn maps() {
1120                [
1121                    {note: "first"},
1122                    {note: "second"}
1123                ]
1124            }
1125
1126            pub fn object_with_maps() {
1127                {
1128                    steps: [
1129                        {note: "first"},
1130                        {note: "second"}
1131                    ]
1132                }
1133            }
1134
1135            pub fn return_maps() {
1136                return [
1137                    {note: "first"},
1138                    {note: "second"}
1139                ];
1140            }
1141
1142            pub fn return_maps_without_semicolon() {
1143                return [
1144                    {note: "first"},
1145                    {note: "second"}
1146                ]
1147            }
1148
1149            pub fn tail_bare_variable() {
1150                let value = [
1151                    {note: "first"},
1152                    {note: "second"}
1153                ];
1154                value
1155            }
1156
1157            pub fn return_bare_variable_without_semicolon() {
1158                let value = [
1159                    {note: "first"},
1160                    {note: "second"}
1161                ];
1162                return value
1163            }
1164
1165            pub fn tail_object_variable() {
1166                let result = {
1167                    steps: [
1168                        {note: "first"},
1169                        {note: "second"}
1170                    ]
1171                };
1172                result
1173            }
1174            "#
1175            .as_bytes()
1176            .to_vec(),
1177        )?;
1178
1179        let compiled = vm.get_fn("vm_tail_list_literal::numbers", &[])?;
1180        assert_eq!(compiled.ret_ty(), &Type::Any);
1181        let numbers: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1182        let result = unsafe { &*numbers() };
1183        assert_eq!(result.len(), 3);
1184        assert_eq!(result.get_idx(1).and_then(|value| value.as_int()), Some(2));
1185
1186        let compiled = vm.get_fn("vm_tail_list_literal::maps", &[])?;
1187        assert_eq!(compiled.ret_ty(), &Type::Any);
1188        let maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1189        let result = unsafe { &*maps() };
1190        assert_eq!(result.len(), 2);
1191        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
1192
1193        let compiled = vm.get_fn("vm_tail_list_literal::object_with_maps", &[])?;
1194        assert_eq!(compiled.ret_ty(), &Type::Any);
1195        let object_with_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1196        let result = unsafe { &*object_with_maps() };
1197        let steps = result.get_dynamic("steps").expect("steps");
1198        assert_eq!(steps.len(), 2);
1199        assert_eq!(steps.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
1200
1201        let compiled = vm.get_fn("vm_tail_list_literal::return_maps", &[])?;
1202        assert_eq!(compiled.ret_ty(), &Type::Any);
1203        let return_maps: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1204        let result = unsafe { &*return_maps() };
1205        assert_eq!(result.len(), 2);
1206        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
1207
1208        let compiled = vm.get_fn("vm_tail_list_literal::return_maps_without_semicolon", &[])?;
1209        assert_eq!(compiled.ret_ty(), &Type::Any);
1210        let return_maps_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1211        let result = unsafe { &*return_maps_without_semicolon() };
1212        assert_eq!(result.len(), 2);
1213        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
1214
1215        let compiled = vm.get_fn("vm_tail_list_literal::tail_bare_variable", &[])?;
1216        assert_eq!(compiled.ret_ty(), &Type::Any);
1217        let tail_bare_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1218        let result = unsafe { &*tail_bare_variable() };
1219        assert_eq!(result.len(), 2);
1220        assert_eq!(result.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
1221
1222        let compiled = vm.get_fn("vm_tail_list_literal::return_bare_variable_without_semicolon", &[])?;
1223        assert_eq!(compiled.ret_ty(), &Type::Any);
1224        let return_bare_variable_without_semicolon: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1225        let result = unsafe { &*return_bare_variable_without_semicolon() };
1226        assert_eq!(result.len(), 2);
1227        assert_eq!(result.get_idx(0).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("first".to_string()));
1228
1229        let compiled = vm.get_fn("vm_tail_list_literal::tail_object_variable", &[])?;
1230        assert_eq!(compiled.ret_ty(), &Type::Any);
1231        let tail_object_variable: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1232        let result = unsafe { &*tail_object_variable() };
1233        let steps = result.get_dynamic("steps").expect("steps");
1234        assert_eq!(steps.len(), 2);
1235        assert_eq!(steps.get_idx(1).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("second".to_string()));
1236        Ok(())
1237    }
1238
1239    #[test]
1240    fn list_return_value_supports_get_idx_method_call() -> anyhow::Result<()> {
1241        let vm = Vm::with_all()?;
1242        vm.import_code(
1243            "vm_returned_list_get_idx",
1244            r#"
1245            pub fn ids() {
1246                [
1247                    "base",
1248                    "2",
1249                    "3"
1250                ]
1251            }
1252
1253            pub fn combinations() {
1254                let result = [];
1255                let values = ids();
1256                let idx = 0;
1257                while idx < values.len() {
1258                    result.push(values.get_idx(idx));
1259                    idx = idx + 1;
1260                }
1261                result
1262            }
1263            "#
1264            .as_bytes()
1265            .to_vec(),
1266        )?;
1267
1268        let compiled = vm.get_fn("vm_returned_list_get_idx::combinations", &[])?;
1269        assert_eq!(compiled.ret_ty(), &Type::Any);
1270        let combinations: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1271        let result = unsafe { &*combinations() };
1272
1273        assert_eq!(result.len(), 3);
1274        assert_eq!(result.get_idx(0).map(|value| value.as_str().to_string()), Some("base".to_string()));
1275        assert_eq!(result.get_idx(2).map(|value| value.as_str().to_string()), Some("3".to_string()));
1276        Ok(())
1277    }
1278
1279    #[test]
1280    fn repeated_deep_step_literals_import_successfully() -> anyhow::Result<()> {
1281        fn extra_page_literal(depth: usize) -> String {
1282            let mut value = "{leaf: \"done\"}".to_string();
1283            for idx in 0..depth {
1284                value = format!("{{kind: \"page\", idx: {idx}, children: [{value}], meta: {{title: \"extra\", visible: true}}}}");
1285            }
1286            value
1287        }
1288
1289        let extra = extra_page_literal(48);
1290        let code = format!(
1291            r#"
1292            pub fn script() {{
1293                return [
1294                    {{ja: "一つ目", note: "first", extra: {extra}}},
1295                    {{ja: "二つ目", note: "second", extra: {extra}}},
1296                    {{ja: "三つ目", note: "third", extra: {extra}}}
1297                ]
1298            }}
1299            "#
1300        );
1301
1302        let vm = Vm::with_all()?;
1303        vm.import_code("vm_repeated_deep_step_literals", code.into_bytes())?;
1304        let compiled = vm.get_fn("vm_repeated_deep_step_literals::script", &[])?;
1305        assert_eq!(compiled.ret_ty(), &Type::Any);
1306        let script: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1307        let result = unsafe { &*script() };
1308        assert_eq!(result.len(), 3);
1309        assert_eq!(result.get_idx(2).and_then(|value| value.get_dynamic("note")).map(|value| value.as_str().to_string()), Some("third".to_string()));
1310        Ok(())
1311    }
1312
1313    #[test]
1314    fn native_import_uses_owning_vm() -> anyhow::Result<()> {
1315        let module_path = std::env::temp_dir().join(format!("zust_vm_import_owner_{}.zs", std::process::id()));
1316        std::fs::write(&module_path, "pub fn value() { 41 }")?;
1317        let module_path = module_path.to_string_lossy().replace('\\', "\\\\").replace('"', "\\\"");
1318
1319        let vm1 = Vm::with_all()?;
1320        vm1.import_code(
1321            "vm_import_owner",
1322            format!(
1323                r#"
1324                pub fn run() {{
1325                    import("vm_imported_owner", "{module_path}");
1326                }}
1327                "#
1328            )
1329            .into_bytes(),
1330        )?;
1331        let compiled = vm1.get_fn("vm_import_owner::run", &[])?;
1332
1333        let vm2 = Vm::with_all()?;
1334        vm2.import_code("vm_import_other", b"pub fn run() { 0 }".to_vec())?;
1335        let _ = vm2.get_fn("vm_import_other::run", &[])?;
1336
1337        let run: extern "C" fn() = unsafe { std::mem::transmute(compiled.ptr()) };
1338        run();
1339
1340        assert!(vm1.get_fn("vm_imported_owner::value", &[]).is_ok());
1341        assert!(vm2.get_fn("vm_imported_owner::value", &[]).is_err());
1342        Ok(())
1343    }
1344
1345    #[test]
1346    fn object_last_field_call_does_not_need_trailing_comma() -> anyhow::Result<()> {
1347        let vm = Vm::with_all()?;
1348        vm.import_code(
1349            "vm_object_last_call_field",
1350            r#"
1351            pub fn extra_page() {
1352                {
1353                    title: "extra",
1354                    pages: [
1355                        {note: "nested"}
1356                    ]
1357                }
1358            }
1359
1360            pub fn data() {
1361                return [
1362                    {
1363                        note: "first",
1364                        choices: ["a", "b"],
1365                        extras: extra_page()
1366                    },
1367                    {
1368                        note: "second",
1369                        choices: ["c"],
1370                        extras: extra_page()
1371                    }
1372                ]
1373            }
1374            "#
1375            .as_bytes()
1376            .to_vec(),
1377        )?;
1378
1379        let compiled = vm.get_fn("vm_object_last_call_field::data", &[])?;
1380        assert_eq!(compiled.ret_ty(), &Type::Any);
1381        let data: extern "C" fn() -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1382        let result = unsafe { &*data() };
1383        assert_eq!(result.len(), 2);
1384        let first = result.get_idx(0).expect("first step");
1385        assert_eq!(first.get_dynamic("extras").and_then(|extras| extras.get_dynamic("title")).map(|title| title.as_str().to_string()), Some("extra".to_string()));
1386        Ok(())
1387    }
1388
1389    #[test]
1390    fn gpu_struct_layout_packs_and_unpacks_dynamic_maps() -> anyhow::Result<()> {
1391        let vm = Vm::with_all()?;
1392        vm.import_code(
1393            "vm_gpu_layout",
1394            br#"
1395            pub struct Params {
1396                a: u32,
1397                b: u32,
1398                c: u32,
1399            }
1400            "#
1401            .to_vec(),
1402        )?;
1403
1404        let layout = vm.gpu_struct_layout("vm_gpu_layout::Params", &[])?;
1405        assert_eq!(layout.size, 16);
1406        assert_eq!(layout.fields.iter().map(|field| (field.name.as_str(), field.offset)).collect::<Vec<_>>(), vec![("a", 0), ("b", 4), ("c", 8)]);
1407
1408        let value = dynamic::map!("a"=> 1u32, "b"=> 2u32, "c"=> 3u32);
1409        let bytes = layout.pack_map(&value)?;
1410        assert_eq!(bytes.len(), 16);
1411        assert_eq!(&bytes[0..4], &1u32.to_ne_bytes());
1412        assert_eq!(&bytes[4..8], &2u32.to_ne_bytes());
1413        assert_eq!(&bytes[8..12], &3u32.to_ne_bytes());
1414
1415        let read = layout.unpack_map(&bytes)?;
1416        assert_eq!(read.get_dynamic("a").and_then(|value| value.as_uint()), Some(1));
1417        assert_eq!(read.get_dynamic("b").and_then(|value| value.as_uint()), Some(2));
1418        assert_eq!(read.get_dynamic("c").and_then(|value| value.as_uint()), Some(3));
1419        Ok(())
1420    }
1421
1422    #[test]
1423    fn root_native_calls_do_not_take_ownership_of_dynamic_args() -> anyhow::Result<()> {
1424        let vm = Vm::with_all()?;
1425        vm.import_code(
1426            "vm_root_clone_bridge",
1427            br#"
1428            pub fn add_then_reuse(arg) {
1429                let user = {
1430                    address: "test-wallet",
1431                    points: 20
1432                };
1433                root::add("local/root-clone-bridge-user", user);
1434                user.points = user.points - 7;
1435                root::add("local/root-clone-bridge-user", user);
1436                {
1437                    user: user,
1438                    points: user.points
1439                }
1440            }
1441
1442            pub fn clone_then_mutate(arg) {
1443                let user = {
1444                    profile: {
1445                        points: 20
1446                    }
1447                };
1448                let copied = user.clone();
1449                copied.profile.points = 13;
1450                user
1451            }
1452            "#
1453            .to_vec(),
1454        )?;
1455
1456        let compiled = vm.get_fn("vm_root_clone_bridge::add_then_reuse", &[Type::Any])?;
1457        assert_eq!(compiled.ret_ty(), &Type::Any);
1458        let add_then_reuse: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(compiled.ptr()) };
1459        let arg = Dynamic::Null;
1460        let result = add_then_reuse(&arg);
1461        let result = unsafe { &*result };
1462
1463        assert_eq!(result.get_dynamic("points").and_then(|value| value.as_int()), Some(13));
1464        let mut json = String::new();
1465        result.to_json(&mut json);
1466        assert!(json.contains("\"points\": 13"));
1467
1468        let clone_then_mutate = vm.get_fn("vm_root_clone_bridge::clone_then_mutate", &[Type::Any])?;
1469        let clone_then_mutate: extern "C" fn(*const Dynamic) -> *const Dynamic = unsafe { std::mem::transmute(clone_then_mutate.ptr()) };
1470        let result = clone_then_mutate(&arg);
1471        let result = unsafe { &*result };
1472        assert_eq!(result.get_dynamic("profile").unwrap().get_dynamic("points").and_then(|value| value.as_int()), Some(20));
1473        Ok(())
1474    }
1475
1476    struct CounterForTypedReceiver {
1477        value: i64,
1478    }
1479
1480    extern "C" fn counter_for_typed_receiver_get(value: *const Dynamic) -> i64 {
1481        unsafe { &*value }.as_custom::<CounterForTypedReceiver>().map(|counter| counter.value).unwrap_or(-1)
1482    }
1483
1484    #[test]
1485    fn typed_receiver_method_call_dispatches_with_type_hint() -> anyhow::Result<()> {
1486        let vm = Vm::with_all()?;
1487        vm.add_empty_type("Counter")?;
1488        let counter_ty = vm.get_symbol("Counter", Vec::new())?;
1489        vm.add_native_method_ptr("Counter", "get", &[counter_ty], Type::I64, counter_for_typed_receiver_get as *const u8)?;
1490        vm.import_code(
1491            "vm_typed_receiver_method",
1492            br#"
1493            pub fn run(value) {
1494                value::<Counter>::get()
1495            }
1496            "#
1497            .to_vec(),
1498        )?;
1499
1500        let compiled = vm.get_fn("vm_typed_receiver_method::run", &[Type::Any])?;
1501        assert_eq!(compiled.ret_ty(), &Type::I64);
1502        let run: extern "C" fn(*const Dynamic) -> i64 = unsafe { std::mem::transmute(compiled.ptr()) };
1503        let value = Dynamic::custom(CounterForTypedReceiver { value: 42 });
1504
1505        assert_eq!(run(&value), 42);
1506        Ok(())
1507    }
1508}