1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
use std::io::prelude::*;

pub struct Repl<S, F>
where
    F: Fn(&mut S, String) -> Option<String>,
{
    state: S,
    print: &'static str,
    evaluate: F,
}

impl<S, F> Repl<S, F>
where
    F: Fn(&mut S, String) -> Option<String>,
{
    pub fn new(print: &'static str, state: S, evaluate: F) -> Self {
        Self {
            state,
            evaluate,
            print,
        }
    }

    pub fn run(&mut self) {
        loop {
            print!("{}", self.print);
            std::io::stdout().flush().unwrap();

            let input = {
                let mut input = String::new();
                std::io::stdin()
                    .read_line(&mut input)
                    .ok()
                    .expect("Failed to read line");
                input
            };

            // 1. Match the input against any internal commands that we have
            // 2. Else, evaluate.
            match input.as_str() {
                // TODO: In the future, we might have an additional checks here if the user also defined/override the internal commands.
                "exit" | "quit" => break,
                "clear" => unimplemented!(
                    "'clear' is currently not implemented. It should clear the screen."
                ),
                _ => {
                    if let Some(result) = (self.evaluate)(&mut self.state, input) {
                        println!("{}", result)
                    }
                }
            }
        }
    }
}