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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
|
//! Implementation of incremental re-parsing.
//!
//! We use two simple strategies for this:
//! - if the edit modifies only a single token (like changing an identifier's
//! letter), we replace only this token.
//! - otherwise, we search for the nearest `{}` block which contains the edit
//! and try to parse only this block.
use ra_parser::Reparser;
use ra_text_edit::AtomTextEdit;
use crate::{
algo,
parsing::{
lexer::{tokenize, Token},
text_token_source::TextTokenSource,
text_tree_sink::TextTreeSink,
},
syntax_node::{GreenNode, GreenToken, SyntaxElement, SyntaxNode},
SyntaxError,
SyntaxKind::*,
TextRange, TextUnit, T,
};
pub(crate) fn incremental_reparse(
node: &SyntaxNode,
edit: &AtomTextEdit,
errors: Vec<SyntaxError>,
) -> Option<(GreenNode, Vec<SyntaxError>, TextRange)> {
if let Some((green, old_range)) = reparse_token(node, &edit) {
return Some((green, merge_errors(errors, Vec::new(), old_range, edit), old_range));
}
if let Some((green, new_errors, old_range)) = reparse_block(node, &edit) {
return Some((green, merge_errors(errors, new_errors, old_range, edit), old_range));
}
None
}
fn reparse_token<'node>(
root: &'node SyntaxNode,
edit: &AtomTextEdit,
) -> Option<(GreenNode, TextRange)> {
let token = algo::find_covering_element(root, edit.delete).as_token()?.clone();
match token.kind() {
WHITESPACE | COMMENT | IDENT | STRING | RAW_STRING => {
if token.kind() == WHITESPACE || token.kind() == COMMENT {
// removing a new line may extends previous token
if token.text().to_string()[edit.delete - token.text_range().start()].contains('\n')
{
return None;
}
}
let text = get_text_after_edit(token.clone().into(), &edit);
let lex_tokens = tokenize(&text);
let lex_token = match lex_tokens[..] {
[lex_token] if lex_token.kind == token.kind() => lex_token,
_ => return None,
};
if lex_token.kind == IDENT && is_contextual_kw(&text) {
return None;
}
if let Some(next_char) = root.text().char_at(token.text_range().end()) {
let tokens_with_next_char = tokenize(&format!("{}{}", text, next_char));
if tokens_with_next_char.len() == 1 {
return None;
}
}
let new_token = GreenToken::new(rowan::SyntaxKind(token.kind().into()), text.into());
Some((token.replace_with(new_token), token.text_range()))
}
_ => None,
}
}
fn reparse_block<'node>(
root: &'node SyntaxNode,
edit: &AtomTextEdit,
) -> Option<(GreenNode, Vec<SyntaxError>, TextRange)> {
let (node, reparser) = find_reparsable_node(root, edit.delete)?;
let text = get_text_after_edit(node.clone().into(), &edit);
let tokens = tokenize(&text);
if !is_balanced(&tokens) {
return None;
}
let mut token_source = TextTokenSource::new(&text, &tokens);
let mut tree_sink = TextTreeSink::new(&text, &tokens);
reparser.parse(&mut token_source, &mut tree_sink);
let (green, new_errors) = tree_sink.finish();
Some((node.replace_with(green), new_errors, node.text_range()))
}
fn get_text_after_edit(element: SyntaxElement, edit: &AtomTextEdit) -> String {
let edit =
AtomTextEdit::replace(edit.delete - element.text_range().start(), edit.insert.clone());
let text = match element {
SyntaxElement::Token(token) => token.text().to_string(),
SyntaxElement::Node(node) => node.text().to_string(),
};
edit.apply(text)
}
fn is_contextual_kw(text: &str) -> bool {
match text {
"auto" | "default" | "union" => true,
_ => false,
}
}
fn find_reparsable_node(node: &SyntaxNode, range: TextRange) -> Option<(SyntaxNode, Reparser)> {
let node = algo::find_covering_element(node, range);
let mut ancestors = match node {
SyntaxElement::Token(it) => it.parent().ancestors(),
SyntaxElement::Node(it) => it.ancestors(),
};
ancestors.find_map(|node| {
let first_child = node.first_child_or_token().map(|it| it.kind());
let parent = node.parent().map(|it| it.kind());
Reparser::for_node(node.kind(), first_child, parent).map(|r| (node, r))
})
}
fn is_balanced(tokens: &[Token]) -> bool {
if tokens.is_empty()
|| tokens.first().unwrap().kind != T!['{']
|| tokens.last().unwrap().kind != T!['}']
{
return false;
}
let mut balance = 0usize;
for t in &tokens[1..tokens.len() - 1] {
match t.kind {
T!['{'] => balance += 1,
T!['}'] => {
balance = match balance.checked_sub(1) {
Some(b) => b,
None => return false,
}
}
_ => (),
}
}
balance == 0
}
fn merge_errors(
old_errors: Vec<SyntaxError>,
new_errors: Vec<SyntaxError>,
old_range: TextRange,
edit: &AtomTextEdit,
) -> Vec<SyntaxError> {
let mut res = Vec::new();
for e in old_errors {
if e.offset() <= old_range.start() {
res.push(e)
} else if e.offset() >= old_range.end() {
res.push(e.add_offset(TextUnit::of_str(&edit.insert), edit.delete.len()));
}
}
for e in new_errors {
res.push(e.add_offset(old_range.start(), 0.into()));
}
res
}
#[cfg(test)]
mod tests {
use test_utils::{assert_eq_text, extract_range};
use super::*;
use crate::{AstNode, Parse, SourceFile};
fn do_check(before: &str, replace_with: &str, reparsed_len: u32) {
let (range, before) = extract_range(before);
let edit = AtomTextEdit::replace(range, replace_with.to_owned());
let after = edit.apply(before.clone());
let fully_reparsed = SourceFile::parse(&after);
let incrementally_reparsed: Parse<SourceFile> = {
let f = SourceFile::parse(&before);
let edit = AtomTextEdit { delete: range, insert: replace_with.to_string() };
let (green, new_errors, range) =
incremental_reparse(f.tree().syntax(), &edit, f.errors.to_vec()).unwrap();
assert_eq!(range.len(), reparsed_len.into(), "reparsed fragment has wrong length");
Parse::new(green, new_errors)
};
assert_eq_text!(
&format!("{:#?}", fully_reparsed.tree().syntax()),
&format!("{:#?}", incrementally_reparsed.tree().syntax()),
);
}
#[test] // FIXME: some test here actually test token reparsing
fn reparse_block_tests() {
do_check(
r"
fn foo() {
let x = foo + <|>bar<|>
}
",
"baz",
3,
);
do_check(
r"
fn foo() {
let x = foo<|> + bar<|>
}
",
"baz",
25,
);
do_check(
r"
struct Foo {
f: foo<|><|>
}
",
",\n g: (),",
14,
);
do_check(
r"
fn foo {
let;
1 + 1;
<|>92<|>;
}
",
"62",
31, // FIXME: reparse only int literal here
);
do_check(
r"
mod foo {
fn <|><|>
}
",
"bar",
11,
);
do_check(
r"
trait Foo {
type <|>Foo<|>;
}
",
"Output",
3,
);
do_check(
r"
impl IntoIterator<Item=i32> for Foo {
f<|><|>
}
",
"n next(",
9,
);
do_check(r"use a::b::{foo,<|>,bar<|>};", "baz", 10);
do_check(
r"
pub enum A {
Foo<|><|>
}
",
"\nBar;\n",
11,
);
do_check(
r"
foo!{a, b<|><|> d}
",
", c[3]",
8,
);
do_check(
r"
fn foo() {
vec![<|><|>]
}
",
"123",
14,
);
do_check(
r"
extern {
fn<|>;<|>
}
",
" exit(code: c_int)",
11,
);
}
#[test]
fn reparse_token_tests() {
do_check(
r"<|><|>
fn foo() -> i32 { 1 }
",
"\n\n\n \n",
1,
);
do_check(
r"
fn foo() -> <|><|> {}
",
" \n",
2,
);
do_check(
r"
fn <|>foo<|>() -> i32 { 1 }
",
"bar",
3,
);
do_check(
r"
fn foo<|><|>foo() { }
",
"bar",
6,
);
do_check(
r"
fn foo /* <|><|> */ () {}
",
"some comment",
6,
);
do_check(
r"
fn baz <|><|> () {}
",
" \t\t\n\n",
2,
);
do_check(
r"
fn baz <|><|> () {}
",
" \t\t\n\n",
2,
);
do_check(
r"
/// foo <|><|>omment
mod { }
",
"c",
14,
);
do_check(
r#"
fn -> &str { "Hello<|><|>" }
"#,
", world",
7,
);
do_check(
r#"
fn -> &str { // "Hello<|><|>"
"#,
", world",
10,
);
do_check(
r##"
fn -> &str { r#"Hello<|><|>"#
"##,
", world",
10,
);
do_check(
r"
#[derive(<|>Copy<|>)]
enum Foo {
}
",
"Clone",
4,
);
}
}
|