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