1use crate::memory::Memory;
2use crate::stack::Stack;
3use std::io::{Read, Write};
4use wain_ast::ValType;
5
6pub enum ImportInvalidError {
7 NotFound,
8 SignatureMismatch {
9 expected_params: &'static [ValType],
10 expected_ret: Option<ValType>,
11 },
12}
13
14pub enum ImportInvokeError {
15 Fatal { message: String },
16}
17
18pub trait Importer {
19 const MODULE_NAME: &'static str = "env";
20 fn validate(&self, name: &str, params: &[ValType], ret: Option<ValType>) -> Option<ImportInvalidError>;
21 fn call(&mut self, name: &str, stack: &mut Stack, memory: &mut Memory) -> Result<(), ImportInvokeError>;
22}
23
24pub fn check_func_signature(
25 actual_params: &[ValType],
26 actual_ret: Option<ValType>,
27 expected_params: &'static [ValType],
28 expected_ret: Option<ValType>,
29) -> Option<ImportInvalidError> {
30 if actual_params.eq(expected_params) && actual_ret == expected_ret {
31 return None;
32 }
33 Some(ImportInvalidError::SignatureMismatch {
34 expected_params,
35 expected_ret,
36 })
37}
38
39pub struct DefaultImporter<R: Read, W: Write> {
40 stdout: W,
41 stdin: R,
42}
43
44impl<R: Read, W: Write> Drop for DefaultImporter<R, W> {
45 fn drop(&mut self) {
46 let _ = self.stdout.flush();
47 }
48}
49
50impl<R: Read, W: Write> DefaultImporter<R, W> {
51 pub fn with_stdio(stdin: R, stdout: W) -> Self {
52 Self { stdout, stdin }
53 }
54
55 fn putchar(&mut self, stack: &mut Stack) {
57 let v: i32 = stack.pop();
58 let b = v as u8;
59 let ret = match self.stdout.write(&[b]) {
60 Ok(_) => b as i32,
61 Err(_) => -1, };
63 stack.push(ret);
64 }
65
66 fn getchar(&mut self, stack: &mut Stack) {
68 let mut buf = [0u8];
69 let v = match self.stdin.read_exact(&mut buf) {
70 Ok(()) => buf[0] as i32,
71 Err(_) => -1, };
73 stack.push(v);
74 }
75
76 fn memcpy(&mut self, stack: &mut Stack, memory: &mut Memory) -> Result<(), ImportInvokeError> {
78 let size = stack.pop::<i32>() as u32 as usize;
80 let src_start = stack.pop::<i32>() as u32 as usize;
81 let dest_i32: i32 = stack.pop();
82 let dest_start = dest_i32 as u32 as usize;
83 let src_end = src_start + size;
84 let dest_end = dest_start + size;
85
86 let (dest, src) = if dest_end <= src_start {
87 let (dest, src) = memory.data_mut().split_at_mut(src_start);
88 (&mut dest[dest_start..dest_end], &mut src[..size])
89 } else if src_end <= dest_start {
90 let (src, dest) = memory.data_mut().split_at_mut(dest_start);
91 (&mut dest[..size], &mut src[src_start..src_end])
92 } else {
93 return Err(ImportInvokeError::Fatal {
94 message: format!(
95 "range overwrap on memcpy: src={}..{} and dest={}..{}",
96 src_start, src_end, dest_start, dest_end
97 ),
98 });
99 };
100
101 dest.copy_from_slice(src);
102 stack.push(dest_i32);
103 Ok(())
104 }
105}
106
107impl<R: Read, W: Write> Importer for DefaultImporter<R, W> {
108 fn validate(&self, name: &str, params: &[ValType], ret: Option<ValType>) -> Option<ImportInvalidError> {
109 use ValType::*;
110 match name {
111 "putchar" => check_func_signature(params, ret, &[I32], Some(I32)),
112 "getchar" => check_func_signature(params, ret, &[], Some(I32)),
113 "memcpy" => check_func_signature(params, ret, &[I32, I32, I32], Some(I32)),
114 "abort" => check_func_signature(params, ret, &[], None),
115 _ => Some(ImportInvalidError::NotFound),
116 }
117 }
118
119 fn call(&mut self, name: &str, stack: &mut Stack, memory: &mut Memory) -> Result<(), ImportInvokeError> {
120 match name {
121 "putchar" => {
122 self.putchar(stack);
123 Ok(())
124 }
125 "getchar" => {
126 self.getchar(stack);
127 Ok(())
128 }
129 "abort" => Err(ImportInvokeError::Fatal {
130 message: "aborted".to_string(),
131 }),
132 "memcpy" => self.memcpy(stack, memory),
133 _ => unreachable!("fatal: invalid import function '{}'", name),
134 }
135 }
136}