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