ablescript/
host_interface.rs

1use crate::value::Variable;
2use std::collections::HashMap;
3
4/// Host Environment Interface
5pub trait HostInterface {
6    /// Initial variables for a stack frame
7    fn initial_vars(&mut self) -> HashMap<String, Variable>;
8
9    /// Print a string
10    fn print(&mut self, string: &str, new_line: bool) -> std::io::Result<()>;
11
12    /// Read a byte
13    fn read_byte(&mut self) -> std::io::Result<u8>;
14
15    /// This function should exit the program with specified code.
16    ///
17    /// For cases where exit is not desired, just let the function return
18    /// and interpreter will terminate with an error.
19    fn exit(&mut self, code: i32);
20}
21
22/// Standard [HostInterface] implementation
23#[derive(Clone, Copy, Default)]
24pub struct Standard;
25impl HostInterface for Standard {
26    fn initial_vars(&mut self) -> HashMap<String, Variable> {
27        HashMap::default()
28    }
29
30    fn print(&mut self, string: &str, new_line: bool) -> std::io::Result<()> {
31        use std::io::Write;
32
33        let mut stdout = std::io::stdout();
34        stdout.write_all(string.as_bytes())?;
35        if new_line {
36            stdout.write_all(b"\n")?;
37        }
38
39        Ok(())
40    }
41
42    fn read_byte(&mut self) -> std::io::Result<u8> {
43        use std::io::Read;
44
45        let mut buf = [0];
46        std::io::stdin().read_exact(&mut buf)?;
47        Ok(buf[0])
48    }
49
50    fn exit(&mut self, code: i32) {
51        std::process::exit(code);
52    }
53}