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