1
use std::io;
2

            
3
use crossterm::ExecutableCommand;
4
use crossterm::event::{self, Event, KeyCode, KeyEventKind, KeyModifiers};
5
use crossterm::terminal::{
6
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
7
};
8
use ratatui::prelude::*;
9
use ratatui::widgets::{Block, Borders, Paragraph, Wrap};
10
use scripting::nomiscript::{Pair, Value, format_value};
11

            
12
use nms::interpreter::Interpreter;
13

            
14
struct App<'a> {
15
    input: String,
16
    cursor_pos: usize,
17
    output: Vec<Line<'a>>,
18
    should_quit: bool,
19
    interpreter: Interpreter,
20
}
21

            
22
impl App<'_> {
23
    fn new() -> anyhow::Result<Self> {
24
        Ok(Self {
25
            input: String::new(),
26
            cursor_pos: 0,
27
            output: vec![Line::from(
28
                "Welcome to Nomiscript REPL. Type expressions and press Enter.",
29
            )],
30
            should_quit: false,
31
            interpreter: Interpreter::new(false)?,
32
        })
33
    }
34

            
35
    fn eval_input(&mut self) {
36
        if self.input.trim().is_empty() {
37
            return;
38
        }
39

            
40
        let input = self.input.clone();
41
        self.output.push(Line::from(Span::styled(
42
            format!("> {input}"),
43
            Style::default(),
44
        )));
45

            
46
        match self.interpreter.eval(&input) {
47
            Ok(values) => {
48
                for value in values {
49
                    self.output.push(format_value_line(&value));
50
                }
51
            }
52
            Err(e) => {
53
                for line in e.render(false).lines() {
54
                    self.output.push(format_error_line(line));
55
                }
56
            }
57
        }
58

            
59
        self.input.clear();
60
        self.cursor_pos = 0;
61
    }
62

            
63
    fn insert_char(&mut self, c: char) {
64
        self.input.insert(self.cursor_pos, c);
65
        self.cursor_pos += 1;
66
    }
67

            
68
    fn delete_char(&mut self) {
69
        if self.cursor_pos > 0 {
70
            self.cursor_pos -= 1;
71
            self.input.remove(self.cursor_pos);
72
        }
73
    }
74

            
75
    fn move_cursor_left(&mut self) {
76
        if self.cursor_pos > 0 {
77
            self.cursor_pos -= 1;
78
        }
79
    }
80

            
81
    fn move_cursor_right(&mut self) {
82
        if self.cursor_pos < self.input.len() {
83
            self.cursor_pos += 1;
84
        }
85
    }
86
}
87

            
88
6
fn format_value_line(value: &Value) -> Line<'static> {
89
6
    Line::from(format_value_spans(value))
90
6
}
91

            
92
fn format_error_line(line: &str) -> Line<'static> {
93
    let red = Style::default().fg(Color::Red);
94
    let cyan = Style::default().fg(Color::Cyan);
95

            
96
    if let Some(rest) = line.strip_prefix("error:") {
97
        Line::from(vec![
98
            Span::styled("error:", red),
99
            Span::raw(rest.to_string()),
100
        ])
101
    } else if line.contains('|') {
102
        let mut spans = Vec::new();
103
        let chars = line.chars().peekable();
104
        let mut current = String::new();
105

            
106
        for c in chars {
107
            if c == '|' {
108
                if !current.is_empty() {
109
                    spans.push(Span::styled(current, cyan));
110
                    current = String::new();
111
                }
112
                spans.push(Span::styled("|", cyan));
113
            } else if c == '^' {
114
                if !current.is_empty() {
115
                    spans.push(Span::raw(current));
116
                    current = String::new();
117
                }
118
                spans.push(Span::styled("^", red));
119
            } else {
120
                current.push(c);
121
            }
122
        }
123
        if !current.is_empty() {
124
            spans.push(Span::raw(current));
125
        }
126
        Line::from(spans)
127
    } else {
128
        Line::from(line.to_string())
129
    }
130
}
131

            
132
100017
fn format_value_spans(value: &Value) -> Vec<Span<'static>> {
133
100017
    let dim = Style::default().fg(Color::DarkGray);
134
100017
    match value {
135
        Value::Nil => vec![Span::styled("nil", dim)],
136
        Value::T => vec![Span::styled("t", Style::default().fg(Color::Green))],
137
        Value::Number(n) => {
138
100009
            let text = n.to_string();
139
100009
            vec![Span::styled(text, Style::default().fg(Color::Cyan))]
140
        }
141
        Value::String(s) => vec![Span::styled(
142
            format!("\"{s}\""),
143
            Style::default().fg(Color::Yellow),
144
        )],
145
        Value::Symbol(s) => vec![Span::styled(s.clone(), Style::default().fg(Color::Magenta))],
146
        Value::Pair(pair) => {
147
6
            let mut spans = vec![Span::styled("(", dim)];
148
6
            spans.extend(format_list_spans(pair));
149
6
            spans.push(Span::styled(")", dim));
150
6
            spans
151
        }
152
        Value::Vector(elems) => {
153
            let mut spans = vec![Span::styled("#(", dim)];
154
            for (i, elem) in elems.iter().enumerate() {
155
                if i > 0 {
156
                    spans.push(Span::styled(" ", dim));
157
                }
158
                spans.extend(format_value_spans(elem));
159
            }
160
            spans.push(Span::styled(")", dim));
161
            spans
162
        }
163
        Value::Bytes(b) => vec![Span::styled(
164
            format_bytes_inline(b),
165
            Style::default().fg(Color::Yellow),
166
        )],
167
        Value::Closure(_) | Value::Condition => vec![Span::styled(format_value(value), dim)],
168
2
        Value::Struct { .. } => vec![Span::styled(
169
2
            format_value(value),
170
2
            Style::default().fg(Color::Blue),
171
2
        )],
172
        Value::Commodity {
173
            amount,
174
            commodity_id,
175
        } => {
176
            let amt = scripting::nomiscript::format_amount(*amount);
177
            vec![Span::styled(
178
                format!("(:commodity {amt} :id \"{commodity_id}\")"),
179
                Style::default().fg(Color::Cyan),
180
            )]
181
        }
182
    }
183
100017
}
184

            
185
fn format_bytes_inline(bytes: &[u8]) -> String {
186
    let parts: Vec<String> = bytes.iter().map(u8::to_string).collect();
187
    format!("#u8({})", parts.join(" "))
188
}
189

            
190
6
fn format_list_spans(pair: &Pair) -> Vec<Span<'static>> {
191
6
    let dim = Style::default().fg(Color::DarkGray);
192
6
    let mut spans = format_value_spans(&pair.car);
193
6
    let mut cdr = &pair.cdr;
194
    loop {
195
100010
        match cdr {
196
5
            Value::Nil => break,
197
            Value::Pair(next) => {
198
100004
                spans.push(Span::styled(" ", dim));
199
100004
                spans.extend(format_value_spans(&next.car));
200
100004
                cdr = &next.cdr;
201
            }
202
            other => {
203
1
                spans.push(Span::styled(" . ", dim));
204
1
                spans.extend(format_value_spans(other));
205
1
                break;
206
            }
207
        }
208
    }
209
6
    spans
210
6
}
211

            
212
pub fn run() -> anyhow::Result<()> {
213
    enable_raw_mode()?;
214
    io::stdout().execute(EnterAlternateScreen)?;
215

            
216
    let backend = CrosstermBackend::new(io::stdout());
217
    let mut terminal = Terminal::new(backend)?;
218
    let mut app = App::new()?;
219

            
220
    while !app.should_quit {
221
        terminal.draw(|frame| ui(frame, &app))?;
222
        handle_events(&mut app)?;
223
    }
224

            
225
    disable_raw_mode()?;
226
    io::stdout().execute(LeaveAlternateScreen)?;
227
    Ok(())
228
}
229

            
230
fn ui(frame: &mut Frame, app: &App) {
231
    let chunks = Layout::default()
232
        .direction(Direction::Vertical)
233
        .constraints([Constraint::Min(3), Constraint::Length(3)])
234
        .split(frame.area());
235

            
236
    let output_widget = Paragraph::new(Text::from(app.output.clone()))
237
        .block(Block::default().borders(Borders::ALL).title("Output"))
238
        .wrap(Wrap { trim: false })
239
        .scroll((
240
            app.output
241
                .len()
242
                .saturating_sub(chunks[0].height as usize - 2) as u16,
243
            0,
244
        ));
245
    frame.render_widget(output_widget, chunks[0]);
246

            
247
    let input_widget = Paragraph::new(app.input.as_str()).block(
248
        Block::default()
249
            .borders(Borders::ALL)
250
            .title("Input (Ctrl+C to quit)"),
251
    );
252
    frame.render_widget(input_widget, chunks[1]);
253

            
254
    frame.set_cursor_position(Position::new(
255
        chunks[1].x + app.cursor_pos as u16 + 1,
256
        chunks[1].y + 1,
257
    ));
258
}
259

            
260
fn handle_events(app: &mut App) -> anyhow::Result<()> {
261
    if event::poll(std::time::Duration::from_millis(100))?
262
        && let Event::Key(key) = event::read()?
263
    {
264
        if key.kind != KeyEventKind::Press {
265
            return Ok(());
266
        }
267

            
268
        match (key.modifiers, key.code) {
269
            (KeyModifiers::CONTROL, KeyCode::Char('c')) => {
270
                app.should_quit = true;
271
            }
272
            (_, KeyCode::Enter) => {
273
                app.eval_input();
274
            }
275
            (_, KeyCode::Backspace) => {
276
                app.delete_char();
277
            }
278
            (_, KeyCode::Left) => {
279
                app.move_cursor_left();
280
            }
281
            (_, KeyCode::Right) => {
282
                app.move_cursor_right();
283
            }
284
            (_, KeyCode::Char(c)) => {
285
                app.insert_char(c);
286
            }
287
            _ => {}
288
        }
289
    }
290
    Ok(())
291
}
292

            
293
#[cfg(test)]
294
#[path = "repl_tests.rs"]
295
mod tests;