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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
use crate::rail_machine::{RailRunResult, RailState, RunConventions};
use crate::tokens::Token;
use crate::{loading, log};
use rustyline::error::ReadlineError;
use rustyline::Editor;

pub struct RailPrompt {
    is_tty: bool,
    editor: Editor<()>,
    conventions: &'static RunConventions<'static>,
}

impl RailPrompt {
    pub fn new(conventions: &'static RunConventions) -> RailPrompt {
        let mut editor = Editor::<()>::new().expect("Unable to boot editor");
        let is_tty = editor.dimensions().is_some();

        RailPrompt {
            is_tty,
            editor,
            conventions,
        }
    }

    pub fn run(self, state: RailState) -> RailRunResult {
        log::info(
            state.conventions,
            format!(
                "{} {}",
                self.conventions.exe_name, self.conventions.exe_version
            ),
        );

        self.fold(Ok(state), |state, term| {
            let result = state.unwrap_or_else(|_| unreachable!()).run_tokens(term);
            let result = log::error_coerce(result);
            Ok(result)
        })
    }
}

impl Iterator for RailPrompt {
    type Item = Vec<Token>;

    fn next(&mut self) -> Option<Self::Item> {
        // If we're interactive with a human (at a TTY and not piped stdin),
        // we pad with a newline in case the user uses print without newline.
        // (Otherwise, the prompt will rewrite the line with output.)
        if self.is_tty {
            println!();
        }

        let input = self.editor.readline("> ");

        if let Err(e) = input {
            // ^D and ^C are not error cases.
            if let ReadlineError::Eof = e {
                log::fatal(self.conventions, "End of input");
                return None;
            } else if let ReadlineError::Interrupted = e {
                log::fatal(self.conventions, "Process interrupt");
                return None;
            }

            log::fatal(self.conventions, e);
            std::process::exit(1);
        }

        let input = input.unwrap();

        self.editor.add_history_entry(&input);

        Some(loading::get_source_as_tokens(input))
    }
}