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