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