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