aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_ide_api
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_ide_api')
-rw-r--r--crates/ra_ide_api/Cargo.toml10
-rw-r--r--crates/ra_ide_api/src/completion/complete_dot.rs2
-rw-r--r--crates/ra_ide_api/src/completion/complete_pattern.rs2
-rw-r--r--crates/ra_ide_api/src/completion/complete_struct_literal.rs2
-rw-r--r--crates/ra_ide_api/src/db.rs2
-rw-r--r--crates/ra_ide_api/src/diagnostics.rs28
-rw-r--r--crates/ra_ide_api/src/goto_definition.rs2
-rw-r--r--crates/ra_ide_api/src/hover.rs2
-rw-r--r--crates/ra_ide_api/src/join_lines.rs581
-rw-r--r--crates/ra_ide_api/src/lib.rs56
-rw-r--r--crates/ra_ide_api/src/line_index.rs2
-rw-r--r--crates/ra_ide_api/src/matching_brace.rs45
-rw-r--r--crates/ra_ide_api/src/snapshots/tests__highlighting.snap34
-rw-r--r--crates/ra_ide_api/src/symbol_index.rs2
-rw-r--r--crates/ra_ide_api/src/syntax_highlighting.rs81
-rw-r--r--crates/ra_ide_api/src/test_utils.rs19
-rw-r--r--crates/ra_ide_api/src/typing.rs419
17 files changed, 1223 insertions, 66 deletions
diff --git a/crates/ra_ide_api/Cargo.toml b/crates/ra_ide_api/Cargo.toml
index ac8c8057b..c64226801 100644
--- a/crates/ra_ide_api/Cargo.toml
+++ b/crates/ra_ide_api/Cargo.toml
@@ -10,7 +10,7 @@ join_to_string = "0.1.3"
10log = "0.4.5" 10log = "0.4.5"
11relative-path = "0.4.0" 11relative-path = "0.4.0"
12rayon = "1.0.2" 12rayon = "1.0.2"
13fst = "0.3.1" 13fst = { version = "0.3.1", default-features = false }
14rustc-hash = "1.0" 14rustc-hash = "1.0"
15parking_lot = "0.7.0" 15parking_lot = "0.7.0"
16unicase = "2.2.0" 16unicase = "2.2.0"
@@ -23,13 +23,19 @@ ra_syntax = { path = "../ra_syntax" }
23ra_ide_api_light = { path = "../ra_ide_api_light" } 23ra_ide_api_light = { path = "../ra_ide_api_light" }
24ra_text_edit = { path = "../ra_text_edit" } 24ra_text_edit = { path = "../ra_text_edit" }
25ra_db = { path = "../ra_db" } 25ra_db = { path = "../ra_db" }
26ra_fmt = { path = "../ra_fmt" }
26hir = { path = "../ra_hir", package = "ra_hir" } 27hir = { path = "../ra_hir", package = "ra_hir" }
27test_utils = { path = "../test_utils" } 28test_utils = { path = "../test_utils" }
28ra_assists = { path = "../ra_assists" } 29ra_assists = { path = "../ra_assists" }
29 30
30[dev-dependencies] 31[dev-dependencies]
31insta = "0.7.0" 32insta = "0.7.0"
32proptest = "0.9.0" 33
34[dev-dependencies.proptest]
35version = "0.9.0"
36# Disable `fork` feature to allow compiling on webassembly
37default-features = false
38features = ["std", "bit-set", "break-dead-code"]
33 39
34[features] 40[features]
35jemalloc = [ "jemallocator", "jemalloc-ctl" ] 41jemalloc = [ "jemallocator", "jemalloc-ctl" ]
diff --git a/crates/ra_ide_api/src/completion/complete_dot.rs b/crates/ra_ide_api/src/completion/complete_dot.rs
index 31d5374ba..f54a02d1d 100644
--- a/crates/ra_ide_api/src/completion/complete_dot.rs
+++ b/crates/ra_ide_api/src/completion/complete_dot.rs
@@ -30,7 +30,7 @@ fn complete_fields(acc: &mut Completions, ctx: &CompletionContext, receiver: Ty)
30 acc.add_field(ctx, field, &a_ty.parameters); 30 acc.add_field(ctx, field, &a_ty.parameters);
31 } 31 }
32 } 32 }
33 // TODO unions 33 // FIXME unions
34 TypeCtor::Tuple => { 34 TypeCtor::Tuple => {
35 for (i, ty) in a_ty.parameters.iter().enumerate() { 35 for (i, ty) in a_ty.parameters.iter().enumerate() {
36 acc.add_pos_field(ctx, i, ty); 36 acc.add_pos_field(ctx, i, ty);
diff --git a/crates/ra_ide_api/src/completion/complete_pattern.rs b/crates/ra_ide_api/src/completion/complete_pattern.rs
index 3cf79c080..7abcd019b 100644
--- a/crates/ra_ide_api/src/completion/complete_pattern.rs
+++ b/crates/ra_ide_api/src/completion/complete_pattern.rs
@@ -5,7 +5,7 @@ pub(super) fn complete_pattern(acc: &mut Completions, ctx: &CompletionContext) {
5 if !ctx.is_pat_binding { 5 if !ctx.is_pat_binding {
6 return; 6 return;
7 } 7 }
8 // TODO: ideally, we should look at the type we are matching against and 8 // FIXME: ideally, we should look at the type we are matching against and
9 // suggest variants + auto-imports 9 // suggest variants + auto-imports
10 let names = ctx.resolver.all_names(ctx.db); 10 let names = ctx.resolver.all_names(ctx.db);
11 for (name, res) in names.into_iter() { 11 for (name, res) in names.into_iter() {
diff --git a/crates/ra_ide_api/src/completion/complete_struct_literal.rs b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
index b75526282..f58bcd03e 100644
--- a/crates/ra_ide_api/src/completion/complete_struct_literal.rs
+++ b/crates/ra_ide_api/src/completion/complete_struct_literal.rs
@@ -26,7 +26,7 @@ pub(super) fn complete_struct_literal(acc: &mut Completions, ctx: &CompletionCon
26 } 26 }
27 } 27 }
28 28
29 // TODO unions 29 // FIXME unions
30 AdtDef::Enum(_) => (), 30 AdtDef::Enum(_) => (),
31 }; 31 };
32} 32}
diff --git a/crates/ra_ide_api/src/db.rs b/crates/ra_ide_api/src/db.rs
index 00f4bdfd2..ea4255d35 100644
--- a/crates/ra_ide_api/src/db.rs
+++ b/crates/ra_ide_api/src/db.rs
@@ -15,7 +15,7 @@ use crate::{LineIndex, symbol_index::{self, SymbolsDatabase}};
15 LineIndexDatabaseStorage, 15 LineIndexDatabaseStorage,
16 symbol_index::SymbolsDatabaseStorage, 16 symbol_index::SymbolsDatabaseStorage,
17 hir::db::HirDatabaseStorage, 17 hir::db::HirDatabaseStorage,
18 hir::db::PersistentHirDatabaseStorage 18 hir::db::DefDatabaseStorage
19)] 19)]
20#[derive(Debug)] 20#[derive(Debug)]
21pub(crate) struct RootDatabase { 21pub(crate) struct RootDatabase {
diff --git a/crates/ra_ide_api/src/diagnostics.rs b/crates/ra_ide_api/src/diagnostics.rs
index 069092528..b9dc424c6 100644
--- a/crates/ra_ide_api/src/diagnostics.rs
+++ b/crates/ra_ide_api/src/diagnostics.rs
@@ -1,6 +1,5 @@
1use itertools::Itertools; 1use itertools::Itertools;
2use hir::{Problem, source_binder}; 2use hir::{Problem, source_binder};
3use ra_ide_api_light::Severity;
4use ra_db::SourceDatabase; 3use ra_db::SourceDatabase;
5use ra_syntax::{ 4use ra_syntax::{
6 Location, SourceFile, SyntaxKind, TextRange, SyntaxNode, 5 Location, SourceFile, SyntaxKind, TextRange, SyntaxNode,
@@ -11,6 +10,12 @@ use ra_text_edit::{TextEdit, TextEditBuilder};
11 10
12use crate::{Diagnostic, FileId, FileSystemEdit, SourceChange, SourceFileEdit, db::RootDatabase}; 11use crate::{Diagnostic, FileId, FileSystemEdit, SourceChange, SourceFileEdit, db::RootDatabase};
13 12
13#[derive(Debug, Copy, Clone)]
14pub enum Severity {
15 Error,
16 WeakWarning,
17}
18
14pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> { 19pub(crate) fn diagnostics(db: &RootDatabase, file_id: FileId) -> Vec<Diagnostic> {
15 let source_file = db.parse(file_id); 20 let source_file = db.parse(file_id);
16 let mut res = Vec::new(); 21 let mut res = Vec::new();
@@ -152,27 +157,6 @@ fn check_module(
152 fix: Some(fix), 157 fix: Some(fix),
153 } 158 }
154 } 159 }
155 Problem::NotDirOwner { move_to, candidate } => {
156 let move_file = FileSystemEdit::MoveFile {
157 src: file_id,
158 dst_source_root: source_root,
159 dst_path: move_to.clone(),
160 };
161 let create_file =
162 FileSystemEdit::CreateFile { source_root, path: move_to.join(candidate) };
163 let fix = SourceChange {
164 label: "move file and create module".to_string(),
165 source_file_edits: Vec::new(),
166 file_system_edits: vec![move_file, create_file],
167 cursor_position: None,
168 };
169 Diagnostic {
170 range: name_node.range(),
171 message: "can't declare module at this location".to_string(),
172 severity: Severity::Error,
173 fix: Some(fix),
174 }
175 }
176 }; 160 };
177 acc.push(diag) 161 acc.push(diag)
178 } 162 }
diff --git a/crates/ra_ide_api/src/goto_definition.rs b/crates/ra_ide_api/src/goto_definition.rs
index f94487d94..660b43cfa 100644
--- a/crates/ra_ide_api/src/goto_definition.rs
+++ b/crates/ra_ide_api/src/goto_definition.rs
@@ -117,7 +117,7 @@ pub(crate) fn reference_definition(
117 return Exact(nav); 117 return Exact(nav);
118 } 118 }
119 Some(Resolution::GenericParam(..)) => { 119 Some(Resolution::GenericParam(..)) => {
120 // TODO: go to the generic param def 120 // FIXME: go to the generic param def
121 } 121 }
122 Some(Resolution::SelfType(impl_block)) => { 122 Some(Resolution::SelfType(impl_block)) => {
123 let ty = impl_block.target_ty(db); 123 let ty = impl_block.target_ty(db);
diff --git a/crates/ra_ide_api/src/hover.rs b/crates/ra_ide_api/src/hover.rs
index f6443580d..3206e68b9 100644
--- a/crates/ra_ide_api/src/hover.rs
+++ b/crates/ra_ide_api/src/hover.rs
@@ -204,7 +204,7 @@ impl NavigationTarget {
204 /// 204 ///
205 /// e.g. `struct Name`, `enum Name`, `fn Name` 205 /// e.g. `struct Name`, `enum Name`, `fn Name`
206 fn description(&self, db: &RootDatabase) -> Option<String> { 206 fn description(&self, db: &RootDatabase) -> Option<String> {
207 // TODO: After type inference is done, add type information to improve the output 207 // FIXME: After type inference is done, add type information to improve the output
208 let node = self.node(db)?; 208 let node = self.node(db)?;
209 209
210 fn visit_ascribed_node<T>(node: &T, prefix: &str) -> Option<String> 210 fn visit_ascribed_node<T>(node: &T, prefix: &str) -> Option<String>
diff --git a/crates/ra_ide_api/src/join_lines.rs b/crates/ra_ide_api/src/join_lines.rs
new file mode 100644
index 000000000..8fb3eaa06
--- /dev/null
+++ b/crates/ra_ide_api/src/join_lines.rs
@@ -0,0 +1,581 @@
1use itertools::Itertools;
2use ra_syntax::{
3 SourceFile, TextRange, TextUnit, AstNode, SyntaxNode,
4 SyntaxKind::{self, WHITESPACE, COMMA, R_CURLY, R_PAREN, R_BRACK},
5 algo::{find_covering_node, non_trivia_sibling},
6 ast,
7 Direction,
8};
9use ra_fmt::{
10 compute_ws, extract_trivial_expression
11};
12use ra_text_edit::{TextEdit, TextEditBuilder};
13
14pub fn join_lines(file: &SourceFile, range: TextRange) -> TextEdit {
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 => return TextEditBuilder::default().finish(),
20 Some(pos) => pos,
21 };
22 TextRange::offset_len(range.start() + pos, TextUnit::of_char('\n'))
23 } else {
24 range
25 };
26
27 let node = find_covering_node(file.syntax(), range);
28 let mut edit = TextEditBuilder::default();
29 for node in node.descendants() {
30 let text = match node.leaf_text() {
31 Some(text) => text,
32 None => continue,
33 };
34 let range = match range.intersection(&node.range()) {
35 Some(range) => range,
36 None => continue,
37 } - node.range().start();
38 for (pos, _) in text[range].bytes().enumerate().filter(|&(_, b)| b == b'\n') {
39 let pos: TextUnit = (pos as u32).into();
40 let off = node.range().start() + range.start() + pos;
41 if !edit.invalidates_offset(off) {
42 remove_newline(&mut edit, node, text.as_str(), off);
43 }
44 }
45 }
46
47 edit.finish()
48}
49
50fn remove_newline(
51 edit: &mut TextEditBuilder,
52 node: &SyntaxNode,
53 node_text: &str,
54 offset: TextUnit,
55) {
56 if node.kind() != WHITESPACE || node_text.bytes().filter(|&b| b == b'\n').count() != 1 {
57 // The node is either the first or the last in the file
58 let suff = &node_text[TextRange::from_to(
59 offset - node.range().start() + TextUnit::of_char('\n'),
60 TextUnit::of_str(node_text),
61 )];
62 let spaces = suff.bytes().take_while(|&b| b == b' ').count();
63
64 edit.replace(TextRange::offset_len(offset, ((spaces + 1) as u32).into()), " ".to_string());
65 return;
66 }
67
68 // Special case that turns something like:
69 //
70 // ```
71 // my_function({<|>
72 // <some-expr>
73 // })
74 // ```
75 //
76 // into `my_function(<some-expr>)`
77 if join_single_expr_block(edit, node).is_some() {
78 return;
79 }
80 // ditto for
81 //
82 // ```
83 // use foo::{<|>
84 // bar
85 // };
86 // ```
87 if join_single_use_tree(edit, node).is_some() {
88 return;
89 }
90
91 // The node is between two other nodes
92 let prev = node.prev_sibling().unwrap();
93 let next = node.next_sibling().unwrap();
94 if is_trailing_comma(prev.kind(), next.kind()) {
95 // Removes: trailing comma, newline (incl. surrounding whitespace)
96 edit.delete(TextRange::from_to(prev.range().start(), node.range().end()));
97 } else if prev.kind() == COMMA && next.kind() == R_CURLY {
98 // Removes: comma, newline (incl. surrounding whitespace)
99 let space = if let Some(left) = prev.prev_sibling() { compute_ws(left, next) } else { " " };
100 edit.replace(
101 TextRange::from_to(prev.range().start(), node.range().end()),
102 space.to_string(),
103 );
104 } else if let (Some(_), Some(next)) = (ast::Comment::cast(prev), ast::Comment::cast(next)) {
105 // Removes: newline (incl. surrounding whitespace), start of the next comment
106 edit.delete(TextRange::from_to(
107 node.range().start(),
108 next.syntax().range().start() + TextUnit::of_str(next.prefix()),
109 ));
110 } else {
111 // Remove newline but add a computed amount of whitespace characters
112 edit.replace(node.range(), compute_ws(prev, next).to_string());
113 }
114}
115
116fn has_comma_after(node: &SyntaxNode) -> bool {
117 match non_trivia_sibling(node, Direction::Next) {
118 Some(n) => n.kind() == COMMA,
119 _ => false,
120 }
121}
122
123fn join_single_expr_block(edit: &mut TextEditBuilder, node: &SyntaxNode) -> Option<()> {
124 let block = ast::Block::cast(node.parent()?)?;
125 let block_expr = ast::BlockExpr::cast(block.syntax().parent()?)?;
126 let expr = extract_trivial_expression(block)?;
127
128 let block_range = block_expr.syntax().range();
129 let mut buf = expr.syntax().text().to_string();
130
131 // Match block needs to have a comma after the block
132 if let Some(match_arm) = block_expr.syntax().parent().and_then(ast::MatchArm::cast) {
133 if !has_comma_after(match_arm.syntax()) {
134 buf.push(',');
135 }
136 }
137
138 edit.replace(block_range, buf);
139
140 Some(())
141}
142
143fn join_single_use_tree(edit: &mut TextEditBuilder, node: &SyntaxNode) -> Option<()> {
144 let use_tree_list = ast::UseTreeList::cast(node.parent()?)?;
145 let (tree,) = use_tree_list.use_trees().collect_tuple()?;
146 edit.replace(use_tree_list.syntax().range(), tree.syntax().text().to_string());
147 Some(())
148}
149
150fn is_trailing_comma(left: SyntaxKind, right: SyntaxKind) -> bool {
151 match (left, right) {
152 (COMMA, R_PAREN) | (COMMA, R_BRACK) => true,
153 _ => false,
154 }
155}
156
157#[cfg(test)]
158mod tests {
159 use crate::test_utils::{assert_eq_text, check_action, extract_range};
160
161 use super::*;
162
163 fn check_join_lines(before: &str, after: &str) {
164 check_action(before, after, |file, offset| {
165 let range = TextRange::offset_len(offset, 0.into());
166 let res = join_lines(file, range);
167 Some(res)
168 })
169 }
170
171 #[test]
172 fn test_join_lines_comma() {
173 check_join_lines(
174 r"
175fn foo() {
176 <|>foo(1,
177 )
178}
179",
180 r"
181fn foo() {
182 <|>foo(1)
183}
184",
185 );
186 }
187
188 #[test]
189 fn test_join_lines_lambda_block() {
190 check_join_lines(
191 r"
192pub fn reparse(&self, edit: &AtomTextEdit) -> File {
193 <|>self.incremental_reparse(edit).unwrap_or_else(|| {
194 self.full_reparse(edit)
195 })
196}
197",
198 r"
199pub fn reparse(&self, edit: &AtomTextEdit) -> File {
200 <|>self.incremental_reparse(edit).unwrap_or_else(|| self.full_reparse(edit))
201}
202",
203 );
204 }
205
206 #[test]
207 fn test_join_lines_block() {
208 check_join_lines(
209 r"
210fn foo() {
211 foo(<|>{
212 92
213 })
214}",
215 r"
216fn foo() {
217 foo(<|>92)
218}",
219 );
220 }
221
222 #[test]
223 fn join_lines_adds_comma_for_block_in_match_arm() {
224 check_join_lines(
225 r"
226fn foo(e: Result<U, V>) {
227 match e {
228 Ok(u) => <|>{
229 u.foo()
230 }
231 Err(v) => v,
232 }
233}",
234 r"
235fn foo(e: Result<U, V>) {
236 match e {
237 Ok(u) => <|>u.foo(),
238 Err(v) => v,
239 }
240}",
241 );
242 }
243
244 #[test]
245 fn join_lines_keeps_comma_for_block_in_match_arm() {
246 // We already have a comma
247 check_join_lines(
248 r"
249fn foo(e: Result<U, V>) {
250 match e {
251 Ok(u) => <|>{
252 u.foo()
253 },
254 Err(v) => v,
255 }
256}",
257 r"
258fn foo(e: Result<U, V>) {
259 match e {
260 Ok(u) => <|>u.foo(),
261 Err(v) => v,
262 }
263}",
264 );
265
266 // comma with whitespace between brace and ,
267 check_join_lines(
268 r"
269fn foo(e: Result<U, V>) {
270 match e {
271 Ok(u) => <|>{
272 u.foo()
273 } ,
274 Err(v) => v,
275 }
276}",
277 r"
278fn foo(e: Result<U, V>) {
279 match e {
280 Ok(u) => <|>u.foo() ,
281 Err(v) => v,
282 }
283}",
284 );
285
286 // comma with newline between brace and ,
287 check_join_lines(
288 r"
289fn foo(e: Result<U, V>) {
290 match e {
291 Ok(u) => <|>{
292 u.foo()
293 }
294 ,
295 Err(v) => v,
296 }
297}",
298 r"
299fn foo(e: Result<U, V>) {
300 match e {
301 Ok(u) => <|>u.foo()
302 ,
303 Err(v) => v,
304 }
305}",
306 );
307 }
308
309 #[test]
310 fn join_lines_keeps_comma_with_single_arg_tuple() {
311 // A single arg tuple
312 check_join_lines(
313 r"
314fn foo() {
315 let x = (<|>{
316 4
317 },);
318}",
319 r"
320fn foo() {
321 let x = (<|>4,);
322}",
323 );
324
325 // single arg tuple with whitespace between brace and comma
326 check_join_lines(
327 r"
328fn foo() {
329 let x = (<|>{
330 4
331 } ,);
332}",
333 r"
334fn foo() {
335 let x = (<|>4 ,);
336}",
337 );
338
339 // single arg tuple with newline between brace and comma
340 check_join_lines(
341 r"
342fn foo() {
343 let x = (<|>{
344 4
345 }
346 ,);
347}",
348 r"
349fn foo() {
350 let x = (<|>4
351 ,);
352}",
353 );
354 }
355
356 #[test]
357 fn test_join_lines_use_items_left() {
358 // No space after the '{'
359 check_join_lines(
360 r"
361<|>use ra_syntax::{
362 TextUnit, TextRange,
363};",
364 r"
365<|>use ra_syntax::{TextUnit, TextRange,
366};",
367 );
368 }
369
370 #[test]
371 fn test_join_lines_use_items_right() {
372 // No space after the '}'
373 check_join_lines(
374 r"
375use ra_syntax::{
376<|> TextUnit, TextRange
377};",
378 r"
379use ra_syntax::{
380<|> TextUnit, TextRange};",
381 );
382 }
383
384 #[test]
385 fn test_join_lines_use_items_right_comma() {
386 // No space after the '}'
387 check_join_lines(
388 r"
389use ra_syntax::{
390<|> TextUnit, TextRange,
391};",
392 r"
393use ra_syntax::{
394<|> TextUnit, TextRange};",
395 );
396 }
397
398 #[test]
399 fn test_join_lines_use_tree() {
400 check_join_lines(
401 r"
402use ra_syntax::{
403 algo::<|>{
404 find_leaf_at_offset,
405 },
406 ast,
407};",
408 r"
409use ra_syntax::{
410 algo::<|>find_leaf_at_offset,
411 ast,
412};",
413 );
414 }
415
416 #[test]
417 fn test_join_lines_normal_comments() {
418 check_join_lines(
419 r"
420fn foo() {
421 // Hello<|>
422 // world!
423}
424",
425 r"
426fn foo() {
427 // Hello<|> world!
428}
429",
430 );
431 }
432
433 #[test]
434 fn test_join_lines_doc_comments() {
435 check_join_lines(
436 r"
437fn foo() {
438 /// Hello<|>
439 /// world!
440}
441",
442 r"
443fn foo() {
444 /// Hello<|> world!
445}
446",
447 );
448 }
449
450 #[test]
451 fn test_join_lines_mod_comments() {
452 check_join_lines(
453 r"
454fn foo() {
455 //! Hello<|>
456 //! world!
457}
458",
459 r"
460fn foo() {
461 //! Hello<|> world!
462}
463",
464 );
465 }
466
467 #[test]
468 fn test_join_lines_multiline_comments_1() {
469 check_join_lines(
470 r"
471fn foo() {
472 // Hello<|>
473 /* world! */
474}
475",
476 r"
477fn foo() {
478 // Hello<|> world! */
479}
480",
481 );
482 }
483
484 #[test]
485 fn test_join_lines_multiline_comments_2() {
486 check_join_lines(
487 r"
488fn foo() {
489 // The<|>
490 /* quick
491 brown
492 fox! */
493}
494",
495 r"
496fn foo() {
497 // The<|> quick
498 brown
499 fox! */
500}
501",
502 );
503 }
504
505 fn check_join_lines_sel(before: &str, after: &str) {
506 let (sel, before) = extract_range(before);
507 let file = SourceFile::parse(&before);
508 let result = join_lines(&file, sel);
509 let actual = result.apply(&before);
510 assert_eq_text!(after, &actual);
511 }
512
513 #[test]
514 fn test_join_lines_selection_fn_args() {
515 check_join_lines_sel(
516 r"
517fn foo() {
518 <|>foo(1,
519 2,
520 3,
521 <|>)
522}
523 ",
524 r"
525fn foo() {
526 foo(1, 2, 3)
527}
528 ",
529 );
530 }
531
532 #[test]
533 fn test_join_lines_selection_struct() {
534 check_join_lines_sel(
535 r"
536struct Foo <|>{
537 f: u32,
538}<|>
539 ",
540 r"
541struct Foo { f: u32 }
542 ",
543 );
544 }
545
546 #[test]
547 fn test_join_lines_selection_dot_chain() {
548 check_join_lines_sel(
549 r"
550fn foo() {
551 join(<|>type_params.type_params()
552 .filter_map(|it| it.name())
553 .map(|it| it.text())<|>)
554}",
555 r"
556fn foo() {
557 join(type_params.type_params().filter_map(|it| it.name()).map(|it| it.text()))
558}",
559 );
560 }
561
562 #[test]
563 fn test_join_lines_selection_lambda_block_body() {
564 check_join_lines_sel(
565 r"
566pub fn handle_find_matching_brace() {
567 params.offsets
568 .map(|offset| <|>{
569 world.analysis().matching_brace(&file, offset).unwrap_or(offset)
570 }<|>)
571 .collect();
572}",
573 r"
574pub fn handle_find_matching_brace() {
575 params.offsets
576 .map(|offset| world.analysis().matching_brace(&file, offset).unwrap_or(offset))
577 .collect();
578}",
579 );
580 }
581}
diff --git a/crates/ra_ide_api/src/lib.rs b/crates/ra_ide_api/src/lib.rs
index d6f63490d..99f18b6b8 100644
--- a/crates/ra_ide_api/src/lib.rs
+++ b/crates/ra_ide_api/src/lib.rs
@@ -36,9 +36,14 @@ mod syntax_tree;
36mod line_index; 36mod line_index;
37mod folding_ranges; 37mod folding_ranges;
38mod line_index_utils; 38mod line_index_utils;
39mod join_lines;
40mod typing;
41mod matching_brace;
39 42
40#[cfg(test)] 43#[cfg(test)]
41mod marks; 44mod marks;
45#[cfg(test)]
46mod test_utils;
42 47
43use std::sync::Arc; 48use std::sync::Arc;
44 49
@@ -66,10 +71,10 @@ pub use crate::{
66 line_index::{LineIndex, LineCol}, 71 line_index::{LineIndex, LineCol},
67 line_index_utils::translate_offset_with_edit, 72 line_index_utils::translate_offset_with_edit,
68 folding_ranges::{Fold, FoldKind}, 73 folding_ranges::{Fold, FoldKind},
74 syntax_highlighting::HighlightedRange,
75 diagnostics::Severity,
69}; 76};
70pub use ra_ide_api_light::{ 77pub use ra_ide_api_light::StructureNode;
71 HighlightedRange, Severity, StructureNode, LocalEdit,
72};
73pub use ra_db::{ 78pub use ra_db::{
74 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId, 79 Canceled, CrateGraph, CrateId, FileId, FilePosition, FileRange, SourceRootId,
75 Edition 80 Edition
@@ -263,7 +268,7 @@ impl Analysis {
263 /// supported). 268 /// supported).
264 pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> { 269 pub fn matching_brace(&self, position: FilePosition) -> Option<TextUnit> {
265 let file = self.db.parse(position.file_id); 270 let file = self.db.parse(position.file_id);
266 ra_ide_api_light::matching_brace(&file, position.offset) 271 matching_brace::matching_brace(&file, position.offset)
267 } 272 }
268 273
269 /// Returns a syntax tree represented as `String`, for debug purposes. 274 /// Returns a syntax tree represented as `String`, for debug purposes.
@@ -276,18 +281,22 @@ impl Analysis {
276 /// stuff like trailing commas. 281 /// stuff like trailing commas.
277 pub fn join_lines(&self, frange: FileRange) -> SourceChange { 282 pub fn join_lines(&self, frange: FileRange) -> SourceChange {
278 let file = self.db.parse(frange.file_id); 283 let file = self.db.parse(frange.file_id);
279 SourceChange::from_local_edit( 284 let file_edit = SourceFileEdit {
280 frange.file_id, 285 file_id: frange.file_id,
281 ra_ide_api_light::join_lines(&file, frange.range), 286 edit: join_lines::join_lines(&file, frange.range),
282 ) 287 };
288 SourceChange {
289 label: "join lines".to_string(),
290 source_file_edits: vec![file_edit],
291 file_system_edits: vec![],
292 cursor_position: None,
293 }
283 } 294 }
284 295
285 /// Returns an edit which should be applied when opening a new line, fixing 296 /// Returns an edit which should be applied when opening a new line, fixing
286 /// up minor stuff like continuing the comment. 297 /// up minor stuff like continuing the comment.
287 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> { 298 pub fn on_enter(&self, position: FilePosition) -> Option<SourceChange> {
288 let file = self.db.parse(position.file_id); 299 typing::on_enter(&self.db, position)
289 let edit = ra_ide_api_light::on_enter(&file, position.offset)?;
290 Some(SourceChange::from_local_edit(position.file_id, edit))
291 } 300 }
292 301
293 /// Returns an edit which should be applied after `=` was typed. Primarily, 302 /// Returns an edit which should be applied after `=` was typed. Primarily,
@@ -295,15 +304,18 @@ impl Analysis {
295 // FIXME: use a snippet completion instead of this hack here. 304 // FIXME: use a snippet completion instead of this hack here.
296 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> { 305 pub fn on_eq_typed(&self, position: FilePosition) -> Option<SourceChange> {
297 let file = self.db.parse(position.file_id); 306 let file = self.db.parse(position.file_id);
298 let edit = ra_ide_api_light::on_eq_typed(&file, position.offset)?; 307 let edit = typing::on_eq_typed(&file, position.offset)?;
299 Some(SourceChange::from_local_edit(position.file_id, edit)) 308 Some(SourceChange {
309 label: "add semicolon".to_string(),
310 source_file_edits: vec![SourceFileEdit { edit, file_id: position.file_id }],
311 file_system_edits: vec![],
312 cursor_position: None,
313 })
300 } 314 }
301 315
302 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately. 316 /// Returns an edit which should be applied when a dot ('.') is typed on a blank line, indenting the line appropriately.
303 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> { 317 pub fn on_dot_typed(&self, position: FilePosition) -> Option<SourceChange> {
304 let file = self.db.parse(position.file_id); 318 typing::on_dot_typed(&self.db, position)
305 let edit = ra_ide_api_light::on_dot_typed(&file, position.offset)?;
306 Some(SourceChange::from_local_edit(position.file_id, edit))
307 } 319 }
308 320
309 /// Returns a tree representation of symbols in the file. Useful to draw a 321 /// Returns a tree representation of symbols in the file. Useful to draw a
@@ -425,18 +437,6 @@ impl Analysis {
425 } 437 }
426} 438}
427 439
428impl SourceChange {
429 pub(crate) fn from_local_edit(file_id: FileId, edit: LocalEdit) -> SourceChange {
430 let file_edit = SourceFileEdit { file_id, edit: edit.edit };
431 SourceChange {
432 label: edit.label,
433 source_file_edits: vec![file_edit],
434 file_system_edits: vec![],
435 cursor_position: edit.cursor_position.map(|offset| FilePosition { offset, file_id }),
436 }
437 }
438}
439
440#[test] 440#[test]
441fn analysis_is_send() { 441fn analysis_is_send() {
442 fn is_send<T: Send>() {} 442 fn is_send<T: Send>() {}
diff --git a/crates/ra_ide_api/src/line_index.rs b/crates/ra_ide_api/src/line_index.rs
index bf004c33a..fd33d6767 100644
--- a/crates/ra_ide_api/src/line_index.rs
+++ b/crates/ra_ide_api/src/line_index.rs
@@ -77,7 +77,7 @@ impl LineIndex {
77 } 77 }
78 78
79 pub fn offset(&self, line_col: LineCol) -> TextUnit { 79 pub fn offset(&self, line_col: LineCol) -> TextUnit {
80 //TODO: return Result 80 //FIXME: return Result
81 let col = self.utf16_to_utf8_col(line_col.line, line_col.col_utf16); 81 let col = self.utf16_to_utf8_col(line_col.line, line_col.col_utf16);
82 self.newlines[line_col.line as usize] + col 82 self.newlines[line_col.line as usize] + col
83 } 83 }
diff --git a/crates/ra_ide_api/src/matching_brace.rs b/crates/ra_ide_api/src/matching_brace.rs
new file mode 100644
index 000000000..d1405f14f
--- /dev/null
+++ b/crates/ra_ide_api/src/matching_brace.rs
@@ -0,0 +1,45 @@
1use ra_syntax::{
2 SourceFile, TextUnit,
3 algo::find_leaf_at_offset,
4 SyntaxKind::{self, *},
5 ast::AstNode,
6};
7
8pub fn matching_brace(file: &SourceFile, offset: TextUnit) -> Option<TextUnit> {
9 const BRACES: &[SyntaxKind] =
10 &[L_CURLY, R_CURLY, L_BRACK, R_BRACK, L_PAREN, R_PAREN, L_ANGLE, R_ANGLE];
11 let (brace_node, brace_idx) = find_leaf_at_offset(file.syntax(), offset)
12 .filter_map(|node| {
13 let idx = BRACES.iter().position(|&brace| brace == node.kind())?;
14 Some((node, idx))
15 })
16 .next()?;
17 let parent = brace_node.parent()?;
18 let matching_kind = BRACES[brace_idx ^ 1];
19 let matching_node = parent.children().find(|node| node.kind() == matching_kind)?;
20 Some(matching_node.range().start())
21}
22
23#[cfg(test)]
24mod tests {
25 use test_utils::{add_cursor, assert_eq_text, extract_offset};
26
27 use super::*;
28
29 #[test]
30 fn test_matching_brace() {
31 fn do_check(before: &str, after: &str) {
32 let (pos, before) = extract_offset(before);
33 let file = SourceFile::parse(&before);
34 let new_pos = match matching_brace(&file, pos) {
35 None => pos,
36 Some(pos) => pos,
37 };
38 let actual = add_cursor(&before, new_pos);
39 assert_eq_text!(after, &actual);
40 }
41
42 do_check("struct Foo { a: i32, }<|>", "struct Foo <|>{ a: i32, }");
43 }
44
45}
diff --git a/crates/ra_ide_api/src/snapshots/tests__highlighting.snap b/crates/ra_ide_api/src/snapshots/tests__highlighting.snap
new file mode 100644
index 000000000..72029e0ed
--- /dev/null
+++ b/crates/ra_ide_api/src/snapshots/tests__highlighting.snap
@@ -0,0 +1,34 @@
1---
2created: "2019-03-23T16:20:31.394314144Z"
3creator: [email protected]
4source: crates/ra_ide_api/src/syntax_highlighting.rs
5expression: result
6---
7Ok(
8 [
9 HighlightedRange {
10 range: [1; 11),
11 tag: "comment"
12 },
13 HighlightedRange {
14 range: [12; 14),
15 tag: "keyword"
16 },
17 HighlightedRange {
18 range: [15; 19),
19 tag: "function"
20 },
21 HighlightedRange {
22 range: [29; 37),
23 tag: "macro"
24 },
25 HighlightedRange {
26 range: [38; 50),
27 tag: "string"
28 },
29 HighlightedRange {
30 range: [52; 54),
31 tag: "literal"
32 }
33 ]
34)
diff --git a/crates/ra_ide_api/src/symbol_index.rs b/crates/ra_ide_api/src/symbol_index.rs
index 23c743bef..0978d164a 100644
--- a/crates/ra_ide_api/src/symbol_index.rs
+++ b/crates/ra_ide_api/src/symbol_index.rs
@@ -68,7 +68,7 @@ fn file_symbols(db: &impl SymbolsDatabase, file_id: FileId) -> Arc<SymbolIndex>
68 68
69 let symbols = source_file_to_file_symbols(&source_file, file_id); 69 let symbols = source_file_to_file_symbols(&source_file, file_id);
70 70
71 // TODO: add macros here 71 // FIXME: add macros here
72 72
73 Arc::new(SymbolIndex::new(symbols)) 73 Arc::new(SymbolIndex::new(symbols))
74} 74}
diff --git a/crates/ra_ide_api/src/syntax_highlighting.rs b/crates/ra_ide_api/src/syntax_highlighting.rs
index fdd87bcff..a0c5e78ad 100644
--- a/crates/ra_ide_api/src/syntax_highlighting.rs
+++ b/crates/ra_ide_api/src/syntax_highlighting.rs
@@ -1,12 +1,81 @@
1use ra_syntax::AstNode; 1use rustc_hash::FxHashSet;
2
3use ra_syntax::{ast, AstNode, TextRange, Direction, SyntaxKind::*};
2use ra_db::SourceDatabase; 4use ra_db::SourceDatabase;
3 5
4use crate::{ 6use crate::{FileId, db::RootDatabase};
5 FileId, HighlightedRange, 7
6 db::RootDatabase, 8#[derive(Debug)]
7}; 9pub struct HighlightedRange {
10 pub range: TextRange,
11 pub tag: &'static str,
12}
8 13
9pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> { 14pub(crate) fn highlight(db: &RootDatabase, file_id: FileId) -> Vec<HighlightedRange> {
10 let source_file = db.parse(file_id); 15 let source_file = db.parse(file_id);
11 ra_ide_api_light::highlight(source_file.syntax()) 16
17 // Visited nodes to handle highlighting priorities
18 let mut highlighted = FxHashSet::default();
19 let mut res = Vec::new();
20 for node in source_file.syntax().descendants() {
21 if highlighted.contains(&node) {
22 continue;
23 }
24 let tag = match node.kind() {
25 COMMENT => "comment",
26 STRING | RAW_STRING | RAW_BYTE_STRING | BYTE_STRING => "string",
27 ATTR => "attribute",
28 NAME_REF => "text",
29 NAME => "function",
30 INT_NUMBER | FLOAT_NUMBER | CHAR | BYTE => "literal",
31 LIFETIME => "parameter",
32 k if k.is_keyword() => "keyword",
33 _ => {
34 if let Some(macro_call) = ast::MacroCall::cast(node) {
35 if let Some(path) = macro_call.path() {
36 if let Some(segment) = path.segment() {
37 if let Some(name_ref) = segment.name_ref() {
38 highlighted.insert(name_ref.syntax());
39 let range_start = name_ref.syntax().range().start();
40 let mut range_end = name_ref.syntax().range().end();
41 for sibling in path.syntax().siblings(Direction::Next) {
42 match sibling.kind() {
43 EXCL | IDENT => range_end = sibling.range().end(),
44 _ => (),
45 }
46 }
47 res.push(HighlightedRange {
48 range: TextRange::from_to(range_start, range_end),
49 tag: "macro",
50 })
51 }
52 }
53 }
54 }
55 continue;
56 }
57 };
58 res.push(HighlightedRange { range: node.range(), tag })
59 }
60 res
61}
62
63#[cfg(test)]
64mod tests {
65 use insta::assert_debug_snapshot_matches;
66
67 use crate::mock_analysis::single_file;
68
69 #[test]
70 fn test_highlighting() {
71 let (analysis, file_id) = single_file(
72 r#"
73// comment
74fn main() {}
75 println!("Hello, {}!", 92);
76"#,
77 );
78 let result = analysis.highlight(file_id);
79 assert_debug_snapshot_matches!("highlighting", result);
80 }
12} 81}
diff --git a/crates/ra_ide_api/src/test_utils.rs b/crates/ra_ide_api/src/test_utils.rs
new file mode 100644
index 000000000..d0bd3a1e4
--- /dev/null
+++ b/crates/ra_ide_api/src/test_utils.rs
@@ -0,0 +1,19 @@
1use ra_syntax::{SourceFile, TextUnit};
2use ra_text_edit::TextEdit;
3
4pub use test_utils::*;
5
6pub fn check_action<F: Fn(&SourceFile, TextUnit) -> Option<TextEdit>>(
7 before: &str,
8 after: &str,
9 f: F,
10) {
11 let (before_cursor_pos, before) = extract_offset(before);
12 let file = SourceFile::parse(&before);
13 let result = f(&file, before_cursor_pos).expect("code action is not applicable");
14 let actual = result.apply(&before);
15 let actual_cursor_pos =
16 result.apply_to_offset(before_cursor_pos).expect("cursor position is affected by the edit");
17 let actual = add_cursor(&actual, actual_cursor_pos);
18 assert_eq_text!(after, &actual);
19}
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}