]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/context.rs
Merge #8015
[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::base_db::{FilePosition, SourceDatabase};
5 use ide_db::{call_info::ActiveParameter, RootDatabase};
6 use syntax::{
7     algo::find_node_at_offset, ast, match_ast, AstNode, NodeOrToken, SyntaxKind::*, SyntaxNode,
8     SyntaxToken, TextRange, TextSize,
9 };
10
11 use text_edit::Indel;
12
13 use crate::{
14     patterns::{
15         fn_is_prev, for_is_prev2, has_bind_pat_parent, has_block_expr_parent,
16         has_field_list_parent, has_impl_as_prev_sibling, has_impl_parent,
17         has_item_list_or_source_file_parent, has_ref_parent, has_trait_as_prev_sibling,
18         has_trait_parent, if_is_prev, inside_impl_trait_block, is_in_loop_body, is_match_arm,
19         unsafe_is_prev,
20     },
21     CompletionConfig,
22 };
23
24 /// `CompletionContext` is created early during completion to figure out, where
25 /// exactly is the cursor, syntax-wise.
26 #[derive(Debug)]
27 pub(crate) struct CompletionContext<'a> {
28     pub(super) sema: Semantics<'a, RootDatabase>,
29     pub(super) scope: SemanticsScope<'a>,
30     pub(super) db: &'a RootDatabase,
31     pub(super) config: &'a CompletionConfig,
32     pub(super) position: FilePosition,
33     /// The token before the cursor, in the original file.
34     pub(super) original_token: SyntaxToken,
35     /// The token before the cursor, in the macro-expanded file.
36     pub(super) token: SyntaxToken,
37     pub(super) krate: Option<hir::Crate>,
38     pub(super) expected_name: Option<String>,
39     pub(super) expected_type: Option<Type>,
40     pub(super) name_ref_syntax: Option<ast::NameRef>,
41     pub(super) function_syntax: Option<ast::Fn>,
42     pub(super) use_item_syntax: Option<ast::Use>,
43     pub(super) record_lit_syntax: Option<ast::RecordExpr>,
44     pub(super) record_pat_syntax: Option<ast::RecordPat>,
45     pub(super) record_field_syntax: Option<ast::RecordExprField>,
46     pub(super) impl_def: Option<ast::Impl>,
47     /// FIXME: `ActiveParameter` is string-based, which is very very wrong
48     pub(super) active_parameter: Option<ActiveParameter>,
49     pub(super) is_param: bool,
50     /// If a name-binding or reference to a const in a pattern.
51     /// Irrefutable patterns (like let) are excluded.
52     pub(super) is_pat_binding_or_const: bool,
53     pub(super) is_irrefutable_pat_binding: bool,
54     /// A single-indent path, like `foo`. `::foo` should not be considered a trivial path.
55     pub(super) is_trivial_path: bool,
56     /// If not a trivial path, the prefix (qualifier).
57     pub(super) path_qual: Option<ast::Path>,
58     pub(super) after_if: bool,
59     /// `true` if we are a statement or a last expr in the block.
60     pub(super) can_be_stmt: bool,
61     /// `true` if we expect an expression at the cursor position.
62     pub(super) is_expr: bool,
63     /// Something is typed at the "top" level, in module or impl/trait.
64     pub(super) is_new_item: bool,
65     /// The receiver if this is a field or method access, i.e. writing something.$0
66     pub(super) dot_receiver: Option<ast::Expr>,
67     pub(super) dot_receiver_is_ambiguous_float_literal: bool,
68     /// If this is a call (method or function) in particular, i.e. the () are already there.
69     pub(super) is_call: bool,
70     /// Like `is_call`, but for tuple patterns.
71     pub(super) is_pattern_call: bool,
72     /// If this is a macro call, i.e. the () are already there.
73     pub(super) is_macro_call: bool,
74     pub(super) is_path_type: bool,
75     pub(super) has_type_args: bool,
76     pub(super) attribute_under_caret: Option<ast::Attr>,
77     pub(super) mod_declaration_under_caret: Option<ast::Module>,
78     pub(super) unsafe_is_prev: bool,
79     pub(super) if_is_prev: bool,
80     pub(super) block_expr_parent: bool,
81     pub(super) bind_pat_parent: bool,
82     pub(super) ref_pat_parent: bool,
83     pub(super) in_loop_body: bool,
84     pub(super) has_trait_parent: bool,
85     pub(super) has_impl_parent: bool,
86     pub(super) inside_impl_trait_block: bool,
87     pub(super) has_field_list_parent: bool,
88     pub(super) trait_as_prev_sibling: bool,
89     pub(super) impl_as_prev_sibling: bool,
90     pub(super) is_match_arm: bool,
91     pub(super) has_item_list_or_source_file_parent: bool,
92     pub(super) for_is_prev2: bool,
93     pub(super) fn_is_prev: bool,
94     pub(super) incomplete_let: bool,
95     pub(super) locals: Vec<(String, Local)>,
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.parent(), 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             expected_name: None,
140             expected_type: None,
141             name_ref_syntax: None,
142             function_syntax: None,
143             use_item_syntax: None,
144             record_lit_syntax: None,
145             record_pat_syntax: None,
146             record_field_syntax: None,
147             impl_def: None,
148             active_parameter: ActiveParameter::at(db, position),
149             is_param: false,
150             is_pat_binding_or_const: false,
151             is_irrefutable_pat_binding: false,
152             is_trivial_path: false,
153             path_qual: None,
154             after_if: false,
155             can_be_stmt: false,
156             is_expr: false,
157             is_new_item: false,
158             dot_receiver: None,
159             dot_receiver_is_ambiguous_float_literal: false,
160             is_call: false,
161             is_pattern_call: false,
162             is_macro_call: false,
163             is_path_type: false,
164             has_type_args: false,
165             attribute_under_caret: None,
166             mod_declaration_under_caret: None,
167             unsafe_is_prev: false,
168             if_is_prev: false,
169             block_expr_parent: false,
170             bind_pat_parent: false,
171             ref_pat_parent: false,
172             in_loop_body: false,
173             has_trait_parent: false,
174             has_impl_parent: false,
175             inside_impl_trait_block: false,
176             has_field_list_parent: false,
177             trait_as_prev_sibling: false,
178             impl_as_prev_sibling: false,
179             is_match_arm: false,
180             has_item_list_or_source_file_parent: false,
181             for_is_prev2: false,
182             fn_is_prev: false,
183             incomplete_let: false,
184             locals,
185         };
186
187         let mut original_file = original_file.syntax().clone();
188         let mut hypothetical_file = file_with_fake_ident.syntax().clone();
189         let mut offset = position.offset;
190         let mut fake_ident_token = fake_ident_token;
191
192         // Are we inside a macro call?
193         while let (Some(actual_macro_call), Some(macro_call_with_fake_ident)) = (
194             find_node_at_offset::<ast::MacroCall>(&original_file, offset),
195             find_node_at_offset::<ast::MacroCall>(&hypothetical_file, offset),
196         ) {
197             if actual_macro_call.path().as_ref().map(|s| s.syntax().text())
198                 != macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text())
199             {
200                 break;
201             }
202             let hypothetical_args = match macro_call_with_fake_ident.token_tree() {
203                 Some(tt) => tt,
204                 None => break,
205             };
206             if let (Some(actual_expansion), Some(hypothetical_expansion)) = (
207                 ctx.sema.expand(&actual_macro_call),
208                 ctx.sema.speculative_expand(
209                     &actual_macro_call,
210                     &hypothetical_args,
211                     fake_ident_token,
212                 ),
213             ) {
214                 let new_offset = hypothetical_expansion.1.text_range().start();
215                 if new_offset > actual_expansion.text_range().end() {
216                     break;
217                 }
218                 original_file = actual_expansion;
219                 hypothetical_file = hypothetical_expansion.0;
220                 fake_ident_token = hypothetical_expansion.1;
221                 offset = new_offset;
222             } else {
223                 break;
224             }
225         }
226         ctx.fill_keyword_patterns(&hypothetical_file, offset);
227         ctx.fill(&original_file, hypothetical_file, offset);
228         Some(ctx)
229     }
230
231     /// Checks whether completions in that particular case don't make much sense.
232     /// Examples:
233     /// - `fn $0` -- we expect function name, it's unlikely that "hint" will be helpful.
234     ///   Exception for this case is `impl Trait for Foo`, where we would like to hint trait method names.
235     /// - `for _ i$0` -- obviously, it'll be "in" keyword.
236     pub(crate) fn no_completion_required(&self) -> bool {
237         (self.fn_is_prev && !self.inside_impl_trait_block) || self.for_is_prev2
238     }
239
240     /// The range of the identifier that is being completed.
241     pub(crate) fn source_range(&self) -> TextRange {
242         // check kind of macro-expanded token, but use range of original token
243         let kind = self.token.kind();
244         if kind == IDENT || kind == UNDERSCORE || kind.is_keyword() {
245             cov_mark::hit!(completes_if_prefix_is_keyword);
246             self.original_token.text_range()
247         } else {
248             TextRange::empty(self.position.offset)
249         }
250     }
251
252     fn fill_keyword_patterns(&mut self, file_with_fake_ident: &SyntaxNode, offset: TextSize) {
253         let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
254         let syntax_element = NodeOrToken::Token(fake_ident_token);
255         self.block_expr_parent = has_block_expr_parent(syntax_element.clone());
256         self.unsafe_is_prev = unsafe_is_prev(syntax_element.clone());
257         self.if_is_prev = if_is_prev(syntax_element.clone());
258         self.bind_pat_parent = has_bind_pat_parent(syntax_element.clone());
259         self.ref_pat_parent = has_ref_parent(syntax_element.clone());
260         self.in_loop_body = is_in_loop_body(syntax_element.clone());
261         self.has_trait_parent = has_trait_parent(syntax_element.clone());
262         self.has_impl_parent = has_impl_parent(syntax_element.clone());
263         self.inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
264         self.has_field_list_parent = has_field_list_parent(syntax_element.clone());
265         self.impl_as_prev_sibling = has_impl_as_prev_sibling(syntax_element.clone());
266         self.trait_as_prev_sibling = has_trait_as_prev_sibling(syntax_element.clone());
267         self.is_match_arm = is_match_arm(syntax_element.clone());
268         self.has_item_list_or_source_file_parent =
269             has_item_list_or_source_file_parent(syntax_element.clone());
270         self.mod_declaration_under_caret =
271             find_node_at_offset::<ast::Module>(&file_with_fake_ident, offset)
272                 .filter(|module| module.item_list().is_none());
273         self.for_is_prev2 = for_is_prev2(syntax_element.clone());
274         self.fn_is_prev = fn_is_prev(syntax_element.clone());
275         self.incomplete_let =
276             syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
277                 it.syntax().text_range().end() == syntax_element.text_range().end()
278             });
279     }
280
281     fn fill_impl_def(&mut self) {
282         self.impl_def = self
283             .sema
284             .ancestors_with_macros(self.token.parent())
285             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
286             .find_map(ast::Impl::cast);
287     }
288
289     fn fill(
290         &mut self,
291         original_file: &SyntaxNode,
292         file_with_fake_ident: SyntaxNode,
293         offset: TextSize,
294     ) {
295         let expected = {
296             let mut node = self.token.parent();
297             loop {
298                 let ret = match_ast! {
299                     match node {
300                         ast::LetStmt(it) => {
301                             cov_mark::hit!(expected_type_let_with_leading_char);
302                             cov_mark::hit!(expected_type_let_without_leading_char);
303                             let ty = it.pat()
304                                 .and_then(|pat| self.sema.type_of_pat(&pat));
305                             let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
306                                 Some(ident.syntax().text().to_string())
307                             } else {
308                                 None
309                             };
310
311                             (ty, name)
312                         },
313                         ast::ArgList(it) => {
314                             cov_mark::hit!(expected_type_fn_param_with_leading_char);
315                             cov_mark::hit!(expected_type_fn_param_without_leading_char);
316                             ActiveParameter::at_token(
317                                 &self.sema,
318                                 self.token.clone(),
319                             ).map(|ap| (Some(ap.ty), Some(ap.name)))
320                             .unwrap_or((None, None))
321                         },
322                         ast::RecordExprFieldList(it) => {
323                             cov_mark::hit!(expected_type_struct_field_without_leading_char);
324                             self.token.prev_sibling_or_token()
325                                 .and_then(|se| se.into_node())
326                                 .and_then(|node| ast::RecordExprField::cast(node))
327                                 .and_then(|rf| self.sema.resolve_record_field(&rf))
328                                 .map(|f|(
329                                     Some(f.0.signature_ty(self.db)),
330                                     Some(f.0.name(self.db).to_string()),
331                                 ))
332                                 .unwrap_or((None, None))
333                         },
334                         ast::RecordExprField(it) => {
335                             cov_mark::hit!(expected_type_struct_field_with_leading_char);
336                             self.sema
337                                 .resolve_record_field(&it)
338                                 .map(|f|(
339                                     Some(f.0.signature_ty(self.db)),
340                                     Some(f.0.name(self.db).to_string()),
341                                 ))
342                                 .unwrap_or((None, None))
343                         },
344                         ast::MatchExpr(it) => {
345                             cov_mark::hit!(expected_type_match_arm_without_leading_char);
346                             let ty = it.expr()
347                                 .and_then(|e| self.sema.type_of_expr(&e));
348
349                             (ty, None)
350                         },
351                         ast::IdentPat(it) => {
352                             cov_mark::hit!(expected_type_if_let_with_leading_char);
353                             cov_mark::hit!(expected_type_if_let_without_leading_char);
354                             cov_mark::hit!(expected_type_match_arm_with_leading_char);
355                             let ty = self.sema.type_of_pat(&ast::Pat::from(it));
356
357                             (ty, None)
358                         },
359                         ast::Fn(it) => {
360                             cov_mark::hit!(expected_type_fn_ret_with_leading_char);
361                             cov_mark::hit!(expected_type_fn_ret_without_leading_char);
362                             let ty = self.token.ancestors()
363                                 .find_map(|ancestor| ast::Expr::cast(ancestor))
364                                 .and_then(|expr| self.sema.type_of_expr(&expr));
365
366                             (ty, None)
367                         },
368                         _ => {
369                             match node.parent() {
370                                 Some(n) => {
371                                     node = n;
372                                     continue;
373                                 },
374                                 None => (None, None),
375                             }
376                         },
377                     }
378                 };
379
380                 break ret;
381             }
382         };
383         self.expected_type = expected.0;
384         self.expected_name = expected.1;
385         self.attribute_under_caret = find_node_at_offset(&file_with_fake_ident, offset);
386
387         // First, let's try to complete a reference to some declaration.
388         if let Some(name_ref) = find_node_at_offset::<ast::NameRef>(&file_with_fake_ident, offset) {
389             // Special case, `trait T { fn foo(i_am_a_name_ref) {} }`.
390             // See RFC#1685.
391             if is_node::<ast::Param>(name_ref.syntax()) {
392                 self.is_param = true;
393                 return;
394             }
395             // FIXME: remove this (V) duplication and make the check more precise
396             if name_ref.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
397                 self.record_pat_syntax =
398                     self.sema.find_node_at_offset_with_macros(&original_file, offset);
399             }
400             self.classify_name_ref(original_file, name_ref, offset);
401         }
402
403         // Otherwise, see if this is a declaration. We can use heuristics to
404         // suggest declaration names, see `CompletionKind::Magic`.
405         if let Some(name) = find_node_at_offset::<ast::Name>(&file_with_fake_ident, offset) {
406             if let Some(bind_pat) = name.syntax().ancestors().find_map(ast::IdentPat::cast) {
407                 self.is_pat_binding_or_const = true;
408                 if bind_pat.at_token().is_some()
409                     || bind_pat.ref_token().is_some()
410                     || bind_pat.mut_token().is_some()
411                 {
412                     self.is_pat_binding_or_const = false;
413                 }
414                 if bind_pat.syntax().parent().and_then(ast::RecordPatFieldList::cast).is_some() {
415                     self.is_pat_binding_or_const = false;
416                 }
417                 if let Some(Some(pat)) = bind_pat.syntax().ancestors().find_map(|node| {
418                     match_ast! {
419                         match node {
420                             ast::LetStmt(it) => Some(it.pat()),
421                             ast::Param(it) => Some(it.pat()),
422                             _ => None,
423                         }
424                     }
425                 }) {
426                     if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range()) {
427                         self.is_pat_binding_or_const = false;
428                         self.is_irrefutable_pat_binding = true;
429                     }
430                 }
431
432                 self.fill_impl_def();
433             }
434             if is_node::<ast::Param>(name.syntax()) {
435                 self.is_param = true;
436                 return;
437             }
438             // FIXME: remove this (^) duplication and make the check more precise
439             if name.syntax().ancestors().find_map(ast::RecordPatFieldList::cast).is_some() {
440                 self.record_pat_syntax =
441                     self.sema.find_node_at_offset_with_macros(&original_file, offset);
442             }
443         }
444     }
445
446     fn classify_name_ref(
447         &mut self,
448         original_file: &SyntaxNode,
449         name_ref: ast::NameRef,
450         offset: TextSize,
451     ) {
452         self.name_ref_syntax =
453             find_node_at_offset(&original_file, name_ref.syntax().text_range().start());
454         let name_range = name_ref.syntax().text_range();
455         if ast::RecordExprField::for_field_name(&name_ref).is_some() {
456             self.record_lit_syntax =
457                 self.sema.find_node_at_offset_with_macros(&original_file, offset);
458         }
459
460         self.fill_impl_def();
461
462         let top_node = name_ref
463             .syntax()
464             .ancestors()
465             .take_while(|it| it.text_range() == name_range)
466             .last()
467             .unwrap();
468
469         match top_node.parent().map(|it| it.kind()) {
470             Some(SOURCE_FILE) | Some(ITEM_LIST) => {
471                 self.is_new_item = true;
472                 return;
473             }
474             _ => (),
475         }
476
477         self.use_item_syntax =
478             self.sema.ancestors_with_macros(self.token.parent()).find_map(ast::Use::cast);
479
480         self.function_syntax = self
481             .sema
482             .ancestors_with_macros(self.token.parent())
483             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
484             .find_map(ast::Fn::cast);
485
486         self.record_field_syntax = self
487             .sema
488             .ancestors_with_macros(self.token.parent())
489             .take_while(|it| {
490                 it.kind() != SOURCE_FILE && it.kind() != MODULE && it.kind() != CALL_EXPR
491             })
492             .find_map(ast::RecordExprField::cast);
493
494         let parent = match name_ref.syntax().parent() {
495             Some(it) => it,
496             None => return,
497         };
498
499         if let Some(segment) = ast::PathSegment::cast(parent.clone()) {
500             let path = segment.parent_path();
501             self.is_call = path
502                 .syntax()
503                 .parent()
504                 .and_then(ast::PathExpr::cast)
505                 .and_then(|it| it.syntax().parent().and_then(ast::CallExpr::cast))
506                 .is_some();
507             self.is_macro_call = path.syntax().parent().and_then(ast::MacroCall::cast).is_some();
508             self.is_pattern_call =
509                 path.syntax().parent().and_then(ast::TupleStructPat::cast).is_some();
510
511             self.is_path_type = path.syntax().parent().and_then(ast::PathType::cast).is_some();
512             self.has_type_args = segment.generic_arg_list().is_some();
513
514             if let Some(path) = path_or_use_tree_qualifier(&path) {
515                 self.path_qual = path
516                     .segment()
517                     .and_then(|it| {
518                         find_node_with_range::<ast::PathSegment>(
519                             original_file,
520                             it.syntax().text_range(),
521                         )
522                     })
523                     .map(|it| it.parent_path());
524                 return;
525             }
526
527             if let Some(segment) = path.segment() {
528                 if segment.coloncolon_token().is_some() {
529                     return;
530                 }
531             }
532
533             self.is_trivial_path = true;
534
535             // Find either enclosing expr statement (thing with `;`) or a
536             // block. If block, check that we are the last expr.
537             self.can_be_stmt = name_ref
538                 .syntax()
539                 .ancestors()
540                 .find_map(|node| {
541                     if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
542                         return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
543                     }
544                     if let Some(block) = ast::BlockExpr::cast(node) {
545                         return Some(
546                             block.tail_expr().map(|e| e.syntax().text_range())
547                                 == Some(name_ref.syntax().text_range()),
548                         );
549                     }
550                     None
551                 })
552                 .unwrap_or(false);
553             self.is_expr = path.syntax().parent().and_then(ast::PathExpr::cast).is_some();
554
555             if let Some(off) = name_ref.syntax().text_range().start().checked_sub(2.into()) {
556                 if let Some(if_expr) =
557                     self.sema.find_node_at_offset_with_macros::<ast::IfExpr>(original_file, off)
558                 {
559                     if if_expr.syntax().text_range().end() < name_ref.syntax().text_range().start()
560                     {
561                         self.after_if = true;
562                     }
563                 }
564             }
565         }
566         if let Some(field_expr) = ast::FieldExpr::cast(parent.clone()) {
567             // The receiver comes before the point of insertion of the fake
568             // ident, so it should have the same range in the non-modified file
569             self.dot_receiver = field_expr
570                 .expr()
571                 .map(|e| e.syntax().text_range())
572                 .and_then(|r| find_node_with_range(original_file, r));
573             self.dot_receiver_is_ambiguous_float_literal =
574                 if let Some(ast::Expr::Literal(l)) = &self.dot_receiver {
575                     match l.kind() {
576                         ast::LiteralKind::FloatNumber { .. } => l.token().text().ends_with('.'),
577                         _ => false,
578                     }
579                 } else {
580                     false
581                 };
582         }
583         if let Some(method_call_expr) = ast::MethodCallExpr::cast(parent) {
584             // As above
585             self.dot_receiver = method_call_expr
586                 .receiver()
587                 .map(|e| e.syntax().text_range())
588                 .and_then(|r| find_node_with_range(original_file, r));
589             self.is_call = true;
590         }
591     }
592 }
593
594 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
595     syntax.covering_element(range).ancestors().find_map(N::cast)
596 }
597
598 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
599     match node.ancestors().find_map(N::cast) {
600         None => false,
601         Some(n) => n.syntax().text_range() == node.text_range(),
602     }
603 }
604
605 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<ast::Path> {
606     if let Some(qual) = path.qualifier() {
607         return Some(qual);
608     }
609     let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
610     let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
611     use_tree.path()
612 }
613
614 #[cfg(test)]
615 mod tests {
616     use expect_test::{expect, Expect};
617     use hir::HirDisplay;
618
619     use crate::test_utils::{position, TEST_CONFIG};
620
621     use super::CompletionContext;
622
623     fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
624         let (db, pos) = position(ra_fixture);
625         let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
626
627         let ty = completion_context
628             .expected_type
629             .map(|t| t.display_test(&db).to_string())
630             .unwrap_or("?".to_owned());
631
632         let name = completion_context.expected_name.unwrap_or("?".to_owned());
633
634         expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
635     }
636
637     #[test]
638     fn expected_type_let_without_leading_char() {
639         cov_mark::check!(expected_type_let_without_leading_char);
640         check_expected_type_and_name(
641             r#"
642 fn foo() {
643     let x: u32 = $0;
644 }
645 "#,
646             expect![[r#"ty: u32, name: x"#]],
647         );
648     }
649
650     #[test]
651     fn expected_type_let_with_leading_char() {
652         cov_mark::check!(expected_type_let_with_leading_char);
653         check_expected_type_and_name(
654             r#"
655 fn foo() {
656     let x: u32 = c$0;
657 }
658 "#,
659             expect![[r#"ty: u32, name: x"#]],
660         );
661     }
662
663     #[test]
664     fn expected_type_fn_param_without_leading_char() {
665         cov_mark::check!(expected_type_fn_param_without_leading_char);
666         check_expected_type_and_name(
667             r#"
668 fn foo() {
669     bar($0);
670 }
671
672 fn bar(x: u32) {}
673 "#,
674             expect![[r#"ty: u32, name: x"#]],
675         );
676     }
677
678     #[test]
679     fn expected_type_fn_param_with_leading_char() {
680         cov_mark::check!(expected_type_fn_param_with_leading_char);
681         check_expected_type_and_name(
682             r#"
683 fn foo() {
684     bar(c$0);
685 }
686
687 fn bar(x: u32) {}
688 "#,
689             expect![[r#"ty: u32, name: x"#]],
690         );
691     }
692
693     #[test]
694     fn expected_type_struct_field_without_leading_char() {
695         cov_mark::check!(expected_type_struct_field_without_leading_char);
696         check_expected_type_and_name(
697             r#"
698 struct Foo { a: u32 }
699 fn foo() {
700     Foo { a: $0 };
701 }
702 "#,
703             expect![[r#"ty: u32, name: a"#]],
704         )
705     }
706
707     #[test]
708     fn expected_type_struct_field_with_leading_char() {
709         cov_mark::check!(expected_type_struct_field_with_leading_char);
710         check_expected_type_and_name(
711             r#"
712 struct Foo { a: u32 }
713 fn foo() {
714     Foo { a: c$0 };
715 }
716 "#,
717             expect![[r#"ty: u32, name: a"#]],
718         );
719     }
720
721     #[test]
722     fn expected_type_match_arm_without_leading_char() {
723         cov_mark::check!(expected_type_match_arm_without_leading_char);
724         check_expected_type_and_name(
725             r#"
726 enum E { X }
727 fn foo() {
728    match E::X { $0 }
729 }
730 "#,
731             expect![[r#"ty: E, name: ?"#]],
732         );
733     }
734
735     #[test]
736     fn expected_type_match_arm_with_leading_char() {
737         cov_mark::check!(expected_type_match_arm_with_leading_char);
738         check_expected_type_and_name(
739             r#"
740 enum E { X }
741 fn foo() {
742    match E::X { c$0 }
743 }
744 "#,
745             expect![[r#"ty: E, name: ?"#]],
746         );
747     }
748
749     #[test]
750     fn expected_type_if_let_without_leading_char() {
751         cov_mark::check!(expected_type_if_let_without_leading_char);
752         check_expected_type_and_name(
753             r#"
754 enum Foo { Bar, Baz, Quux }
755
756 fn foo() {
757     let f = Foo::Quux;
758     if let $0 = f { }
759 }
760 "#,
761             expect![[r#"ty: (), name: ?"#]],
762         ) // FIXME should be `ty: u32, name: ?`
763     }
764
765     #[test]
766     fn expected_type_if_let_with_leading_char() {
767         cov_mark::check!(expected_type_if_let_with_leading_char);
768         check_expected_type_and_name(
769             r#"
770 enum Foo { Bar, Baz, Quux }
771
772 fn foo() {
773     let f = Foo::Quux;
774     if let c$0 = f { }
775 }
776 "#,
777             expect![[r#"ty: Foo, name: ?"#]],
778         )
779     }
780
781     #[test]
782     fn expected_type_fn_ret_without_leading_char() {
783         cov_mark::check!(expected_type_fn_ret_without_leading_char);
784         check_expected_type_and_name(
785             r#"
786 fn foo() -> u32 {
787     $0
788 }
789 "#,
790             expect![[r#"ty: (), name: ?"#]],
791         ) // FIXME this should be `ty: u32, name: ?`
792     }
793
794     #[test]
795     fn expected_type_fn_ret_with_leading_char() {
796         cov_mark::check!(expected_type_fn_ret_with_leading_char);
797         check_expected_type_and_name(
798             r#"
799 fn foo() -> u32 {
800     c$0
801 }
802 "#,
803             expect![[r#"ty: u32, name: ?"#]],
804         )
805     }
806 }