1 //! Patterns telling us certain facts about current syntax element, they are used in completion context
4 use ide_db::RootDatabase;
6 algo::non_trivia_sibling,
7 ast::{self, ArgListOwner, LoopBodyOwner},
8 match_ast, AstNode, Direction, SyntaxElement,
10 SyntaxNode, SyntaxToken, TextRange, TextSize, T,
14 use crate::tests::{check_pattern_is_applicable, check_pattern_is_not_applicable};
16 /// Immediate previous node to what we are completing.
17 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
18 pub(crate) enum ImmediatePrevSibling {
26 /// Direct parent "thing" of what we are currently completing.
27 #[derive(Clone, Debug, PartialEq, Eq)]
28 pub(crate) enum ImmediateLocation {
43 ModDeclaration(ast::Module),
44 // Original file ast node
46 receiver: Option<ast::Expr>,
49 // Original file ast node
51 receiver: Option<ast::Expr>,
52 receiver_is_ambiguous_float_literal: bool,
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),
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(),
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
76 // FIXME path expr and statement have a similar problem with attrs
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() =>
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! {
91 // vis followed by random ident will always error the parser
92 ast::Visibility(_it) => ImmediatePrevSibling::Visibility,
98 let res = match_ast! {
100 ast::ExprStmt(it) => {
101 let node = it.expr().filter(|_| it.semicolon_token().is_none())?.syntax().clone();
104 ast::IfExpr(_it) => ImmediatePrevSibling::IfExpr,
109 ast::Trait(it) => if it.assoc_item_list().is_none() {
110 ImmediatePrevSibling::TraitDefName
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
120 ast::Attr(_it) => ImmediatePrevSibling::Attribute,
127 pub(crate) fn determine_location(
128 sema: &Semantics<RootDatabase>,
129 original_file: &SyntaxNode,
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() {
137 .find_node_at_offset_with_macros(original_file, offset)
138 .map(ImmediateLocation::RecordExpr);
140 if ast::RecordPatField::for_field_name_ref(name_ref).is_some() {
142 .find_node_at_offset_with_macros(original_file, offset)
143 .map(ImmediateLocation::RecordPat);
145 maximize_name_ref(name_ref)
147 ast::NameLike::Name(name) => {
148 if ast::RecordPatField::for_field_name(name).is_some() {
150 .find_node_at_offset_with_macros(original_file, offset)
151 .map(ImmediateLocation::RecordPat);
153 name.syntax().clone()
155 ast::NameLike::Lifetime(lt) => lt.syntax().clone(),
160 ast::TypeBoundList(_it) => return Some(ImmediateLocation::TypeBound),
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
173 if call.excl_token().is_none()
174 && call.token_tree().is_none()
175 && call.semicolon_token().is_none() =>
177 call.syntax().parent()?
183 return match node.kind() {
184 MACRO_ITEMS | SOURCE_FILE => Some(ImmediateLocation::ItemList),
189 let res = match_ast! {
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)) {
202 ImmediateLocation::RecordField
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,
213 ast::GenericArgList(_it) => sema
214 .find_node_at_offset_with_macros(original_file, offset)
215 .map(ImmediateLocation::GenericArgList)?,
217 if it.item_list().is_none() {
218 ImmediateLocation::ModDeclaration(it)
223 ast::Attr(it) => ImmediateLocation::Attribute(it),
224 ast::FieldExpr(it) => {
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 {
231 ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
237 ImmediateLocation::FieldAccess {
239 receiver_is_ambiguous_float_literal,
242 ast::MethodCallExpr(it) => ImmediateLocation::MethodCall {
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())
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() {
263 .take_while(|it| it.text_range() == p.syntax().text_range())
270 name_ref.syntax().clone()
273 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
274 syntax.covering_element(range).ancestors().find_map(N::cast)
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.
282 .find(|it| it.kind() == IMPL)
283 .map(|it| ast::Impl::cast(it).unwrap())
284 .map(|it| it.trait_().is_some())
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);
295 pub(crate) fn previous_token(element: SyntaxElement) -> Option<SyntaxToken> {
296 element.into_token().and_then(previous_non_trivia_token)
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 {
304 .and_then(previous_non_trivia_token)
305 .and_then(previous_non_trivia_token)
306 .filter(|it| it.kind() == T![for])
310 fn test_for_is_prev2() {
311 check_pattern_is_applicable(r"for i i$0", for_is_prev2);
314 pub(crate) fn is_in_loop_body(node: &SyntaxNode) -> bool {
316 .take_while(|it| it.kind() != FN && it.kind() != CLOSURE_EXPR)
318 let loop_body = match_ast! {
320 ast::ForExpr(it) => it.loop_body(),
321 ast::WhileExpr(it) => it.loop_body(),
322 ast::LoopExpr(it) => it.loop_body(),
326 loop_body.filter(|it| it.syntax().text_range().contains_range(node.text_range()))
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() {
337 token = inner.prev_token();
345 use syntax::algo::find_node_at_offset;
347 use crate::tests::position;
351 fn check_location(code: &str, loc: impl Into<Option<ImmediateLocation>>) {
352 let (db, pos) = position(code);
354 let sema = Semantics::new(&db);
355 let original_file = sema.parse(pos.file_id);
357 let name_like = find_node_at_offset(original_file.syntax(), pos.offset).unwrap();
359 determine_location(&sema, original_file.syntax(), pos.offset, &name_like),
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());
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);
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);
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);
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);
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);
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);
422 fn test_ref_expr_loc() {
423 check_location(r"fn my_fn() { let x = &m$0 foo; }", ImmediateLocation::RefExpr);
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);
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);
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);
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);
460 fn test_vis_prev_sibling() {
461 check_prev_sibling(r"pub w$0", ImmediatePrevSibling::Visibility);
465 fn test_attr_prev_sibling() {
466 check_prev_sibling(r"#[attr] w$0", ImmediatePrevSibling::Attribute);