about summary refs log tree commit diff
path: root/tvix/cli/src/repl.rs
blob: 50c1779b0b6844183b8eea85d29be75c9246dd49 (plain) (blame)
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use std::path::PathBuf;
use std::rc::Rc;

use rustyline::{error::ReadlineError, Editor};
use tvix_glue::tvix_store_io::TvixStoreIO;

use crate::{interpret, AllowIncomplete, Args, IncompleteInput};

fn state_dir() -> Option<PathBuf> {
    let mut path = dirs::data_dir();
    if let Some(p) = path.as_mut() {
        p.push("tvix")
    }
    path
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplCommand<'a> {
    Expr(&'a str),
    Explain(&'a str),
    Quit,
}

impl<'a> ReplCommand<'a> {
    pub fn parse(input: &'a str) -> Self {
        if let Some(without_prefix) = input.strip_prefix(":d ") {
            Self::Explain(without_prefix)
        } else if input.trim_end() == ":q" {
            Self::Quit
        } else {
            Self::Expr(input)
        }
    }
}

#[derive(Debug)]
pub struct Repl {
    /// In-progress multiline input, when the input so far doesn't parse as a complete expression
    multiline_input: Option<String>,
    rl: Editor<()>,
}

impl Repl {
    pub fn new() -> Self {
        let rl = Editor::<()>::new().expect("should be able to launch rustyline");
        Self {
            multiline_input: None,
            rl,
        }
    }

    pub fn run(&mut self, io_handle: Rc<TvixStoreIO>, args: &Args) {
        if args.compile_only {
            eprintln!("warning: `--compile-only` has no effect on REPL usage!");
        }

        let history_path = match state_dir() {
            // Attempt to set up these paths, but do not hard fail if it
            // doesn't work.
            Some(mut path) => {
                let _ = std::fs::create_dir_all(&path);
                path.push("history.txt");
                let _ = self.rl.load_history(&path);
                Some(path)
            }

            None => None,
        };

        loop {
            let prompt = if self.multiline_input.is_some() {
                "         > "
            } else {
                "tvix-repl> "
            };

            let readline = self.rl.readline(prompt);
            match readline {
                Ok(line) => {
                    if line.is_empty() {
                        continue;
                    }

                    let input = if let Some(mi) = &mut self.multiline_input {
                        mi.push('\n');
                        mi.push_str(&line);
                        mi
                    } else {
                        &line
                    };

                    let res = match ReplCommand::parse(input) {
                        ReplCommand::Quit => break,
                        ReplCommand::Expr(input) => interpret(
                            Rc::clone(&io_handle),
                            input,
                            None,
                            args,
                            false,
                            AllowIncomplete::Allow,
                        ),
                        ReplCommand::Explain(input) => interpret(
                            Rc::clone(&io_handle),
                            input,
                            None,
                            args,
                            true,
                            AllowIncomplete::Allow,
                        ),
                    };

                    match res {
                        Ok(_) => {
                            self.rl.add_history_entry(input);
                            self.multiline_input = None;
                        }
                        Err(IncompleteInput) => {
                            if self.multiline_input.is_none() {
                                self.multiline_input = Some(line);
                            }
                        }
                    }
                }
                Err(ReadlineError::Interrupted) | Err(ReadlineError::Eof) => break,

                Err(err) => {
                    eprintln!("error: {}", err);
                    break;
                }
            }
        }

        if let Some(path) = history_path {
            self.rl.save_history(&path).unwrap();
        }
    }
}