-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepl.rs
191 lines (158 loc) · 5.82 KB
/
repl.rs
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
use std::env;
use std::sync::{Arc, Mutex};
use rustyline::completion::{Completer, Pair};
use rustyline::error::ReadlineError;
use rustyline::{CompletionType, Config, Editor};
use rustyline_derive::{Helper, Highlighter, Hinter, Validator};
use crate::interpreter;
use crate::parser;
#[derive(Helper, Highlighter, Hinter, Validator)]
struct RlHelper {
context: Arc<Mutex<interpreter::Context>>,
}
impl Completer for RlHelper {
type Candidate = Pair;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<Self::Candidate>)> {
let prefix = &line[..pos];
fn is_split_char(c: char) -> bool {
matches!(c, ' ' | ':' | '(' | '{')
}
// Split off last "word"
let parts = prefix.split(is_split_char).collect::<Vec<&str>>();
let prefix = if parts.len() > 1 {
*parts.last().unwrap()
} else {
prefix
};
let parts = prefix.split('.').collect::<Vec<&str>>();
// Case 1: no member access
if parts.len() == 1 {
let context = self.context.lock().unwrap();
let vars = context.list_vars();
let prefix_len = prefix.len();
let candidates = vars
.into_iter()
.flat_map(|vars_in_scope| {
vars_in_scope
.into_iter()
.filter(|var| prefix_len <= var.len() && &var[..prefix_len] == prefix)
.map(|var| Pair {
display: var.clone(),
replacement: var,
})
})
.collect::<Vec<Pair>>();
return Ok((pos - prefix_len, candidates));
}
// Case 2: member access
if parts.len() > 1 {
let expr = parts[..(parts.len() - 1)].join(".");
let ast = parser::parse_string(&expr).ok();
let result = ast.and_then(|ast| {
interpreter::exec_with_context(&ast, &mut self.context.lock().unwrap()).ok()
});
if let Some(value) = result {
use interpreter::Value;
let keys = match value {
Value::Map(map) => map.keys().cloned().collect::<Vec<String>>(),
Value::List(_) => vec![String::from("length")],
Value::String(_) => vec![String::from("length")],
Value::Function(_) => vec![String::from("name")],
_ => vec![],
};
let prefix = parts.last().unwrap();
let prefix_len = prefix.len();
let candidates = keys
.into_iter()
.filter(|var| prefix_len <= var.len() && &var[..prefix_len] == *prefix)
.map(|key| Pair {
display: key.clone(),
replacement: key,
})
.collect::<Vec<Pair>>();
return Ok((pos - prefix_len, candidates));
}
}
Ok((0, vec![]))
}
}
pub fn start(context: interpreter::Context) {
let history_file = env::var("HOME")
.map(|dir| format!("{}/.mol_repl_history", dir))
.ok();
let context = Arc::new(Mutex::new(context));
let mut rl = Editor::<RlHelper>::with_config(
Config::builder()
.completion_type(CompletionType::List)
.build(),
);
let mut multiline: Option<String> = Option::None;
rl.set_helper(Some(RlHelper {
context: context.clone(),
}));
if let Some(Err(err)) = history_file
.as_ref()
.map(|hisotry| rl.load_history(hisotry))
{
log::info!("No previous history: {}", err);
}
loop {
let promt = match multiline {
None => "> ",
Some(_) => " ",
};
match rl.readline(promt) {
Ok(line) => {
let line_len = line.len();
let org_line = line.clone();
let input = match multiline {
Some(prefix) => format!("{}\n{}", prefix, line),
None => line,
};
multiline = None;
if line_len == 0 {
if !input.is_empty() {
multiline = Some(input)
}
// No need to parse empty string and eval to void
continue;
}
rl.add_history_entry(org_line);
match parser::parse_string(&input) {
Ok(program) => {
match interpreter::exec_with_context(&program, &mut context.lock().unwrap())
{
Ok(value) => println!("{}", value.print(0)),
Err(throw) => println!("Uncaught {}", throw),
}
}
Err(error) => {
// If parsing error is an unexpected end of input
if error.column > line_len {
multiline = Some(input);
continue;
}
println!(" {: >1$}", "^", error.column);
println!();
println!("Syntax {}", error);
println!();
}
}
}
Err(ReadlineError::Interrupted) => break,
Err(ReadlineError::Eof) => break,
Err(err) => println!("Error: {:?}", err),
}
}
if let Some(Err(err)) = history_file
.as_ref()
.map(|hisotry| rl.save_history(&hisotry))
{
eprintln!("Failed to save history: {}", err)
}
}