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