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