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