aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api_light/src/typing.rs
diff options
context:
space:
mode:
authorAleksey Kladov <[email protected]>2019-01-08 19:17:36 +0000
committerAleksey Kladov <[email protected]>2019-01-08 19:17:36 +0000
commit1967884d6836219ee78a754ca5c66ac781351559 (patch)
tree7594f37cd0a5200eb097b9d472c61f0223d01d05 /crates/ra_ide_api_light/src/typing.rs
parent4f4f7933b1b7ff34f8633b1686b18b2d1b994c47 (diff)
rename ra_editor -> ra_ide_api_light
Diffstat (limited to 'crates/ra_ide_api_light/src/typing.rs')
-rw-r--r--crates/ra_ide_api_light/src/typing.rs826
1 files changed, 826 insertions, 0 deletions
diff --git a/crates/ra_ide_api_light/src/typing.rs b/crates/ra_ide_api_light/src/typing.rs
new file mode 100644
index 000000000..d8177f245
--- /dev/null
+++ b/crates/ra_ide_api_light/src/typing.rs
@@ -0,0 +1,826 @@
1use std::mem;
2
3use itertools::Itertools;
4use ra_syntax::{
5 algo::{find_node_at_offset, find_covering_node, find_leaf_at_offset, LeafAtOffset},
6 ast,
7 AstNode, Direction, SourceFile, SyntaxKind,
8 SyntaxKind::*,
9 SyntaxNode, TextRange, TextUnit,
10};
11
12use crate::{LocalEdit, TextEditBuilder};
13
14pub fn join_lines(file: &SourceFile, range: TextRange) -> LocalEdit {
15 let range = if range.is_empty() {
16 let syntax = file.syntax();
17 let text = syntax.text().slice(range.start()..);
18 let pos = match text.find('\n') {
19 None => {
20 return LocalEdit {
21 label: "join lines".to_string(),
22 edit: TextEditBuilder::default().finish(),
23 cursor_position: None,
24 };
25 }
26 Some(pos) => pos,
27 };
28 TextRange::offset_len(range.start() + pos, TextUnit::of_char('\n'))
29 } else {
30 range
31 };
32
33 let node = find_covering_node(file.syntax(), range);
34 let mut edit = TextEditBuilder::default();
35 for node in node.descendants() {
36 let text = match node.leaf_text() {
37 Some(text) => text,
38 None => continue,
39 };
40 let range = match range.intersection(&node.range()) {
41 Some(range) => range,
42 None => continue,
43 } - node.range().start();
44 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
45 let pos: TextUnit = (pos as u32).into();
46 let off = node.range().start() + range.start() + pos;
47 if !edit.invalidates_offset(off) {
48 remove_newline(&mut edit, node, text.as_str(), off);
49 }
50 }
51 }
52
53 LocalEdit {
54 label: "join lines".to_string(),
55 edit: edit.finish(),
56 cursor_position: None,
57 }
58}
59
60pub fn on_enter(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> {
61 let comment = find_leaf_at_offset(file.syntax(), offset)
62 .left_biased()
63 .and_then(ast::Comment::cast)?;
64
65 if let ast::CommentFlavor::Multiline = comment.flavor() {
66 return None;
67 }
68
69 let prefix = comment.prefix();
70 if offset < comment.syntax().range().start() + TextUnit::of_str(prefix) + TextUnit::from(1) {
71 return None;
72 }
73
74 let indent = node_indent(file, comment.syntax())?;
75 let inserted = format!("\n{}{} ", indent, prefix);
76 let cursor_position = offset + TextUnit::of_str(&inserted);
77 let mut edit = TextEditBuilder::default();
78 edit.insert(offset, inserted);
79 Some(LocalEdit {
80 label: "on enter".to_string(),
81 edit: edit.finish(),
82 cursor_position: Some(cursor_position),
83 })
84}
85
86fn node_indent<'a>(file: &'a SourceFile, node: &SyntaxNode) -> Option<&'a str> {
87 let ws = match find_leaf_at_offset(file.syntax(), node.range().start()) {
88 LeafAtOffset::Between(l, r) => {
89 assert!(r == node);
90 l
91 }
92 LeafAtOffset::Single(n) => {
93 assert!(n == node);
94 return Some("");
95 }
96 LeafAtOffset::None => unreachable!(),
97 };
98 if ws.kind() != WHITESPACE {
99 return None;
100 }
101 let text = ws.leaf_text().unwrap();
102 let pos = text.as_str().rfind('\n').map(|it| it + 1).unwrap_or(0);
103 Some(&text[pos..])
104}
105
106pub fn on_eq_typed(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> {
107 let let_stmt: &ast::LetStmt = find_node_at_offset(file.syntax(), offset)?;
108 if let_stmt.has_semi() {
109 return None;
110 }
111 if let Some(expr) = let_stmt.initializer() {
112 let expr_range = expr.syntax().range();
113 if expr_range.contains(offset) && offset != expr_range.start() {
114 return None;
115 }
116 if file
117 .syntax()
118 .text()
119 .slice(offset..expr_range.start())
120 .contains('\n')
121 {
122 return None;
123 }
124 } else {
125 return None;
126 }
127 let offset = let_stmt.syntax().range().end();
128 let mut edit = TextEditBuilder::default();
129 edit.insert(offset, ";".to_string());
130 Some(LocalEdit {
131 label: "add semicolon".to_string(),
132 edit: edit.finish(),
133 cursor_position: None,
134 })
135}
136
137pub fn on_dot_typed(file: &SourceFile, offset: TextUnit) -> Option<LocalEdit> {
138 let before_dot_offset = offset - TextUnit::of_char('.');
139
140 let whitespace = find_leaf_at_offset(file.syntax(), before_dot_offset).left_biased()?;
141
142 // find whitespace just left of the dot
143 ast::Whitespace::cast(whitespace)?;
144
145 // make sure there is a method call
146 let method_call = whitespace
147 .siblings(Direction::Prev)
148 // first is whitespace
149 .skip(1)
150 .next()?;
151
152 ast::MethodCallExpr::cast(method_call)?;
153
154 // find how much the _method call is indented
155 let method_chain_indent = method_call
156 .parent()?
157 .siblings(Direction::Prev)
158 .skip(1)
159 .next()?
160 .leaf_text()
161 .map(|x| last_line_indent_in_whitespace(x))?;
162
163 let current_indent = TextUnit::of_str(last_line_indent_in_whitespace(whitespace.leaf_text()?));
164 // TODO: indent is always 4 spaces now. A better heuristic could look on the previous line(s)
165
166 let target_indent = TextUnit::of_str(method_chain_indent) + TextUnit::from_usize(4);
167
168 let diff = target_indent - current_indent;
169
170 let indent = "".repeat(diff.to_usize());
171
172 let cursor_position = offset + diff;
173 let mut edit = TextEditBuilder::default();
174 edit.insert(before_dot_offset, indent);
175 Some(LocalEdit {
176 label: "indent dot".to_string(),
177 edit: edit.finish(),
178 cursor_position: Some(cursor_position),
179 })
180}
181
182/// Finds the last line in the whitespace
183fn last_line_indent_in_whitespace(ws: &str) -> &str {
184 ws.split('\n').last().unwrap_or("")
185}
186
187fn remove_newline(
188 edit: &mut TextEditBuilder,
189 node: &SyntaxNode,
190 node_text: &str,
191 offset: TextUnit,
192) {
193 if node.kind() != WHITESPACE || node_text.bytes().filter(|&b| b == b'\n').count() != 1 {
194 // The node is either the first or the last in the file
195 let suff = &node_text[TextRange::from_to(
196 offset - node.range().start() + TextUnit::of_char('\n'),
197 TextUnit::of_str(node_text),
198 )];
199 let spaces = suff.bytes().take_while(|&b| b == b' ').count();
200
201 edit.replace(
202 TextRange::offset_len(offset, ((spaces + 1) as u32).into()),
203 " ".to_string(),
204 );
205 return;
206 }
207
208 // Special case that turns something like:
209 //
210 // ```
211 // my_function({<|>
212 // <some-expr>
213 // })
214 // ```
215 //
216 // into `my_function(<some-expr>)`
217 if join_single_expr_block(edit, node).is_some() {
218 return;
219 }
220 // ditto for
221 //
222 // ```
223 // use foo::{<|>
224 // bar
225 // };
226 // ```
227 if join_single_use_tree(edit, node).is_some() {
228 return;
229 }
230
231 // The node is between two other nodes
232 let prev = node.prev_sibling().unwrap();
233 let next = node.next_sibling().unwrap();
234 if is_trailing_comma(prev.kind(), next.kind()) {
235 // Removes: trailing comma, newline (incl. surrounding whitespace)
236 edit.delete(TextRange::from_to(prev.range().start(), node.range().end()));
237 } else if prev.kind() == COMMA && next.kind() == R_CURLY {
238 // Removes: comma, newline (incl. surrounding whitespace)
239 let space = if let Some(left) = prev.prev_sibling() {
240 compute_ws(left, next)
241 } else {
242 " "
243 };
244 edit.replace(
245 TextRange::from_to(prev.range().start(), node.range().end()),
246 space.to_string(),
247 );
248 } else if let (Some(_), Some(next)) = (ast::Comment::cast(prev), ast::Comment::cast(next)) {
249 // Removes: newline (incl. surrounding whitespace), start of the next comment
250 edit.delete(TextRange::from_to(
251 node.range().start(),
252 next.syntax().range().start() + TextUnit::of_str(next.prefix()),
253 ));
254 } else {
255 // Remove newline but add a computed amount of whitespace characters
256 edit.replace(node.range(), compute_ws(prev, next).to_string());
257 }
258}
259
260fn is_trailing_comma(left: SyntaxKind, right: SyntaxKind) -> bool {
261 match (left, right) {
262 (COMMA, R_PAREN) | (COMMA, R_BRACK) => true,
263 _ => false,
264 }
265}
266
267fn join_single_expr_block(edit: &mut TextEditBuilder, node: &SyntaxNode) -> Option<()> {
268 let block = ast::Block::cast(node.parent()?)?;
269 let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?;
270 let expr = single_expr(block)?;
271 edit.replace(
272 block_expr.syntax().range(),
273 expr.syntax().text().to_string(),
274 );
275 Some(())
276}
277
278fn single_expr(block: &ast::Block) -> Option<&ast::Expr> {
279 let mut res = None;
280 for child in block.syntax().children() {
281 if let Some(expr) = ast::Expr::cast(child) {
282 if expr.syntax().text().contains('\n') {
283 return None;
284 }
285 if mem::replace(&mut res, Some(expr)).is_some() {
286 return None;
287 }
288 } else {
289 match child.kind() {
290 WHITESPACE | L_CURLY | R_CURLY => (),
291 _ => return None,
292 }
293 }
294 }
295 res
296}
297
298fn join_single_use_tree(edit: &mut TextEditBuilder, node: &SyntaxNode) -> Option<()> {
299 let use_tree_list = ast::UseTreeList::cast(node.parent()?)?;
300 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
301 edit.replace(
302 use_tree_list.syntax().range(),
303 tree.syntax().text().to_string(),
304 );
305 Some(())
306}
307
308fn compute_ws(left: &SyntaxNode, right: &SyntaxNode) -> &'static str {
309 match left.kind() {
310 L_PAREN | L_BRACK => return "",
311 L_CURLY => {
312 if let USE_TREE = right.kind() {
313 return "";
314 }
315 }
316 _ => (),
317 }
318 match right.kind() {
319 R_PAREN | R_BRACK => return "",
320 R_CURLY => {
321 if let USE_TREE = left.kind() {
322 return "";
323 }
324 }
325 DOT => return "",
326 _ => (),
327 }
328 " "
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334 use crate::test_utils::{
335 add_cursor, assert_eq_text, check_action, extract_offset, extract_range,
336};
337
338 fn check_join_lines(before: &str, after: &str) {
339 check_action(before, after, |file, offset| {
340 let range = TextRange::offset_len(offset, 0.into());
341 let res = join_lines(file, range);
342 Some(res)
343 })
344 }
345
346 #[test]
347 fn test_join_lines_comma() {
348 check_join_lines(
349 r"
350fn foo() {
351 <|>foo(1,
352 )
353}
354",
355 r"
356fn foo() {
357 <|>foo(1)
358}
359",
360 );
361 }
362
363 #[test]
364 fn test_join_lines_lambda_block() {
365 check_join_lines(
366 r"
367pub fn reparse(&self, edit: &AtomTextEdit) -> File {
368 <|>self.incremental_reparse(edit).unwrap_or_else(|| {
369 self.full_reparse(edit)
370 })
371}
372",
373 r"
374pub fn reparse(&self, edit: &AtomTextEdit) -> File {
375 <|>self.incremental_reparse(edit).unwrap_or_else(|| self.full_reparse(edit))
376}
377",
378 );
379 }
380
381 #[test]
382 fn test_join_lines_block() {
383 check_join_lines(
384 r"
385fn foo() {
386 foo(<|>{
387 92
388 })
389}",
390 r"
391fn foo() {
392 foo(<|>92)
393}",
394 );
395 }
396
397 #[test]
398 fn test_join_lines_use_items_left() {
399 // No space after the '{'
400 check_join_lines(
401 r"
402<|>use ra_syntax::{
403 TextUnit, TextRange,
404};",
405 r"
406<|>use ra_syntax::{TextUnit, TextRange,
407};",
408 );
409 }
410
411 #[test]
412 fn test_join_lines_use_items_right() {
413 // No space after the '}'
414 check_join_lines(
415 r"
416use ra_syntax::{
417<|> TextUnit, TextRange
418};",
419 r"
420use ra_syntax::{
421<|> TextUnit, TextRange};",
422 );
423 }
424
425 #[test]
426 fn test_join_lines_use_items_right_comma() {
427 // No space after the '}'
428 check_join_lines(
429 r"
430use ra_syntax::{
431<|> TextUnit, TextRange,
432};",
433 r"
434use ra_syntax::{
435<|> TextUnit, TextRange};",
436 );
437 }
438
439 #[test]
440 fn test_join_lines_use_tree() {
441 check_join_lines(
442 r"
443use ra_syntax::{
444 algo::<|>{
445 find_leaf_at_offset,
446 },
447 ast,
448};",
449 r"
450use ra_syntax::{
451 algo::<|>find_leaf_at_offset,
452 ast,
453};",
454 );
455 }
456
457 #[test]
458 fn test_join_lines_normal_comments() {
459 check_join_lines(
460 r"
461fn foo() {
462 // Hello<|>
463 // world!
464}
465",
466 r"
467fn foo() {
468 // Hello<|> world!
469}
470",
471 );
472 }
473
474 #[test]
475 fn test_join_lines_doc_comments() {
476 check_join_lines(
477 r"
478fn foo() {
479 /// Hello<|>
480 /// world!
481}
482",
483 r"
484fn foo() {
485 /// Hello<|> world!
486}
487",
488 );
489 }
490
491 #[test]
492 fn test_join_lines_mod_comments() {
493 check_join_lines(
494 r"
495fn foo() {
496 //! Hello<|>
497 //! world!
498}
499",
500 r"
501fn foo() {
502 //! Hello<|> world!
503}
504",
505 );
506 }
507
508 #[test]
509 fn test_join_lines_multiline_comments_1() {
510 check_join_lines(
511 r"
512fn foo() {
513 // Hello<|>
514 /* world! */
515}
516",
517 r"
518fn foo() {
519 // Hello<|> world! */
520}
521",
522 );
523 }
524
525 #[test]
526 fn test_join_lines_multiline_comments_2() {
527 check_join_lines(
528 r"
529fn foo() {
530 // The<|>
531 /* quick
532 brown
533 fox! */
534}
535",
536 r"
537fn foo() {
538 // The<|> quick
539 brown
540 fox! */
541}
542",
543 );
544 }
545
546 fn check_join_lines_sel(before: &str, after: &str) {
547 let (sel, before) = extract_range(before);
548 let file = SourceFile::parse(&before);
549 let result = join_lines(&file, sel);
550 let actual = result.edit.apply(&before);
551 assert_eq_text!(after, &actual);
552 }
553
554 #[test]
555 fn test_join_lines_selection_fn_args() {
556 check_join_lines_sel(
557 r"
558fn foo() {
559 <|>foo(1,
560 2,
561 3,
562 <|>)
563}
564 ",
565 r"
566fn foo() {
567 foo(1, 2, 3)
568}
569 ",
570 );
571 }
572
573 #[test]
574 fn test_join_lines_selection_struct() {
575 check_join_lines_sel(
576 r"
577struct Foo <|>{
578 f: u32,
579}<|>
580 ",
581 r"
582struct Foo { f: u32 }
583 ",
584 );
585 }
586
587 #[test]
588 fn test_join_lines_selection_dot_chain() {
589 check_join_lines_sel(
590 r"
591fn foo() {
592 join(<|>type_params.type_params()
593 .filter_map(|it| it.name())
594 .map(|it| it.text())<|>)
595}",
596 r"
597fn foo() {
598 join(type_params.type_params().filter_map(|it| it.name()).map(|it| it.text()))
599}",
600 );
601 }
602
603 #[test]
604 fn test_join_lines_selection_lambda_block_body() {
605 check_join_lines_sel(
606 r"
607pub fn handle_find_matching_brace() {
608 params.offsets
609 .map(|offset| <|>{
610 world.analysis().matching_brace(&file, offset).unwrap_or(offset)
611 }<|>)
612 .collect();
613}",
614 r"
615pub fn handle_find_matching_brace() {
616 params.offsets
617 .map(|offset| world.analysis().matching_brace(&file, offset).unwrap_or(offset))
618 .collect();
619}",
620 );
621 }
622
623 #[test]
624 fn test_on_eq_typed() {
625 fn do_check(before: &str, after: &str) {
626 let (offset, before) = extract_offset(before);
627 let file = SourceFile::parse(&before);
628 let result = on_eq_typed(&file, offset).unwrap();
629 let actual = result.edit.apply(&before);
630 assert_eq_text!(after, &actual);
631 }
632
633 // do_check(r"
634 // fn foo() {
635 // let foo =<|>
636 // }
637 // ", r"
638 // fn foo() {
639 // let foo =;
640 // }
641 // ");
642 do_check(
643 r"
644fn foo() {
645 let foo =<|> 1 + 1
646}
647",
648 r"
649fn foo() {
650 let foo = 1 + 1;
651}
652",
653 );
654 // do_check(r"
655 // fn foo() {
656 // let foo =<|>
657 // let bar = 1;
658 // }
659 // ", r"
660 // fn foo() {
661 // let foo =;
662 // let bar = 1;
663 // }
664 // ");
665 }
666
667 #[test]
668 fn test_on_dot_typed() {
669 fn do_check(before: &str, after: &str) {
670 let (offset, before) = extract_offset(before);
671 let file = SourceFile::parse(&before);
672 if let Some(result) = on_eq_typed(&file, offset) {
673 let actual = result.edit.apply(&before);
674 assert_eq_text!(after, &actual);
675 };
676 }
677 // indent if continuing chain call
678 do_check(
679 r"
680 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
681 self.child_impl(db, name)
682 .<|>
683 }
684",
685 r"
686 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
687 self.child_impl(db, name)
688 .
689 }
690",
691 );
692
693 // do not indent if already indented
694 do_check(
695 r"
696 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
697 self.child_impl(db, name)
698 .<|>
699 }
700",
701 r"
702 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
703 self.child_impl(db, name)
704 .
705 }
706",
707 );
708
709 // indent if the previous line is already indented
710 do_check(
711 r"
712 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
713 self.child_impl(db, name)
714 .first()
715 .<|>
716 }
717",
718 r"
719 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
720 self.child_impl(db, name)
721 .first()
722 .
723 }
724",
725 );
726
727 // don't indent if indent matches previous line
728 do_check(
729 r"
730 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
731 self.child_impl(db, name)
732 .first()
733 .<|>
734 }
735",
736 r"
737 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
738 self.child_impl(db, name)
739 .first()
740 .
741 }
742",
743 );
744
745 // don't indent if there is no method call on previous line
746 do_check(
747 r"
748 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
749 .<|>
750 }
751",
752 r"
753 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
754 .
755 }
756",
757 );
758
759 // indent to match previous expr
760 do_check(
761 r"
762 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
763 self.child_impl(db, name)
764.<|>
765 }
766",
767 r"
768 pub fn child(&self, db: &impl HirDatabase, name: &Name) -> Cancelable<Option<Module>> {
769 self.child_impl(db, name)
770 .
771 }
772",
773 );
774 }
775
776 #[test]
777 fn test_on_enter() {
778 fn apply_on_enter(before: &str) -> Option<String> {
779 let (offset, before) = extract_offset(before);
780 let file = SourceFile::parse(&before);
781 let result = on_enter(&file, offset)?;
782 let actual = result.edit.apply(&before);
783 let actual = add_cursor(&actual, result.cursor_position.unwrap());
784 Some(actual)
785 }
786
787 fn do_check(before: &str, after: &str) {
788 let actual = apply_on_enter(before).unwrap();
789 assert_eq_text!(after, &actual);
790 }
791
792 fn do_check_noop(text: &str) {
793 assert!(apply_on_enter(text).is_none())
794 }
795
796 do_check(
797 r"
798/// Some docs<|>
799fn foo() {
800}
801",
802 r"
803/// Some docs
804/// <|>
805fn foo() {
806}
807",
808 );
809 do_check(
810 r"
811impl S {
812 /// Some<|> docs.
813 fn foo() {}
814}
815",
816 r"
817impl S {
818 /// Some
819 /// <|> docs.
820 fn foo() {}
821}
822",
823 );
824 do_check_noop(r"<|>//! docz");
825 }
826}