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