]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/patterns.rs
Don't complete visibility accessors after existing ones
[rust.git] / crates / ide_completion / src / patterns.rs
1 //! Patterns telling us certain facts about current syntax element, they are used in completion context
2
3 use hir::Semantics;
4 use ide_db::RootDatabase;
5 use syntax::{
6     algo::non_trivia_sibling,
7     ast::{self, ArgListOwner, LoopBodyOwner},
8     match_ast, AstNode, Direction, SyntaxElement,
9     SyntaxKind::*,
10     SyntaxNode, SyntaxToken, TextRange, TextSize, T,
11 };
12
13 #[cfg(test)]
14 use crate::test_utils::{check_pattern_is_applicable, check_pattern_is_not_applicable};
15
16 /// Immediate previous node to what we are completing.
17 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
18 pub(crate) enum ImmediatePrevSibling {
19     IfExpr,
20     TraitDefName,
21     ImplDefType,
22     Visibility,
23 }
24
25 /// Direct parent "thing" of what we are currently completing.
26 #[derive(Clone, Debug, PartialEq, Eq)]
27 pub(crate) enum ImmediateLocation {
28     Use,
29     Impl,
30     Trait,
31     RecordField,
32     RefExpr,
33     IdentPat,
34     BlockExpr,
35     ItemList,
36     // Fake file ast node
37     Attribute(ast::Attr),
38     // Fake file ast node
39     ModDeclaration(ast::Module),
40     // Original file ast node
41     MethodCall {
42         receiver: Option<ast::Expr>,
43         has_parens: bool,
44     },
45     // Original file ast node
46     FieldAccess {
47         receiver: Option<ast::Expr>,
48         receiver_is_ambiguous_float_literal: bool,
49     },
50     // Original file ast node
51     // Only set from a type arg
52     GenericArgList(ast::GenericArgList),
53     // Original file ast node
54     /// The record expr of the field name we are completing
55     RecordExpr(ast::RecordExpr),
56     // Original file ast node
57     /// The record pat of the field name we are completing
58     RecordPat(ast::RecordPat),
59 }
60
61 pub(crate) fn determine_prev_sibling(name_like: &ast::NameLike) -> Option<ImmediatePrevSibling> {
62     let node = match name_like {
63         ast::NameLike::NameRef(name_ref) => maximize_name_ref(name_ref),
64         ast::NameLike::Name(n) => n.syntax().clone(),
65         ast::NameLike::Lifetime(lt) => lt.syntax().clone(),
66     };
67     let node = match node.parent().and_then(ast::MacroCall::cast) {
68         // When a path is being typed after the name of a trait/type of an impl it is being
69         // parsed as a macro, so when the trait/impl has a block following it an we are between the
70         // name and block the macro will attach the block to itself so maximizing fails to take
71         // that into account
72         // FIXME path expr and statement have a similar problem with attrs
73         Some(call)
74             if call.excl_token().is_none()
75                 && call.token_tree().map_or(false, |t| t.l_curly_token().is_some())
76                 && call.semicolon_token().is_none() =>
77         {
78             call.syntax().clone()
79         }
80         _ => node,
81     };
82     let prev_sibling = non_trivia_sibling(node.into(), Direction::Prev)?.into_node()?;
83     if prev_sibling.kind() == ERROR {
84         let prev_sibling = prev_sibling.first_child()?;
85         let res = match_ast! {
86             match prev_sibling {
87                 // vis followed by random ident will always error the parser
88                 ast::Visibility(_it) => ImmediatePrevSibling::Visibility,
89                 _ => return None,
90             }
91         };
92         return Some(res);
93     }
94     let res = match_ast! {
95         match prev_sibling {
96             ast::ExprStmt(it) => {
97                 let node = it.expr().filter(|_| it.semicolon_token().is_none())?.syntax().clone();
98                 match_ast! {
99                     match node {
100                         ast::IfExpr(_it) => ImmediatePrevSibling::IfExpr,
101                         _ => return None,
102                     }
103                 }
104             },
105             ast::Trait(it) => if it.assoc_item_list().is_none() {
106                     ImmediatePrevSibling::TraitDefName
107                 } else {
108                     return None
109             },
110             ast::Impl(it) => if it.assoc_item_list().is_none()
111                 && (it.for_token().is_none() || it.self_ty().is_some()) {
112                     ImmediatePrevSibling::ImplDefType
113                 } else {
114                     return None
115             },
116             _ => return None,
117         }
118     };
119     Some(res)
120 }
121
122 pub(crate) fn determine_location(
123     sema: &Semantics<RootDatabase>,
124     original_file: &SyntaxNode,
125     offset: TextSize,
126     name_like: &ast::NameLike,
127 ) -> Option<ImmediateLocation> {
128     let node = match name_like {
129         ast::NameLike::NameRef(name_ref) => {
130             if ast::RecordExprField::for_field_name(name_ref).is_some() {
131                 return sema
132                     .find_node_at_offset_with_macros(original_file, offset)
133                     .map(ImmediateLocation::RecordExpr);
134             }
135             if ast::RecordPatField::for_field_name_ref(name_ref).is_some() {
136                 return sema
137                     .find_node_at_offset_with_macros(original_file, offset)
138                     .map(ImmediateLocation::RecordPat);
139             }
140             maximize_name_ref(name_ref)
141         }
142         ast::NameLike::Name(name) => {
143             if ast::RecordPatField::for_field_name(name).is_some() {
144                 return sema
145                     .find_node_at_offset_with_macros(original_file, offset)
146                     .map(ImmediateLocation::RecordPat);
147             }
148             name.syntax().clone()
149         }
150         ast::NameLike::Lifetime(lt) => lt.syntax().clone(),
151     };
152
153     let parent = match node.parent() {
154         Some(parent) => match ast::MacroCall::cast(parent.clone()) {
155             // When a path is being typed in an (Assoc)ItemList the parser will always emit a macro_call.
156             // This is usually fine as the node expansion code above already accounts for that with
157             // the ancestors call, but there is one exception to this which is that when an attribute
158             // precedes it the code above will not walk the Path to the parent MacroCall as their ranges differ.
159             // FIXME path expr and statement have a similar problem
160             Some(call)
161                 if call.excl_token().is_none()
162                     && call.token_tree().is_none()
163                     && call.semicolon_token().is_none() =>
164             {
165                 call.syntax().parent()?
166             }
167             _ => parent,
168         },
169         // SourceFile
170         None => {
171             return match node.kind() {
172                 MACRO_ITEMS | SOURCE_FILE => Some(ImmediateLocation::ItemList),
173                 _ => None,
174             }
175         }
176     };
177     let res = match_ast! {
178         match parent {
179             ast::IdentPat(_it) => ImmediateLocation::IdentPat,
180             ast::Use(_it) => ImmediateLocation::Use,
181             ast::BlockExpr(_it) => ImmediateLocation::BlockExpr,
182             ast::SourceFile(_it) => ImmediateLocation::ItemList,
183             ast::ItemList(_it) => ImmediateLocation::ItemList,
184             ast::RefExpr(_it) => ImmediateLocation::RefExpr,
185             ast::RecordField(_it) => ImmediateLocation::RecordField,
186             ast::AssocItemList(it) => match it.syntax().parent().map(|it| it.kind()) {
187                 Some(IMPL) => ImmediateLocation::Impl,
188                 Some(TRAIT) => ImmediateLocation::Trait,
189                 _ => return None,
190             },
191             ast::GenericArgList(_it) => sema
192                 .find_node_at_offset_with_macros(original_file, offset)
193                 .map(ImmediateLocation::GenericArgList)?,
194             ast::Module(it) => {
195                 if it.item_list().is_none() {
196                     ImmediateLocation::ModDeclaration(it)
197                 } else {
198                     return None;
199                 }
200             },
201             ast::Attr(it) => ImmediateLocation::Attribute(it),
202             ast::FieldExpr(it) => {
203                 let receiver = it
204                     .expr()
205                     .map(|e| e.syntax().text_range())
206                     .and_then(|r| find_node_with_range(original_file, r));
207                 let receiver_is_ambiguous_float_literal = if let Some(ast::Expr::Literal(l)) = &receiver {
208                     match l.kind() {
209                         ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
210                         _ => false,
211                     }
212                 } else {
213                     false
214                 };
215                 ImmediateLocation::FieldAccess {
216                     receiver,
217                     receiver_is_ambiguous_float_literal,
218                 }
219             },
220             ast::MethodCallExpr(it) => ImmediateLocation::MethodCall {
221                 receiver: it
222                     .receiver()
223                     .map(|e| e.syntax().text_range())
224                     .and_then(|r| find_node_with_range(original_file, r)),
225                 has_parens: it.arg_list().map_or(false, |it| it.l_paren_token().is_some())
226             },
227             _ => return None,
228         }
229     };
230     Some(res)
231 }
232
233 fn maximize_name_ref(name_ref: &ast::NameRef) -> SyntaxNode {
234     // Maximize a nameref to its enclosing path if its the last segment of said path
235     if let Some(segment) = name_ref.syntax().parent().and_then(ast::PathSegment::cast) {
236         let p = segment.parent_path();
237         if p.parent_path().is_none() {
238             if let Some(it) = p
239                 .syntax()
240                 .ancestors()
241                 .take_while(|it| it.text_range() == p.syntax().text_range())
242                 .last()
243             {
244                 return it;
245             }
246         }
247     }
248     name_ref.syntax().clone()
249 }
250
251 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
252     syntax.covering_element(range).ancestors().find_map(N::cast)
253 }
254
255 pub(crate) fn inside_impl_trait_block(element: SyntaxElement) -> bool {
256     // Here we search `impl` keyword up through the all ancestors, unlike in `has_impl_parent`,
257     // where we only check the first parent with different text range.
258     element
259         .ancestors()
260         .find(|it| it.kind() == IMPL)
261         .map(|it| ast::Impl::cast(it).unwrap())
262         .map(|it| it.trait_().is_some())
263         .unwrap_or(false)
264 }
265 #[test]
266 fn test_inside_impl_trait_block() {
267     check_pattern_is_applicable(r"impl Foo for Bar { f$0 }", inside_impl_trait_block);
268     check_pattern_is_applicable(r"impl Foo for Bar { fn f$0 }", inside_impl_trait_block);
269     check_pattern_is_not_applicable(r"impl A { f$0 }", inside_impl_trait_block);
270     check_pattern_is_not_applicable(r"impl A { fn f$0 }", inside_impl_trait_block);
271 }
272
273 pub(crate) fn previous_token(element: SyntaxElement) -> Option<SyntaxToken> {
274     element.into_token().and_then(previous_non_trivia_token)
275 }
276
277 /// Check if the token previous to the previous one is `for`.
278 /// For example, `for _ i$0` => true.
279 pub(crate) fn for_is_prev2(element: SyntaxElement) -> bool {
280     element
281         .into_token()
282         .and_then(previous_non_trivia_token)
283         .and_then(previous_non_trivia_token)
284         .filter(|it| it.kind() == T![for])
285         .is_some()
286 }
287 #[test]
288 fn test_for_is_prev2() {
289     check_pattern_is_applicable(r"for i i$0", for_is_prev2);
290 }
291
292 pub(crate) fn is_in_loop_body(node: &SyntaxNode) -> bool {
293     node.ancestors()
294         .take_while(|it| it.kind() != FN && it.kind() != CLOSURE_EXPR)
295         .find_map(|it| {
296             let loop_body = match_ast! {
297                 match it {
298                     ast::ForExpr(it) => it.loop_body(),
299                     ast::WhileExpr(it) => it.loop_body(),
300                     ast::LoopExpr(it) => it.loop_body(),
301                     _ => None,
302                 }
303             };
304             loop_body.filter(|it| it.syntax().text_range().contains_range(node.text_range()))
305         })
306         .is_some()
307 }
308
309 fn previous_non_trivia_token(token: SyntaxToken) -> Option<SyntaxToken> {
310     let mut token = token.prev_token();
311     while let Some(inner) = token.clone() {
312         if !inner.kind().is_trivia() {
313             return Some(inner);
314         } else {
315             token = inner.prev_token();
316         }
317     }
318     None
319 }
320
321 #[cfg(test)]
322 mod tests {
323     use syntax::algo::find_node_at_offset;
324
325     use crate::test_utils::position;
326
327     use super::*;
328
329     fn check_location(code: &str, loc: impl Into<Option<ImmediateLocation>>) {
330         let (db, pos) = position(code);
331
332         let sema = Semantics::new(&db);
333         let original_file = sema.parse(pos.file_id);
334
335         let name_like = find_node_at_offset(original_file.syntax(), pos.offset).unwrap();
336         assert_eq!(
337             determine_location(&sema, original_file.syntax(), pos.offset, &name_like),
338             loc.into()
339         );
340     }
341
342     fn check_prev_sibling(code: &str, sibling: impl Into<Option<ImmediatePrevSibling>>) {
343         check_pattern_is_applicable(code, |e| {
344             let name = &e.parent().and_then(ast::NameLike::cast).expect("Expected a namelike");
345             assert_eq!(determine_prev_sibling(name), sibling.into());
346             true
347         });
348     }
349
350     #[test]
351     fn test_trait_loc() {
352         check_location(r"trait A { f$0 }", ImmediateLocation::Trait);
353         check_location(r"trait A { #[attr] f$0 }", ImmediateLocation::Trait);
354         check_location(r"trait A { f$0 fn f() {} }", ImmediateLocation::Trait);
355         check_location(r"trait A { fn f() {} f$0 }", ImmediateLocation::Trait);
356         check_location(r"trait A$0 {}", None);
357         check_location(r"trait A { fn f$0 }", None);
358     }
359
360     #[test]
361     fn test_impl_loc() {
362         check_location(r"impl A { f$0 }", ImmediateLocation::Impl);
363         check_location(r"impl A { #[attr] f$0 }", ImmediateLocation::Impl);
364         check_location(r"impl A { f$0 fn f() {} }", ImmediateLocation::Impl);
365         check_location(r"impl A { fn f() {} f$0 }", ImmediateLocation::Impl);
366         check_location(r"impl A$0 {}", None);
367         check_location(r"impl A { fn f$0 }", None);
368     }
369
370     #[test]
371     fn test_use_loc() {
372         check_location(r"use f$0", ImmediateLocation::Use);
373         check_location(r"use f$0;", ImmediateLocation::Use);
374         check_location(r"use f::{f$0}", None);
375         check_location(r"use {f$0}", None);
376     }
377
378     #[test]
379     fn test_record_field_loc() {
380         check_location(r"struct Foo { f$0 }", ImmediateLocation::RecordField);
381         check_location(r"struct Foo { f$0 pub f: i32}", ImmediateLocation::RecordField);
382         check_location(r"struct Foo { pub f: i32, f$0 }", ImmediateLocation::RecordField);
383     }
384
385     #[test]
386     fn test_block_expr_loc() {
387         check_location(r"fn my_fn() { let a = 2; f$0 }", ImmediateLocation::BlockExpr);
388         check_location(r"fn my_fn() { f$0 f }", ImmediateLocation::BlockExpr);
389     }
390
391     #[test]
392     fn test_ident_pat_loc() {
393         check_location(r"fn my_fn(m$0) {}", ImmediateLocation::IdentPat);
394         check_location(r"fn my_fn() { let m$0 }", ImmediateLocation::IdentPat);
395         check_location(r"fn my_fn(&m$0) {}", ImmediateLocation::IdentPat);
396         check_location(r"fn my_fn() { let &m$0 }", ImmediateLocation::IdentPat);
397     }
398
399     #[test]
400     fn test_ref_expr_loc() {
401         check_location(r"fn my_fn() { let x = &m$0 foo; }", ImmediateLocation::RefExpr);
402     }
403
404     #[test]
405     fn test_item_list_loc() {
406         check_location(r"i$0", ImmediateLocation::ItemList);
407         check_location(r"#[attr] i$0", ImmediateLocation::ItemList);
408         check_location(r"fn f() {} i$0", ImmediateLocation::ItemList);
409         check_location(r"mod foo { f$0 }", ImmediateLocation::ItemList);
410         check_location(r"mod foo { #[attr] f$0 }", ImmediateLocation::ItemList);
411         check_location(r"mod foo { fn f() {} f$0 }", ImmediateLocation::ItemList);
412         check_location(r"mod foo$0 {}", None);
413     }
414
415     #[test]
416     fn test_impl_prev_sibling() {
417         check_prev_sibling(r"impl A w$0 ", ImmediatePrevSibling::ImplDefType);
418         check_prev_sibling(r"impl A w$0 {}", ImmediatePrevSibling::ImplDefType);
419         check_prev_sibling(r"impl A for A w$0 ", ImmediatePrevSibling::ImplDefType);
420         check_prev_sibling(r"impl A for A w$0 {}", ImmediatePrevSibling::ImplDefType);
421         check_prev_sibling(r"impl A for w$0 {}", None);
422         check_prev_sibling(r"impl A for w$0", None);
423     }
424
425     #[test]
426     fn test_trait_prev_sibling() {
427         check_prev_sibling(r"trait A w$0 ", ImmediatePrevSibling::TraitDefName);
428         check_prev_sibling(r"trait A w$0 {}", ImmediatePrevSibling::TraitDefName);
429     }
430
431     #[test]
432     fn test_if_expr_prev_sibling() {
433         check_prev_sibling(r"fn foo() { if true {} w$0", ImmediatePrevSibling::IfExpr);
434         check_prev_sibling(r"fn foo() { if true {}; w$0", None);
435     }
436
437     #[test]
438     fn test_vis_prev_sibling() {
439         check_prev_sibling(r"pub w$0", ImmediatePrevSibling::Visibility);
440     }
441 }