]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/context.rs
eeb4333f851e7dc25e2dd0116487638d179612fe
[rust.git] / crates / ide_completion / src / context.rs
1 //! See `CompletionContext` structure.
2
3 use hir::{Local, ScopeDef, Semantics, SemanticsScope, Type};
4 use ide_db::{
5     base_db::{FilePosition, SourceDatabase},
6     call_info::ActiveParameter,
7     RootDatabase,
8 };
9 use syntax::{
10     algo::find_node_at_offset,
11     ast::{self, NameOrNameRef, NameOwner},
12     match_ast, AstNode, NodeOrToken,
13     SyntaxKind::{self, *},
14     SyntaxNode, SyntaxToken, TextRange, TextSize, T,
15 };
16 use text_edit::Indel;
17
18 use crate::{
19     patterns::{
20         determine_location, determine_prev_sibling, for_is_prev2, inside_impl_trait_block,
21         is_in_loop_body, previous_token, ImmediateLocation, ImmediatePrevSibling,
22     },
23     CompletionConfig,
24 };
25
26 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
27 pub(crate) enum PatternRefutability {
28     Refutable,
29     Irrefutable,
30 }
31
32 /// `CompletionContext` is created early during completion to figure out, where
33 /// exactly is the cursor, syntax-wise.
34 #[derive(Debug)]
35 pub(crate) struct CompletionContext<'a> {
36     pub(super) sema: Semantics<'a, RootDatabase>,
37     pub(super) scope: SemanticsScope<'a>,
38     pub(super) db: &'a RootDatabase,
39     pub(super) config: &'a CompletionConfig,
40     pub(super) position: FilePosition,
41     /// The token before the cursor, in the original file.
42     pub(super) original_token: SyntaxToken,
43     /// The token before the cursor, in the macro-expanded file.
44     pub(super) token: SyntaxToken,
45     pub(super) krate: Option<hir::Crate>,
46     pub(super) expected_name: Option<NameOrNameRef>,
47     pub(super) expected_type: Option<Type>,
48     pub(super) name_ref_syntax: Option<ast::NameRef>,
49
50     pub(super) use_item_syntax: Option<ast::Use>,
51
52     /// The parent function of the cursor position if it exists.
53     pub(super) function_def: Option<ast::Fn>,
54     /// The parent impl of the cursor position if it exists.
55     pub(super) impl_def: Option<ast::Impl>,
56
57     // potentially set if we are completing a lifetime
58     pub(super) lifetime_syntax: Option<ast::Lifetime>,
59     pub(super) lifetime_param_syntax: Option<ast::LifetimeParam>,
60     pub(super) lifetime_allowed: bool,
61     pub(super) is_label_ref: bool,
62
63     // potentially set if we are completing a name
64     pub(super) is_pat_or_const: Option<PatternRefutability>,
65     pub(super) is_param: bool,
66
67     pub(super) completion_location: Option<ImmediateLocation>,
68     pub(super) prev_sibling: Option<ImmediatePrevSibling>,
69     pub(super) attribute_under_caret: Option<ast::Attr>,
70
71     /// FIXME: `ActiveParameter` is string-based, which is very very wrong
72     pub(super) active_parameter: Option<ActiveParameter>,
73     /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
74     pub(super) is_trivial_path: bool,
75     /// If not a trivial path, the prefix (qualifier).
76     pub(super) path_qual: Option<ast::Path>,
77     /// `true` if we are a statement or a last expr in the block.
78     pub(super) can_be_stmt: bool,
79     /// `true` if we expect an expression at the cursor position.
80     pub(super) is_expr: bool,
81     /// Something is typed at the "top" level, in module or impl/trait.
82     pub(super) is_new_item: bool,
83     /// If this is a call (method or function) in particular, i.e. the () are already there.
84     pub(super) is_call: bool,
85     /// Like `is_call`, but for tuple patterns.
86     pub(super) is_pattern_call: bool,
87     /// If this is a macro call, i.e. the () are already there.
88     pub(super) is_macro_call: bool,
89     pub(super) is_path_type: bool,
90     pub(super) has_type_args: bool,
91     pub(super) locals: Vec<(String, Local)>,
92
93     pub(super) previous_token: Option<SyntaxToken>,
94     pub(super) in_loop_body: bool,
95     pub(super) incomplete_let: bool,
96
97     no_completion_required: bool,
98 }
99
100 impl<'a> CompletionContext<'a> {
101     pub(super) fn new(
102         db: &'a RootDatabase,
103         position: FilePosition,
104         config: &'a CompletionConfig,
105     ) -> Option<CompletionContext<'a>> {
106         let sema = Semantics::new(db);
107
108         let original_file = sema.parse(position.file_id);
109
110         // Insert a fake ident to get a valid parse tree. We will use this file
111         // to determine context, though the original_file will be used for
112         // actual completion.
113         let file_with_fake_ident = {
114             let parse = db.parse(position.file_id);
115             let edit = Indel::insert(position.offset, "intellijRulezz".to_string());
116             parse.reparse(&edit).tree()
117         };
118         let fake_ident_token =
119             file_with_fake_ident.syntax().token_at_offset(position.offset).right_biased().unwrap();
120
121         let krate = sema.to_module_def(position.file_id).map(|m| m.krate());
122         let original_token =
123             original_file.syntax().token_at_offset(position.offset).left_biased()?;
124         let token = sema.descend_into_macros(original_token.clone());
125         let scope = sema.scope_at_offset(&token, position.offset);
126         let mut locals = vec![];
127         scope.process_all_names(&mut |name, scope| {
128             if let ScopeDef::Local(local) = scope {
129                 locals.push((name.to_string(), local));
130             }
131         });
132         let mut ctx = CompletionContext {
133             sema,
134             scope,
135             db,
136             config,
137             position,
138             original_token,
139             token,
140             krate,
141             lifetime_allowed: false,
142             expected_name: None,
143             expected_type: None,
144             name_ref_syntax: None,
145             lifetime_syntax: None,
146             lifetime_param_syntax: None,
147             function_def: None,
148             use_item_syntax: None,
149             impl_def: None,
150             active_parameter: ActiveParameter::at(db, position),
151             is_label_ref: false,
152             is_param: false,
153             is_pat_or_const: None,
154             is_trivial_path: false,
155             path_qual: None,
156             can_be_stmt: false,
157             is_expr: false,
158             is_new_item: false,
159             is_call: false,
160             is_pattern_call: false,
161             is_macro_call: false,
162             is_path_type: false,
163             has_type_args: false,
164             previous_token: None,
165             in_loop_body: false,
166             completion_location: None,
167             prev_sibling: None,
168             no_completion_required: false,
169             incomplete_let: false,
170             attribute_under_caret: None,
171             locals,
172         };
173
174         let mut original_file = original_file.syntax().clone();
175         let mut speculative_file = file_with_fake_ident.syntax().clone();
176         let mut offset = position.offset;
177         let mut fake_ident_token = fake_ident_token;
178
179         // Are we inside a macro call?
180         while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
181             find_node_at_offset::<ast::MacroCall>(&original_file, offset),
182             find_node_at_offset::<ast::MacroCall>(&speculative_file, offset),
183         ) {
184             if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
185                 != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
186             {
187                 break;
188             }
189             let speculative_args = match macro_call_with_fake_ident.token_tree() {
190                 Some(tt) => tt,
191                 None => break,
192             };
193             if let (Some(actual_expansion), Some(speculative_expansion)) = (
194                 ctx.sema.expand(&actual_macro_call),
195                 ctx.sema.speculative_expand(
196                     &actual_macro_call,
197                     &speculative_args,
198                     fake_ident_token,
199                 ),
200             ) {
201                 let new_offset = speculative_expansion.1.text_range().start();
202                 if new_offset > actual_expansion.text_range().end() {
203                     break;
204                 }
205                 original_file = actual_expansion;
206                 speculative_file = speculative_expansion.0;
207                 fake_ident_token = speculative_expansion.1;
208                 offset = new_offset;
209             } else {
210                 break;
211             }
212         }
213         ctx.fill(&original_file, speculative_file, offset);
214         Some(ctx)
215     }
216
217     /// Checks whether completions in that particular case don't make much sense.
218     /// Examples:
219     /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
220     ///   Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
221     /// - `for _ i$0` -- obviously, it'll be "in" keyword.
222     pub(crate) fn no_completion_required(&self) -> bool {
223         self.no_completion_required
224     }
225
226     /// The range of the identifier that is being completed.
227     pub(crate) fn source_range(&self) -> TextRange {
228         // check kind of macro-expanded token, but use range of original token
229         let kind = self.token.kind();
230         if kind == IDENT || kind == LIFETIME_IDENT || kind == UNDERSCORE || kind.is_keyword() {
231             cov_mark::hit!(completes_if_prefix_is_keyword);
232             self.original_token.text_range()
233         } else if kind == CHAR {
234             // assume we are completing a lifetime but the user has only typed the '
235             cov_mark::hit!(completes_if_lifetime_without_idents);
236             TextRange::at(self.original_token.text_range().start(), TextSize::from(1))
237         } else {
238             TextRange::empty(self.position.offset)
239         }
240     }
241
242     pub(crate) fn previous_token_is(&self, kind: SyntaxKind) -> bool {
243         self.previous_token.as_ref().map_or(false, |tok| tok.kind() == kind)
244     }
245
246     pub(crate) fn expects_assoc_item(&self) -> bool {
247         matches!(
248             self.completion_location,
249             Some(ImmediateLocation::Trait) | Some(ImmediateLocation::Impl)
250         )
251     }
252
253     pub(crate) fn has_dot_receiver(&self) -> bool {
254         matches!(
255             &self.completion_location,
256             Some(ImmediateLocation::FieldAccess { receiver, .. }) | Some(ImmediateLocation::MethodCall { receiver })
257                 if receiver.is_some()
258         )
259     }
260
261     pub(crate) fn dot_receiver(&self) -> Option<&ast::Expr> {
262         match &self.completion_location {
263             Some(ImmediateLocation::MethodCall { receiver })
264             | Some(ImmediateLocation::FieldAccess { receiver, .. }) => receiver.as_ref(),
265             _ => None,
266         }
267     }
268
269     pub(crate) fn expects_use_tree(&self) -> bool {
270         matches!(self.completion_location, Some(ImmediateLocation::Use))
271     }
272
273     pub(crate) fn expects_non_trait_assoc_item(&self) -> bool {
274         matches!(self.completion_location, Some(ImmediateLocation::Impl))
275     }
276
277     pub(crate) fn expects_item(&self) -> bool {
278         matches!(self.completion_location, Some(ImmediateLocation::ItemList))
279     }
280
281     //         fn expects_value(&self) -> bool {
282     pub(crate) fn expects_expression(&self) -> bool {
283         self.is_expr
284     }
285
286     pub(crate) fn has_block_expr_parent(&self) -> bool {
287         matches!(self.completion_location, Some(ImmediateLocation::BlockExpr))
288     }
289
290     pub(crate) fn expects_ident_pat_or_ref_expr(&self) -> bool {
291         matches!(
292             self.completion_location,
293             Some(ImmediateLocation::IdentPat) | Some(ImmediateLocation::RefExpr)
294         )
295     }
296
297     pub(crate) fn expect_record_field(&self) -> bool {
298         matches!(self.completion_location, Some(ImmediateLocation::RecordField))
299     }
300
301     pub(crate) fn has_impl_or_trait_prev_sibling(&self) -> bool {
302         matches!(
303             self.prev_sibling,
304             Some(ImmediatePrevSibling::ImplDefType) | Some(ImmediatePrevSibling::TraitDefName)
305         )
306     }
307
308     pub(crate) fn after_if(&self) -> bool {
309         matches!(self.prev_sibling, Some(ImmediatePrevSibling::IfExpr))
310     }
311
312     pub(crate) fn is_path_disallowed(&self) -> bool {
313         matches!(
314             self.completion_location,
315             Some(ImmediateLocation::Attribute(_))
316                 | Some(ImmediateLocation::ModDeclaration(_))
317                 | Some(ImmediateLocation::RecordPat(_))
318                 | Some(ImmediateLocation::RecordExpr(_))
319         ) || self.attribute_under_caret.is_some()
320     }
321
322     fn fill_impl_def(&mut self) {
323         self.impl_def = self
324             .sema
325             .token_ancestors_with_macros(self.token.clone())
326             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
327             .find_map(ast::Impl::cast);
328     }
329
330     fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
331         let mut node = match self.token.parent() {
332             Some(it) => it,
333             None => return (None, None),
334         };
335         loop {
336             break match_ast! {
337                 match node {
338                     ast::LetStmt(it) => {
339                         cov_mark::hit!(expected_type_let_with_leading_char);
340                         cov_mark::hit!(expected_type_let_without_leading_char);
341                         let ty = it.pat()
342                             .and_then(|pat| self.sema.type_of_pat(&pat))
343                             .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)));
344                         let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
345                             ident.name().map(NameOrNameRef::Name)
346                         } else {
347                             None
348                         };
349
350                         (ty, name)
351                     },
352                     ast::ArgList(_it) => {
353                         cov_mark::hit!(expected_type_fn_param_with_leading_char);
354                         cov_mark::hit!(expected_type_fn_param_without_leading_char);
355                         ActiveParameter::at_token(
356                             &self.sema,
357                             self.token.clone(),
358                         ).map(|ap| {
359                             let name = ap.ident().map(NameOrNameRef::Name);
360                             (Some(ap.ty), name)
361                         })
362                         .unwrap_or((None, None))
363                     },
364                     ast::RecordExprFieldList(_it) => {
365                         cov_mark::hit!(expected_type_struct_field_without_leading_char);
366                         // wouldn't try {} be nice...
367                         (|| {
368                             let expr_field = self.token.prev_sibling_or_token()?
369                                       .into_node()
370                                       .and_then(|node| ast::RecordExprField::cast(node))?;
371                             let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
372                             Some((
373                                 Some(ty),
374                                 expr_field.field_name().map(NameOrNameRef::NameRef),
375                             ))
376                         })().unwrap_or((None, None))
377                     },
378                     ast::RecordExprField(it) => {
379                         cov_mark::hit!(expected_type_struct_field_with_leading_char);
380                         (
381                             it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)),
382                             it.field_name().map(NameOrNameRef::NameRef),
383                         )
384                     },
385                     ast::MatchExpr(it) => {
386                         cov_mark::hit!(expected_type_match_arm_without_leading_char);
387                         let ty = it.expr()
388                             .and_then(|e| self.sema.type_of_expr(&e));
389                         (ty, None)
390                     },
391                     ast::IfExpr(it) => {
392                         cov_mark::hit!(expected_type_if_let_without_leading_char);
393                         let ty = it.condition()
394                             .and_then(|cond| cond.expr())
395                             .and_then(|e| self.sema.type_of_expr(&e));
396                         (ty, None)
397                     },
398                     ast::IdentPat(it) => {
399                         cov_mark::hit!(expected_type_if_let_with_leading_char);
400                         cov_mark::hit!(expected_type_match_arm_with_leading_char);
401                         let ty = self.sema.type_of_pat(&ast::Pat::from(it));
402                         (ty, None)
403                     },
404                     ast::Fn(it) => {
405                         cov_mark::hit!(expected_type_fn_ret_with_leading_char);
406                         cov_mark::hit!(expected_type_fn_ret_without_leading_char);
407                         let def = self.sema.to_def(&it);
408                         (def.map(|def| def.ret_type(self.db)), None)
409                     },
410                     ast::ClosureExpr(it) => {
411                         let ty = self.sema.type_of_expr(&it.into());
412                         ty.and_then(|ty| ty.as_callable(self.db))
413                             .map(|c| (Some(c.return_type()), None))
414                             .unwrap_or((None, None))
415                     },
416                     ast::Stmt(_it) => (None, None),
417                     _ => {
418                         match node.parent() {
419                             Some(n) => {
420                                 node = n;
421                                 continue;
422                             },
423                             None => (None, None),
424                         }
425                     },
426                 }
427             };
428         }
429     }
430
431     fn fill(
432         &mut self,
433         original_file: &SyntaxNode,
434         file_with_fake_ident: SyntaxNode,
435         offset: TextSize,
436     ) {
437         let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
438         let syntax_element = NodeOrToken::Token(fake_ident_token);
439         self.previous_token = previous_token(syntax_element.clone());
440         self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
441         self.no_completion_required = {
442             let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
443             let fn_is_prev = self.previous_token_is(T![fn]);
444             let for_is_prev2 = for_is_prev2(syntax_element.clone());
445             (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
446         };
447         self.in_loop_body = is_in_loop_body(syntax_element.clone());
448
449         self.incomplete_let =
450             syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
451                 it.syntax().text_range().end() == syntax_element.text_range().end()
452             });
453
454         let (expected_type, expected_name) = self.expected_type_and_name();
455         self.expected_type = expected_type;
456         self.expected_name = expected_name;
457
458         let name_like = match find_node_at_offset(&&file_with_fake_ident, offset) {
459             Some(it) => it,
460             None => return,
461         };
462         self.completion_location =
463             determine_location(&self.sema, original_file, offset, &name_like);
464         self.prev_sibling = determine_prev_sibling(&name_like);
465         match name_like {
466             ast::NameLike::Lifetime(lifetime) => {
467                 self.classify_lifetime(original_file, lifetime, offset);
468             }
469             ast::NameLike::NameRef(name_ref) => {
470                 self.classify_name_ref(original_file, name_ref);
471             }
472             ast::NameLike::Name(name) => {
473                 self.classify_name(name);
474             }
475         }
476     }
477
478     fn classify_lifetime(
479         &mut self,
480         original_file: &SyntaxNode,
481         lifetime: ast::Lifetime,
482         offset: TextSize,
483     ) {
484         self.lifetime_syntax =
485             find_node_at_offset(original_file, lifetime.syntax().text_range().start());
486         if let Some(parent) = lifetime.syntax().parent() {
487             if parent.kind() == ERROR {
488                 return;
489             }
490
491             match_ast! {
492                 match parent {
493                     ast::LifetimeParam(_it) => {
494                         self.lifetime_allowed = true;
495                         self.lifetime_param_syntax =
496                             self.sema.find_node_at_offset_with_macros(original_file, offset);
497                     },
498                     ast::BreakExpr(_it) => self.is_label_ref = true,
499                     ast::ContinueExpr(_it) => self.is_label_ref = true,
500                     ast::Label(_it) => (),
501                     _ => self.lifetime_allowed = true,
502                 }
503             }
504         }
505     }
506
507     fn classify_name(&mut self, name: ast::Name) {
508         if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
509             self.is_pat_or_const = Some(PatternRefutability::Refutable);
510             // if any of these is here our bind pat can't be a const pat anymore
511             let complex_ident_pat = bind_pat.at_token().is_some()
512                 || bind_pat.ref_token().is_some()
513                 || bind_pat.mut_token().is_some();
514             if complex_ident_pat {
515                 self.is_pat_or_const = None;
516             } else {
517                 let irrefutable_pat = bind_pat.syntax().ancestors().find_map(|node| {
518                     match_ast! {
519                         match node {
520                             ast::LetStmt(it) => Some(it.pat()),
521                             ast::Param(it) => Some(it.pat()),
522                             _ => None,
523                         }
524                     }
525                 });
526                 if let Some(Some(pat)) = irrefutable_pat {
527                     // This check is here since we could be inside a pattern in the initializer expression of the let statement.
528                     if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range()) {
529                         self.is_pat_or_const = Some(PatternRefutability::Irrefutable);
530                     }
531                 }
532
533                 let is_name_in_field_pat = bind_pat
534                     .syntax()
535                     .parent()
536                     .and_then(ast::RecordPatField::cast)
537                     .map_or(false, |pat_field| pat_field.name_ref().is_none());
538                 if is_name_in_field_pat {
539                     self.is_pat_or_const = None;
540                 }
541             }
542
543             self.fill_impl_def();
544         }
545
546         self.is_param |= is_node::<ast::Param>(name.syntax());
547     }
548
549     fn classify_name_ref(&mut self, original_file: &SyntaxNode, name_ref: ast::NameRef) {
550         self.fill_impl_def();
551
552         self.name_ref_syntax =
553             find_node_at_offset(original_file, name_ref.syntax().text_range().start());
554
555         let name_range = name_ref.syntax().text_range();
556         let top_node = name_ref
557             .syntax()
558             .ancestors()
559             .take_while(|it| it.text_range() == name_range)
560             .last()
561             .unwrap();
562
563         if matches!(top_node.parent().map(|it| it.kind()), Some(SOURCE_FILE) | Some(ITEM_LIST)) {
564             self.is_new_item = true;
565             return;
566         }
567
568         self.use_item_syntax =
569             self.sema.token_ancestors_with_macros(self.token.clone()).find_map(ast::Use::cast);
570
571         self.function_def = self
572             .sema
573             .token_ancestors_with_macros(self.token.clone())
574             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
575             .find_map(ast::Fn::cast);
576
577         let parent = match name_ref.syntax().parent() {
578             Some(it) => it,
579             None => return,
580         };
581
582         if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
583             let path = segment.parent_path();
584             self.is_call = path
585                 .syntax()
586                 .parent()
587                 .and_then(ast::PathExpr::cast)
588                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
589                 .is_some();
590             self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
591             self.is_pattern_call =
592                 path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
593
594             self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
595             self.has_type_args = segment.generic_arg_list().is_some();
596
597             if let Some(path) = path_or_use_tree_qualifier(&path) {
598                 self.path_qual = path
599                     .segment()
600                     .and_then(|it| {
601                         find_node_with_range::<ast::PathSegment>(
602                             original_file,
603                             it.syntax().text_range(),
604                         )
605                     })
606                     .map(|it| it.parent_path());
607                 return;
608             }
609
610             if let Some(segment) = path.segment() {
611                 if segment.coloncolon_token().is_some() {
612                     return;
613                 }
614             }
615
616             self.is_trivial_path = true;
617
618             // Find either enclosing expr statement (thing with `;`) or a
619             // block. If block, check that we are the last expr.
620             self.can_be_stmt = name_ref
621                 .syntax()
622                 .ancestors()
623                 .find_map(|node| {
624                     if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
625                         return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
626                     }
627                     if let Some(block) = ast::BlockExpr::cast(node) {
628                         return Some(
629                             block.tail_expr().map(|e| e.syntax().text_range())
630                                 == Some(name_ref.syntax().text_range()),
631                         );
632                     }
633                     None
634                 })
635                 .unwrap_or(false);
636             self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
637         }
638         self.is_call |=
639             matches!(self.completion_location, Some(ImmediateLocation::MethodCall { .. }));
640     }
641 }
642
643 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
644     syntax.covering_element(range).ancestors().find_map(N::cast)
645 }
646
647 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
648     match node.ancestors().find_map(N::cast) {
649         None => false,
650         Some(n) => n.syntax().text_range() == node.text_range(),
651     }
652 }
653
654 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
655     if let Some(qual) = path.qualifier() {
656         return Some(qual);
657     }
658     let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
659     let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
660     use_tree.path()
661 }
662
663 #[cfg(test)]
664 mod tests {
665     use expect_test::{expect, Expect};
666     use hir::HirDisplay;
667
668     use crate::test_utils::{position, TEST_CONFIG};
669
670     use super::CompletionContext;
671
672     fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
673         let (db, pos) = position(ra_fixture);
674         let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
675
676         let ty = completion_context
677             .expected_type
678             .map(|t| t.display_test(&db).to_string())
679             .unwrap_or("?".to_owned());
680
681         let name = completion_context
682             .expected_name
683             .map_or_else(|| "?".to_owned(), |name| name.to_string());
684
685         expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
686     }
687
688     #[test]
689     fn expected_type_let_without_leading_char() {
690         cov_mark::check!(expected_type_let_without_leading_char);
691         check_expected_type_and_name(
692             r#"
693 fn foo() {
694     let x: u32 = $0;
695 }
696 "#,
697             expect![[r#"ty: u32, name: x"#]],
698         );
699     }
700
701     #[test]
702     fn expected_type_let_with_leading_char() {
703         cov_mark::check!(expected_type_let_with_leading_char);
704         check_expected_type_and_name(
705             r#"
706 fn foo() {
707     let x: u32 = c$0;
708 }
709 "#,
710             expect![[r#"ty: u32, name: x"#]],
711         );
712     }
713
714     #[test]
715     fn expected_type_let_pat() {
716         check_expected_type_and_name(
717             r#"
718 fn foo() {
719     let x$0 = 0u32;
720 }
721 "#,
722             expect![[r#"ty: u32, name: ?"#]],
723         );
724         check_expected_type_and_name(
725             r#"
726 fn foo() {
727     let $0 = 0u32;
728 }
729 "#,
730             expect![[r#"ty: u32, name: ?"#]],
731         );
732     }
733
734     #[test]
735     fn expected_type_fn_param_without_leading_char() {
736         cov_mark::check!(expected_type_fn_param_without_leading_char);
737         check_expected_type_and_name(
738             r#"
739 fn foo() {
740     bar($0);
741 }
742
743 fn bar(x: u32) {}
744 "#,
745             expect![[r#"ty: u32, name: x"#]],
746         );
747     }
748
749     #[test]
750     fn expected_type_fn_param_with_leading_char() {
751         cov_mark::check!(expected_type_fn_param_with_leading_char);
752         check_expected_type_and_name(
753             r#"
754 fn foo() {
755     bar(c$0);
756 }
757
758 fn bar(x: u32) {}
759 "#,
760             expect![[r#"ty: u32, name: x"#]],
761         );
762     }
763
764     #[test]
765     fn expected_type_struct_field_without_leading_char() {
766         cov_mark::check!(expected_type_struct_field_without_leading_char);
767         check_expected_type_and_name(
768             r#"
769 struct Foo { a: u32 }
770 fn foo() {
771     Foo { a: $0 };
772 }
773 "#,
774             expect![[r#"ty: u32, name: a"#]],
775         )
776     }
777
778     #[test]
779     fn expected_type_generic_struct_field() {
780         check_expected_type_and_name(
781             r#"
782 struct Foo<T> { a: T }
783 fn foo() -> Foo<u32> {
784     Foo { a: $0 }
785 }
786 "#,
787             expect![[r#"ty: u32, name: a"#]],
788         )
789     }
790
791     #[test]
792     fn expected_type_struct_field_with_leading_char() {
793         cov_mark::check!(expected_type_struct_field_with_leading_char);
794         check_expected_type_and_name(
795             r#"
796 struct Foo { a: u32 }
797 fn foo() {
798     Foo { a: c$0 };
799 }
800 "#,
801             expect![[r#"ty: u32, name: a"#]],
802         );
803     }
804
805     #[test]
806     fn expected_type_match_arm_without_leading_char() {
807         cov_mark::check!(expected_type_match_arm_without_leading_char);
808         check_expected_type_and_name(
809             r#"
810 enum E { X }
811 fn foo() {
812    match E::X { $0 }
813 }
814 "#,
815             expect![[r#"ty: E, name: ?"#]],
816         );
817     }
818
819     #[test]
820     fn expected_type_match_arm_with_leading_char() {
821         cov_mark::check!(expected_type_match_arm_with_leading_char);
822         check_expected_type_and_name(
823             r#"
824 enum E { X }
825 fn foo() {
826    match E::X { c$0 }
827 }
828 "#,
829             expect![[r#"ty: E, name: ?"#]],
830         );
831     }
832
833     #[test]
834     fn expected_type_if_let_without_leading_char() {
835         cov_mark::check!(expected_type_if_let_without_leading_char);
836         check_expected_type_and_name(
837             r#"
838 enum Foo { Bar, Baz, Quux }
839
840 fn foo() {
841     let f = Foo::Quux;
842     if let $0 = f { }
843 }
844 "#,
845             expect![[r#"ty: Foo, name: ?"#]],
846         )
847     }
848
849     #[test]
850     fn expected_type_if_let_with_leading_char() {
851         cov_mark::check!(expected_type_if_let_with_leading_char);
852         check_expected_type_and_name(
853             r#"
854 enum Foo { Bar, Baz, Quux }
855
856 fn foo() {
857     let f = Foo::Quux;
858     if let c$0 = f { }
859 }
860 "#,
861             expect![[r#"ty: Foo, name: ?"#]],
862         )
863     }
864
865     #[test]
866     fn expected_type_fn_ret_without_leading_char() {
867         cov_mark::check!(expected_type_fn_ret_without_leading_char);
868         check_expected_type_and_name(
869             r#"
870 fn foo() -> u32 {
871     $0
872 }
873 "#,
874             expect![[r#"ty: u32, name: ?"#]],
875         )
876     }
877
878     #[test]
879     fn expected_type_fn_ret_with_leading_char() {
880         cov_mark::check!(expected_type_fn_ret_with_leading_char);
881         check_expected_type_and_name(
882             r#"
883 fn foo() -> u32 {
884     c$0
885 }
886 "#,
887             expect![[r#"ty: u32, name: ?"#]],
888         )
889     }
890
891     #[test]
892     fn expected_type_fn_ret_fn_ref_fully_typed() {
893         check_expected_type_and_name(
894             r#"
895 fn foo() -> u32 {
896     foo$0
897 }
898 "#,
899             expect![[r#"ty: u32, name: ?"#]],
900         )
901     }
902
903     #[test]
904     fn expected_type_closure_param_return() {
905         // FIXME: make this work with `|| $0`
906         check_expected_type_and_name(
907             r#"
908 fn foo() {
909     bar(|| a$0);
910 }
911
912 fn bar(f: impl FnOnce() -> u32) {}
913 #[lang = "fn_once"]
914 trait FnOnce { type Output; }
915 "#,
916             expect![[r#"ty: u32, name: ?"#]],
917         );
918     }
919
920     #[test]
921     fn expected_type_generic_function() {
922         check_expected_type_and_name(
923             r#"
924 fn foo() {
925     bar::<u32>($0);
926 }
927
928 fn bar<T>(t: T) {}
929 "#,
930             expect![[r#"ty: u32, name: t"#]],
931         );
932     }
933
934     #[test]
935     fn expected_type_generic_method() {
936         check_expected_type_and_name(
937             r#"
938 fn foo() {
939     S(1u32).bar($0);
940 }
941
942 struct S<T>(T);
943 impl<T> S<T> {
944     fn bar(self, t: T) {}
945 }
946 "#,
947             expect![[r#"ty: u32, name: t"#]],
948         );
949     }
950 }