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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
use std::borrow::Cow;
use ansi_term::{Colour, Style};
use rustyline::validate::{ValidationContext, ValidationResult};
use arret_syntax::datum::DataStr;
use super::command::{HELP_COMMAND, QUIT_COMMAND, TYPE_ONLY_PREFIX};
use super::syntax::{error_context_for_eol, error_for_line, MAXIMUM_PARSED_LINE_LEN};
const UNBOUND_COMPLETIONS: &[&str] = &[
TYPE_ONLY_PREFIX,
QUIT_COMMAND,
HELP_COMMAND,
"true",
"false",
"##NaN",
"##Inf",
"##-Inf",
];
pub struct ArretHelper {
all_names: Vec<DataStr>,
}
fn sorted_strings_prefixed_by<'a, T: AsRef<str>>(
haystack: &'a [T],
prefix: &'a str,
) -> impl Iterator<Item = &'a T> + 'a {
let start_pos = match haystack.binary_search_by(|needle| needle.as_ref().cmp(prefix)) {
Ok(found) => found,
Err(insert_idx) => insert_idx,
};
haystack[start_pos..]
.iter()
.take_while(move |needle| needle.as_ref().starts_with(prefix))
}
impl ArretHelper {
pub fn new(mut bound_names: Vec<DataStr>) -> ArretHelper {
bound_names.extend(UNBOUND_COMPLETIONS.iter().map(|unbound| (*unbound).into()));
bound_names.sort();
ArretHelper {
all_names: bound_names,
}
}
}
impl rustyline::completion::Completer for ArretHelper {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<String>)> {
use arret_syntax::parser::is_identifier_char;
let prefix_start = line[0..pos]
.rfind(|c| !is_identifier_char(c))
.map(|i| i + 1)
.unwrap_or(0);
let prefix = &line[prefix_start..pos];
let suffix = if line.len() > pos {
let suffix_end = line[pos..]
.find(|c| !is_identifier_char(c))
.map(|i| i + pos)
.unwrap_or_else(|| line.len());
&line[pos..suffix_end]
} else {
""
};
let is_command = prefix.starts_with('/');
let is_first_identifier = pos == prefix.len();
if is_command && !is_first_identifier {
return Ok((0, vec![]));
}
let options = sorted_strings_prefixed_by(&self.all_names, prefix)
.filter_map(|name| {
if name.ends_with(suffix) {
Some((&name[0..name.len() - suffix.len()]).to_owned())
} else {
None
}
})
.collect();
Ok((prefix_start, options))
}
}
impl rustyline::hint::Hinter for ArretHelper {
type Hint = String;
fn hint(&self, line: &str, pos: usize, _: &rustyline::Context<'_>) -> Option<String> {
use arret_syntax::error::WithinContext;
use arret_syntax::parser::is_identifier_char;
let within_context = error_context_for_eol(line);
if let Some(WithinContext::String(_)) = within_context {
return Some("\"".to_owned());
}
let last_ident_start = line
.rfind(|c| !is_identifier_char(c))
.map(|i| i + 1)
.unwrap_or(0);
let last_ident = &line[last_ident_start..];
let is_command = last_ident.starts_with('/');
let is_first_identifier = pos == last_ident.len();
if !(last_ident.is_empty() || (is_command && !is_first_identifier)) {
for name in sorted_strings_prefixed_by(&self.all_names, last_ident) {
if name.len() != last_ident.len() {
return Some(name[last_ident.len()..].to_owned());
}
}
}
within_context
.and_then(|within| within.expected_next())
.map(|en| en.close_char().to_string())
}
}
impl rustyline::highlight::Highlighter for ArretHelper {
fn highlight<'l>(&self, line: &'l str, _pos: usize) -> Cow<'l, str> {
let error_span = error_for_line(line).and_then(|error| {
if let arret_syntax::error::ErrorKind::Eof(ec) = error.kind() {
ec.open_char_span()
} else {
Some(error.span())
}
});
let error_span = if let Some(error_span) = error_span {
error_span
} else {
return line.into();
};
let error_start = error_span.start() as usize;
let error_end = error_span.end() as usize;
let prefix = &line[0..error_start];
let error = &line[error_start..error_end];
let suffix = &line[error_end..];
let error_style = Colour::Red.bold();
format!("{}{}{}", prefix, error_style.paint(error), suffix).into()
}
fn highlight_prompt<'b, 's: 'b, 'p: 'b>(
&'s self,
prompt: &'p str,
_default: bool,
) -> Cow<'b, str> {
let prompt_style = Colour::Fixed(25);
prompt_style.paint(prompt).to_string().into()
}
fn highlight_hint<'h>(&self, hint: &'h str) -> Cow<'h, str> {
use arret_syntax::parser::is_identifier_char;
if hint.chars().next().map(is_identifier_char) == Some(true) {
let name_style = Style::new().dimmed();
name_style.paint(hint).to_string().into()
} else {
let unexpected_eof_style = Colour::Red.bold();
unexpected_eof_style.paint(hint).to_string().into()
}
}
fn highlight_char(&self, line: &str, _pos: usize) -> bool {
line.len() <= MAXIMUM_PARSED_LINE_LEN
}
}
impl rustyline::validate::Validator for ArretHelper {
fn validate(
&self,
ctx: &mut ValidationContext<'_>,
) -> Result<ValidationResult, rustyline::error::ReadlineError> {
match error_context_for_eol(ctx.input()) {
Some(_) => Ok(ValidationResult::Incomplete),
None => Ok(ValidationResult::Valid(None)),
}
}
}
impl rustyline::Helper for ArretHelper {}
#[cfg(test)]
mod test {
use super::*;
fn assert_sorted_strings_prefixed_by(
expected: &[&'static str],
haystack: &[&'static str],
needle: &'static str,
) {
let expected_vec = expected.to_owned();
let actual_vec: Vec<&str> = sorted_strings_prefixed_by(haystack, needle)
.cloned()
.collect();
assert_eq!(expected_vec, actual_vec)
}
#[test]
fn sorted_strings_prefixed_by_empty() {
let haystack: &[&str] = &[];
assert_sorted_strings_prefixed_by(&[], haystack, "foo");
}
#[test]
fn sorted_strings_prefixed_by_missing_at_beginning() {
let haystack = &["zoop"];
assert_sorted_strings_prefixed_by(&[], haystack, "foo");
}
#[test]
fn sorted_strings_prefixed_by_missing_in_middle() {
let haystack = &["bar", "zoop"];
assert_sorted_strings_prefixed_by(&[], haystack, "foo");
}
#[test]
fn sorted_strings_prefixed_by_missing_at_end() {
let haystack = &["bar", "baz"];
assert_sorted_strings_prefixed_by(&[], haystack, "foo");
}
#[test]
fn sorted_strings_prefixed_by_only_self() {
let haystack = &["bar", "baz", "foo"];
assert_sorted_strings_prefixed_by(&["foo"], haystack, "foo");
}
#[test]
fn strings_prefixed_by_only_other() {
let haystack = &["bar", "baz", "foobar", "foobaz"];
assert_sorted_strings_prefixed_by(&["foobar", "foobaz"], haystack, "foo");
}
#[test]
fn strings_prefixed_by_self_and_other() {
let haystack = &["bar", "baz", "foo", "foobar", "foobaz", "zoop"];
assert_sorted_strings_prefixed_by(&["foo", "foobar", "foobaz"], haystack, "foo");
}
}