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