aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api/src/typing.rs
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide_api/src/typing.rs')
-rw-r--r--crates/ra_ide_api/src/typing.rs419
1 files changed, 419 insertions, 0 deletions
diff --git a/crates/ra_ide_api/src/typing.rs b/crates/ra_ide_api/src/typing.rs
new file mode 100644
index 000000000..94b228466
--- /dev/null
+++ b/crates/ra_ide_api/src/typing.rs
@@ -0,0 +1,419 @@
1use ra_syntax::{
2 AstNode, SourceFile, SyntaxKind::*,
3 SyntaxNode, TextUnit, TextRange,
4 algo::{find_node_at_offset, find_leaf_at_offset, LeafAtOffset},
5 ast::{self, AstToken},
6};
7use ra_fmt::leading_indent;
8use ra_text_edit::{TextEdit, TextEditBuilder};
9use ra_db::{FilePosition, SourceDatabase};
10use crate::{db::RootDatabase, SourceChange, SourceFileEdit};
11
12pub(crate) fn on_enter(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
13 let file = db.parse(position.file_id);
14 let comment = find_leaf_at_offset(file.syntax(), position.offset)
15 .left_biased()
16 .and_then(ast::Comment::cast)?;
17
18 if let ast::CommentFlavor::Multiline = comment.flavor() {
19 return None;
20 }
21
22 let prefix = comment.prefix();
23 if position.offset
24 < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1)
25 {
26 return None;
27 }
28
29 let indent = node_indent(&file, comment.syntax())?;
30 let inserted = format!("\n{}{} ", indent, prefix);
31 let cursor_position = position.offset + TextUnit::of_str(&inserted);
32 let mut edit = TextEditBuilder::default();
33 edit.insert(position.offset, inserted);
34 Some(SourceChange {
35 label: "on enter".to_string(),
36 source_file_edits: vec![SourceFileEdit { edit: edit.finish(), file_id: position.file_id }],
37 file_system_edits: vec![],
38 cursor_position: Some(FilePosition { offset: cursor_position, file_id: position.file_id }),
39 })
40}
41
42fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> {
43 let ws = match find_leaf_at_offset(file.syntax(), node.range().start()) {
44 LeafAtOffset::Between(l, r) => {
45 assert!(r == node);
46 l
47 }
48 LeafAtOffset::Single(n) => {
49 assert!(n == node);
50 return Some("");
51 }
52 LeafAtOffset::None => unreachable!(),
53 };
54 if ws.kind() != WHITESPACE {
55 return None;
56 }
57 let text = ws.leaf_text().unwrap();
58 let pos = text.as_str().rfind('\n').map(|it| it + 1).unwrap_or(0);
59 Some(&text[pos..])
60}
61
62pub fn on_eq_typed(file: &SourceFile, eq_offset: TextUnit) -> Option<TextEdit> {
63 assert_eq!(file.syntax().text().char_at(eq_offset), Some('='));
64 let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), eq_offset)?;
65 if let_stmt.has_semi() {
66 return None;
67 }
68 if let Some(expr) = let_stmt.initializer() {
69 let expr_range = expr.syntax().range();
70 if expr_range.contains(eq_offset) && eq_offset != expr_range.start() {
71 return None;
72 }
73 if file.syntax().text().slice(eq_offset..expr_range.start()).contains('\n') {
74 return None;
75 }
76 } else {
77 return None;
78 }
79 let offset = let_stmt.syntax().range().end();
80 let mut edit = TextEditBuilder::default();
81 edit.insert(offset, ";".to_string());
82 Some(edit.finish())
83}
84
85pub(crate) fn on_dot_typed(db: &RootDatabase, position: FilePosition) -> Option<SourceChange> {
86 let file = db.parse(position.file_id);
87 assert_eq!(file.syntax().text().char_at(position.offset), Some('.'));
88
89 let whitespace = find_leaf_at_offset(file.syntax(), position.offset)
90 .left_biased()
91 .and_then(ast::Whitespace::cast)?;
92
93 let current_indent = {
94 let text = whitespace.text();
95 let newline = text.rfind('\n')?;
96 &text[newline + 1..]
97 };
98 let current_indent_len = TextUnit::of_str(current_indent);
99
100 // Make sure dot is a part of call chain
101 let field_expr = whitespace.syntax().parent().and_then(ast::FieldExpr::cast)?;
102 let prev_indent = leading_indent(field_expr.syntax())?;
103 let target_indent = format!(" {}", prev_indent);
104 let target_indent_len = TextUnit::of_str(&target_indent);
105 if current_indent_len == target_indent_len {
106 return None;
107 }
108 let mut edit = TextEditBuilder::default();
109 edit.replace(
110 TextRange::from_to(position.offset - current_indent_len, position.offset),
111 target_indent.into(),
112 );
113 let res = SourceChange {
114 label: "reindent dot".to_string(),
115 source_file_edits: vec![SourceFileEdit { edit: edit.finish(), file_id: position.file_id }],
116 file_system_edits: vec![],
117 cursor_position: Some(FilePosition {
118 offset: position.offset + target_indent_len - current_indent_len
119 + TextUnit::of_char('.'),
120 file_id: position.file_id,
121 }),
122 };
123 Some(res)
124}
125
126#[cfg(test)]
127mod tests {
128 use test_utils::{add_cursor, assert_eq_text, extract_offset};
129
130 use crate::mock_analysis::single_file;
131
132 use super::*;
133
134 #[test]
135 fn test_on_eq_typed() {
136 fn type_eq(before: &str, after: &str) {
137 let (offset, before) = extract_offset(before);
138 let mut edit = TextEditBuilder::default();
139 edit.insert(offset, "=".to_string());
140 let before = edit.finish().apply(&before);
141 let file = SourceFile::parse(&before);
142 if let Some(result) = on_eq_typed(&file, offset) {
143 let actual = result.apply(&before);
144 assert_eq_text!(after, &actual);
145 } else {
146 assert_eq_text!(&before, after)
147 };
148 }
149
150 // do_check(r"
151 // fn foo() {
152 // let foo =<|>
153 // }
154 // ", r"
155 // fn foo() {
156 // let foo =;
157 // }
158 // ");
159 type_eq(
160 r"
161fn foo() {
162 let foo <|> 1 + 1
163}
164",
165 r"
166fn foo() {
167 let foo = 1 + 1;
168}
169",
170 );
171 // do_check(r"
172 // fn foo() {
173 // let foo =<|>
174 // let bar = 1;
175 // }
176 // ", r"
177 // fn foo() {
178 // let foo =;
179 // let bar = 1;
180 // }
181 // ");
182 }
183
184 fn type_dot(before: &str, after: &str) {
185 let (offset, before) = extract_offset(before);
186 let mut edit = TextEditBuilder::default();
187 edit.insert(offset, ".".to_string());
188 let before = edit.finish().apply(&before);
189 let (analysis, file_id) = single_file(&before);
190 if let Some(result) = analysis.on_dot_typed(FilePosition { offset, file_id }) {
191 assert_eq!(result.source_file_edits.len(), 1);
192 let actual = result.source_file_edits[0].edit.apply(&before);
193 assert_eq_text!(after, &actual);
194 } else {
195 assert_eq_text!(&before, after)
196 };
197 }
198
199 #[test]
200 fn indents_new_chain_call() {
201 type_dot(
202 r"
203 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
204 self.child_impl(db, name)
205 <|>
206 }
207 ",
208 r"
209 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
210 self.child_impl(db, name)
211 .
212 }
213 ",
214 );
215 type_dot(
216 r"
217 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
218 self.child_impl(db, name)
219 <|>
220 }
221 ",
222 r"
223 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
224 self.child_impl(db, name)
225 .
226 }
227 ",
228 )
229 }
230
231 #[test]
232 fn indents_new_chain_call_with_semi() {
233 type_dot(
234 r"
235 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
236 self.child_impl(db, name)
237 <|>;
238 }
239 ",
240 r"
241 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
242 self.child_impl(db, name)
243 .;
244 }
245 ",
246 );
247 type_dot(
248 r"
249 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
250 self.child_impl(db, name)
251 <|>;
252 }
253 ",
254 r"
255 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
256 self.child_impl(db, name)
257 .;
258 }
259 ",
260 )
261 }
262
263 #[test]
264 fn indents_continued_chain_call() {
265 type_dot(
266 r"
267 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
268 self.child_impl(db, name)
269 .first()
270 <|>
271 }
272 ",
273 r"
274 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
275 self.child_impl(db, name)
276 .first()
277 .
278 }
279 ",
280 );
281 type_dot(
282 r"
283 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
284 self.child_impl(db, name)
285 .first()
286 <|>
287 }
288 ",
289 r"
290 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
291 self.child_impl(db, name)
292 .first()
293 .
294 }
295 ",
296 );
297 }
298
299 #[test]
300 fn indents_middle_of_chain_call() {
301 type_dot(
302 r"
303 fn source_impl() {
304 let var = enum_defvariant_list().unwrap()
305 <|>
306 .nth(92)
307 .unwrap();
308 }
309 ",
310 r"
311 fn source_impl() {
312 let var = enum_defvariant_list().unwrap()
313 .
314 .nth(92)
315 .unwrap();
316 }
317 ",
318 );
319 type_dot(
320 r"
321 fn source_impl() {
322 let var = enum_defvariant_list().unwrap()
323 <|>
324 .nth(92)
325 .unwrap();
326 }
327 ",
328 r"
329 fn source_impl() {
330 let var = enum_defvariant_list().unwrap()
331 .
332 .nth(92)
333 .unwrap();
334 }
335 ",
336 );
337 }
338
339 #[test]
340 fn dont_indent_freestanding_dot() {
341 type_dot(
342 r"
343 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
344 <|>
345 }
346 ",
347 r"
348 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
349 .
350 }
351 ",
352 );
353 type_dot(
354 r"
355 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
356 <|>
357 }
358 ",
359 r"
360 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
361 .
362 }
363 ",
364 );
365 }
366
367 #[test]
368 fn test_on_enter() {
369 fn apply_on_enter(before: &str) -> Option<String> {
370 let (offset, before) = extract_offset(before);
371 let (analysis, file_id) = single_file(&before);
372 let result = analysis.on_enter(FilePosition { offset, file_id })?;
373
374 assert_eq!(result.source_file_edits.len(), 1);
375 let actual = result.source_file_edits[0].edit.apply(&before);
376 let actual = add_cursor(&actual, result.cursor_position.unwrap().offset);
377 Some(actual)
378 }
379
380 fn do_check(before: &str, after: &str) {
381 let actual = apply_on_enter(before).unwrap();
382 assert_eq_text!(after, &actual);
383 }
384
385 fn do_check_noop(text: &str) {
386 assert!(apply_on_enter(text).is_none())
387 }
388
389 do_check(
390 r"
391/// Some docs<|>
392fn foo() {
393}
394",
395 r"
396/// Some docs
397/// <|>
398fn foo() {
399}
400",
401 );
402 do_check(
403 r"
404impl S {
405 /// Some<|> docs.
406 fn foo() {}
407}
408",
409 r"
410impl S {
411 /// Some
412 /// <|> docs.
413 fn foo() {}
414}
415",
416 );
417 do_check_noop(r"<|>//! docz");
418 }
419}