]> git.lizzy.rs Git - rust.git/blob - crates/ide_completion/src/context.rs
Merge #9681
[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 is_non_trivial_path(&self) -> bool {
357         matches!(self.path_context, Some(PathCompletionContext { is_trivial_path: false, .. }))
358     }
359
360     pub(crate) fn path_qual(&self) -> Option<&ast::Path> {
361         self.path_context.as_ref().and_then(|it| it.qualifier.as_ref())
362     }
363
364     /// Checks if an item is visible and not `doc(hidden)` at the completion site.
365     pub(crate) fn is_visible<I>(&self, item: &I) -> bool
366     where
367         I: hir::HasVisibility + hir::HasAttrs + hir::HasCrate + Copy,
368     {
369         self.is_visible_impl(&item.visibility(self.db), &item.attrs(self.db), item.krate(self.db))
370     }
371
372     fn is_visible_impl(
373         &self,
374         vis: &hir::Visibility,
375         attrs: &hir::Attrs,
376         defining_crate: hir::Crate,
377     ) -> bool {
378         let module = match self.scope.module() {
379             Some(it) => it,
380             None => return false,
381         };
382         if !vis.is_visible_from(self.db, module.into()) {
383             // FIXME: if the definition location is editable, also show private items
384             return false;
385         }
386
387         if module.krate() != defining_crate && attrs.has_doc_hidden() {
388             // `doc(hidden)` items are only completed within the defining crate.
389             return false;
390         }
391
392         true
393     }
394
395     fn fill_impl_def(&mut self) {
396         self.impl_def = self
397             .sema
398             .token_ancestors_with_macros(self.token.clone())
399             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
400             .find_map(ast::Impl::cast);
401     }
402
403     fn expected_type_and_name(&self) -> (Option<Type>, Option<NameOrNameRef>) {
404         let mut node = match self.token.parent() {
405             Some(it) => it,
406             None => return (None, None),
407         };
408         loop {
409             break match_ast! {
410                 match node {
411                     ast::LetStmt(it) => {
412                         cov_mark::hit!(expected_type_let_with_leading_char);
413                         cov_mark::hit!(expected_type_let_without_leading_char);
414                         let ty = it.pat()
415                             .and_then(|pat| self.sema.type_of_pat(&pat))
416                             .or_else(|| it.initializer().and_then(|it| self.sema.type_of_expr(&it)));
417                         let name = if let Some(ast::Pat::IdentPat(ident)) = it.pat() {
418                             ident.name().map(NameOrNameRef::Name)
419                         } else {
420                             None
421                         };
422
423                         (ty, name)
424                     },
425                     ast::ArgList(_it) => {
426                         cov_mark::hit!(expected_type_fn_param);
427                         ActiveParameter::at_token(
428                             &self.sema,
429                             self.token.clone(),
430                         ).map(|ap| {
431                             let name = ap.ident().map(NameOrNameRef::Name);
432                             let ty = if has_ref(&self.token) {
433                                 cov_mark::hit!(expected_type_fn_param_ref);
434                                 ap.ty.remove_ref()
435                             } else {
436                                 Some(ap.ty)
437                             };
438                             (ty, name)
439                         })
440                         .unwrap_or((None, None))
441                     },
442                     ast::RecordExprFieldList(_it) => {
443                         cov_mark::hit!(expected_type_struct_field_without_leading_char);
444                         // wouldn't try {} be nice...
445                         (|| {
446                             let expr_field = self.token.prev_sibling_or_token()?
447                                       .into_node()
448                                       .and_then(ast::RecordExprField::cast)?;
449                             let (_, _, ty) = self.sema.resolve_record_field(&expr_field)?;
450                             Some((
451                                 Some(ty),
452                                 expr_field.field_name().map(NameOrNameRef::NameRef),
453                             ))
454                         })().unwrap_or((None, None))
455                     },
456                     ast::RecordExprField(it) => {
457                         cov_mark::hit!(expected_type_struct_field_with_leading_char);
458                         (
459                             it.expr().as_ref().and_then(|e| self.sema.type_of_expr(e)),
460                             it.field_name().map(NameOrNameRef::NameRef),
461                         )
462                     },
463                     ast::MatchExpr(it) => {
464                         cov_mark::hit!(expected_type_match_arm_without_leading_char);
465                         let ty = it.expr()
466                             .and_then(|e| self.sema.type_of_expr(&e));
467                         (ty, None)
468                     },
469                     ast::IfExpr(it) => {
470                         cov_mark::hit!(expected_type_if_let_without_leading_char);
471                         let ty = it.condition()
472                             .and_then(|cond| cond.expr())
473                             .and_then(|e| self.sema.type_of_expr(&e));
474                         (ty, None)
475                     },
476                     ast::IdentPat(it) => {
477                         cov_mark::hit!(expected_type_if_let_with_leading_char);
478                         cov_mark::hit!(expected_type_match_arm_with_leading_char);
479                         let ty = self.sema.type_of_pat(&ast::Pat::from(it));
480                         (ty, None)
481                     },
482                     ast::Fn(it) => {
483                         cov_mark::hit!(expected_type_fn_ret_with_leading_char);
484                         cov_mark::hit!(expected_type_fn_ret_without_leading_char);
485                         let def = self.sema.to_def(&it);
486                         (def.map(|def| def.ret_type(self.db)), None)
487                     },
488                     ast::ClosureExpr(it) => {
489                         let ty = self.sema.type_of_expr(&it.into());
490                         ty.and_then(|ty| ty.as_callable(self.db))
491                             .map(|c| (Some(c.return_type()), None))
492                             .unwrap_or((None, None))
493                     },
494                     ast::Stmt(_it) => (None, None),
495                     _ => {
496                         match node.parent() {
497                             Some(n) => {
498                                 node = n;
499                                 continue;
500                             },
501                             None => (None, None),
502                         }
503                     },
504                 }
505             };
506         }
507     }
508
509     fn fill(
510         &mut self,
511         original_file: &SyntaxNode,
512         file_with_fake_ident: SyntaxNode,
513         offset: TextSize,
514     ) {
515         let fake_ident_token = file_with_fake_ident.token_at_offset(offset).right_biased().unwrap();
516         let syntax_element = NodeOrToken::Token(fake_ident_token);
517         self.previous_token = previous_token(syntax_element.clone());
518         self.attribute_under_caret = syntax_element.ancestors().find_map(ast::Attr::cast);
519         self.no_completion_required = {
520             let inside_impl_trait_block = inside_impl_trait_block(syntax_element.clone());
521             let fn_is_prev = self.previous_token_is(T![fn]);
522             let for_is_prev2 = for_is_prev2(syntax_element.clone());
523             (fn_is_prev && !inside_impl_trait_block) || for_is_prev2
524         };
525
526         self.incomplete_let =
527             syntax_element.ancestors().take(6).find_map(ast::LetStmt::cast).map_or(false, |it| {
528                 it.syntax().text_range().end() == syntax_element.text_range().end()
529             });
530
531         let (expected_type, expected_name) = self.expected_type_and_name();
532         self.expected_type = expected_type;
533         self.expected_name = expected_name;
534
535         let name_like = match find_node_at_offset(&file_with_fake_ident, offset) {
536             Some(it) => it,
537             None => return,
538         };
539         self.completion_location =
540             determine_location(&self.sema, original_file, offset, &name_like);
541         self.prev_sibling = determine_prev_sibling(&name_like);
542         match name_like {
543             ast::NameLike::Lifetime(lifetime) => {
544                 self.classify_lifetime(original_file, lifetime, offset);
545             }
546             ast::NameLike::NameRef(name_ref) => {
547                 self.classify_name_ref(original_file, name_ref);
548             }
549             ast::NameLike::Name(name) => {
550                 self.classify_name(name);
551             }
552         }
553     }
554
555     fn classify_lifetime(
556         &mut self,
557         original_file: &SyntaxNode,
558         lifetime: ast::Lifetime,
559         offset: TextSize,
560     ) {
561         self.lifetime_syntax =
562             find_node_at_offset(original_file, lifetime.syntax().text_range().start());
563         if let Some(parent) = lifetime.syntax().parent() {
564             if parent.kind() == ERROR {
565                 return;
566             }
567
568             match_ast! {
569                 match parent {
570                     ast::LifetimeParam(_it) => {
571                         self.lifetime_allowed = true;
572                         self.lifetime_param_syntax =
573                             self.sema.find_node_at_offset_with_macros(original_file, offset);
574                     },
575                     ast::BreakExpr(_it) => self.is_label_ref = true,
576                     ast::ContinueExpr(_it) => self.is_label_ref = true,
577                     ast::Label(_it) => (),
578                     _ => self.lifetime_allowed = true,
579                 }
580             }
581         }
582     }
583
584     fn classify_name(&mut self, name: ast::Name) {
585         if let Some(bind_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) {
586             self.is_pat_or_const = Some(PatternRefutability::Refutable);
587             // if any of these is here our bind pat can't be a const pat anymore
588             let complex_ident_pat = bind_pat.at_token().is_some()
589                 || bind_pat.ref_token().is_some()
590                 || bind_pat.mut_token().is_some();
591             if complex_ident_pat {
592                 self.is_pat_or_const = None;
593             } else {
594                 let irrefutable_pat = bind_pat.syntax().ancestors().find_map(|node| {
595                     match_ast! {
596                         match node {
597                             ast::LetStmt(it) => Some(it.pat()),
598                             ast::Param(it) => Some(it.pat()),
599                             _ => None,
600                         }
601                     }
602                 });
603                 if let Some(Some(pat)) = irrefutable_pat {
604                     // This check is here since we could be inside a pattern in the initializer expression of the let statement.
605                     if pat.syntax().text_range().contains_range(bind_pat.syntax().text_range()) {
606                         self.is_pat_or_const = Some(PatternRefutability::Irrefutable);
607                     }
608                 }
609
610                 let is_name_in_field_pat = bind_pat
611                     .syntax()
612                     .parent()
613                     .and_then(ast::RecordPatField::cast)
614                     .map_or(false, |pat_field| pat_field.name_ref().is_none());
615                 if is_name_in_field_pat {
616                     self.is_pat_or_const = None;
617                 }
618             }
619
620             self.fill_impl_def();
621         }
622
623         self.is_param |= is_node::<ast::Param>(name.syntax());
624     }
625
626     fn classify_name_ref(&mut self, original_file: &SyntaxNode, name_ref: ast::NameRef) {
627         self.fill_impl_def();
628
629         self.name_ref_syntax =
630             find_node_at_offset(original_file, name_ref.syntax().text_range().start());
631
632         self.function_def = self
633             .sema
634             .token_ancestors_with_macros(self.token.clone())
635             .take_while(|it| it.kind() != SOURCE_FILE && it.kind() != MODULE)
636             .find_map(ast::Fn::cast);
637
638         let parent = match name_ref.syntax().parent() {
639             Some(it) => it,
640             None => return,
641         };
642
643         if let Some(segment) = ast::PathSegment::cast(parent) {
644             let path_ctx = self.path_context.get_or_insert(PathCompletionContext {
645                 call_kind: None,
646                 is_trivial_path: false,
647                 qualifier: None,
648                 has_type_args: false,
649                 can_be_stmt: false,
650                 in_loop_body: false,
651                 use_tree_parent: false,
652                 kind: None,
653             });
654             path_ctx.in_loop_body = is_in_loop_body(name_ref.syntax());
655             let path = segment.parent_path();
656
657             if let Some(p) = path.syntax().parent() {
658                 path_ctx.call_kind = match_ast! {
659                     match p {
660                         ast::PathExpr(it) => it.syntax().parent().and_then(ast::CallExpr::cast).map(|_| CallKind::Expr),
661                         ast::MacroCall(it) => it.excl_token().and(Some(CallKind::Mac)),
662                         ast::TupleStructPat(_it) => Some(CallKind::Pat),
663                         _ => None
664                     }
665                 };
666             }
667
668             if let Some(parent) = path.syntax().parent() {
669                 path_ctx.kind = match_ast! {
670                     match parent {
671                         ast::PathType(_it) => Some(PathKind::Type),
672                         ast::PathExpr(_it) => Some(PathKind::Expr),
673                         _ => None,
674                     }
675                 };
676             }
677             path_ctx.has_type_args = segment.generic_arg_list().is_some();
678
679             if let Some((path, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
680                 path_ctx.use_tree_parent = use_tree_parent;
681                 path_ctx.qualifier = path
682                     .segment()
683                     .and_then(|it| {
684                         find_node_with_range::<ast::PathSegment>(
685                             original_file,
686                             it.syntax().text_range(),
687                         )
688                     })
689                     .map(|it| it.parent_path());
690                 return;
691             }
692
693             if let Some(segment) = path.segment() {
694                 if segment.coloncolon_token().is_some() {
695                     return;
696                 }
697             }
698
699             path_ctx.is_trivial_path = true;
700
701             // Find either enclosing expr statement (thing with `;`) or a
702             // block. If block, check that we are the last expr.
703             path_ctx.can_be_stmt = name_ref
704                 .syntax()
705                 .ancestors()
706                 .find_map(|node| {
707                     if let Some(stmt) = ast::ExprStmt::cast(node.clone()) {
708                         return Some(stmt.syntax().text_range() == name_ref.syntax().text_range());
709                     }
710                     if let Some(block) = ast::BlockExpr::cast(node) {
711                         return Some(
712                             block.tail_expr().map(|e| e.syntax().text_range())
713                                 == Some(name_ref.syntax().text_range()),
714                         );
715                     }
716                     None
717                 })
718                 .unwrap_or(false);
719         }
720     }
721 }
722
723 fn find_node_with_range<N: AstNode>(syntax: &SyntaxNode, range: TextRange) -> Option<N> {
724     syntax.covering_element(range).ancestors().find_map(N::cast)
725 }
726
727 fn is_node<N: AstNode>(node: &SyntaxNode) -> bool {
728     match node.ancestors().find_map(N::cast) {
729         None => false,
730         Some(n) => n.syntax().text_range() == node.text_range(),
731     }
732 }
733
734 fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
735     if let Some(qual) = path.qualifier() {
736         return Some((qual, false));
737     }
738     let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
739     let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
740     use_tree.path().zip(Some(true))
741 }
742
743 fn has_ref(token: &SyntaxToken) -> bool {
744     let mut token = token.clone();
745     for skip in [WHITESPACE, IDENT, T![mut]] {
746         if token.kind() == skip {
747             token = match token.prev_token() {
748                 Some(it) => it,
749                 None => return false,
750             }
751         }
752     }
753     token.kind() == T![&]
754 }
755
756 #[cfg(test)]
757 mod tests {
758     use expect_test::{expect, Expect};
759     use hir::HirDisplay;
760
761     use crate::tests::{position, TEST_CONFIG};
762
763     use super::CompletionContext;
764
765     fn check_expected_type_and_name(ra_fixture: &str, expect: Expect) {
766         let (db, pos) = position(ra_fixture);
767         let completion_context = CompletionContext::new(&db, pos, &TEST_CONFIG).unwrap();
768
769         let ty = completion_context
770             .expected_type
771             .map(|t| t.display_test(&db).to_string())
772             .unwrap_or("?".to_owned());
773
774         let name = completion_context
775             .expected_name
776             .map_or_else(|| "?".to_owned(), |name| name.to_string());
777
778         expect.assert_eq(&format!("ty: {}, name: {}", ty, name));
779     }
780
781     #[test]
782     fn expected_type_let_without_leading_char() {
783         cov_mark::check!(expected_type_let_without_leading_char);
784         check_expected_type_and_name(
785             r#"
786 fn foo() {
787     let x: u32 = $0;
788 }
789 "#,
790             expect![[r#"ty: u32, name: x"#]],
791         );
792     }
793
794     #[test]
795     fn expected_type_let_with_leading_char() {
796         cov_mark::check!(expected_type_let_with_leading_char);
797         check_expected_type_and_name(
798             r#"
799 fn foo() {
800     let x: u32 = c$0;
801 }
802 "#,
803             expect![[r#"ty: u32, name: x"#]],
804         );
805     }
806
807     #[test]
808     fn expected_type_let_pat() {
809         check_expected_type_and_name(
810             r#"
811 fn foo() {
812     let x$0 = 0u32;
813 }
814 "#,
815             expect![[r#"ty: u32, name: ?"#]],
816         );
817         check_expected_type_and_name(
818             r#"
819 fn foo() {
820     let $0 = 0u32;
821 }
822 "#,
823             expect![[r#"ty: u32, name: ?"#]],
824         );
825     }
826
827     #[test]
828     fn expected_type_fn_param() {
829         cov_mark::check!(expected_type_fn_param);
830         check_expected_type_and_name(
831             r#"
832 fn foo() { bar($0); }
833 fn bar(x: u32) {}
834 "#,
835             expect![[r#"ty: u32, name: x"#]],
836         );
837         check_expected_type_and_name(
838             r#"
839 fn foo() { bar(c$0); }
840 fn bar(x: u32) {}
841 "#,
842             expect![[r#"ty: u32, name: x"#]],
843         );
844     }
845
846     #[test]
847     fn expected_type_fn_param_ref() {
848         cov_mark::check!(expected_type_fn_param_ref);
849         check_expected_type_and_name(
850             r#"
851 fn foo() { bar(&$0); }
852 fn bar(x: &u32) {}
853 "#,
854             expect![[r#"ty: u32, name: x"#]],
855         );
856         check_expected_type_and_name(
857             r#"
858 fn foo() { bar(&mut $0); }
859 fn bar(x: &mut u32) {}
860 "#,
861             expect![[r#"ty: u32, name: x"#]],
862         );
863         check_expected_type_and_name(
864             r#"
865 fn foo() { bar(&c$0); }
866 fn bar(x: &u32) {}
867         "#,
868             expect![[r#"ty: u32, name: x"#]],
869         );
870     }
871
872     #[test]
873     fn expected_type_struct_field_without_leading_char() {
874         cov_mark::check!(expected_type_struct_field_without_leading_char);
875         check_expected_type_and_name(
876             r#"
877 struct Foo { a: u32 }
878 fn foo() {
879     Foo { a: $0 };
880 }
881 "#,
882             expect![[r#"ty: u32, name: a"#]],
883         )
884     }
885
886     #[test]
887     fn expected_type_generic_struct_field() {
888         check_expected_type_and_name(
889             r#"
890 struct Foo<T> { a: T }
891 fn foo() -> Foo<u32> {
892     Foo { a: $0 }
893 }
894 "#,
895             expect![[r#"ty: u32, name: a"#]],
896         )
897     }
898
899     #[test]
900     fn expected_type_struct_field_with_leading_char() {
901         cov_mark::check!(expected_type_struct_field_with_leading_char);
902         check_expected_type_and_name(
903             r#"
904 struct Foo { a: u32 }
905 fn foo() {
906     Foo { a: c$0 };
907 }
908 "#,
909             expect![[r#"ty: u32, name: a"#]],
910         );
911     }
912
913     #[test]
914     fn expected_type_match_arm_without_leading_char() {
915         cov_mark::check!(expected_type_match_arm_without_leading_char);
916         check_expected_type_and_name(
917             r#"
918 enum E { X }
919 fn foo() {
920    match E::X { $0 }
921 }
922 "#,
923             expect![[r#"ty: E, name: ?"#]],
924         );
925     }
926
927     #[test]
928     fn expected_type_match_arm_with_leading_char() {
929         cov_mark::check!(expected_type_match_arm_with_leading_char);
930         check_expected_type_and_name(
931             r#"
932 enum E { X }
933 fn foo() {
934    match E::X { c$0 }
935 }
936 "#,
937             expect![[r#"ty: E, name: ?"#]],
938         );
939     }
940
941     #[test]
942     fn expected_type_if_let_without_leading_char() {
943         cov_mark::check!(expected_type_if_let_without_leading_char);
944         check_expected_type_and_name(
945             r#"
946 enum Foo { Bar, Baz, Quux }
947
948 fn foo() {
949     let f = Foo::Quux;
950     if let $0 = f { }
951 }
952 "#,
953             expect![[r#"ty: Foo, name: ?"#]],
954         )
955     }
956
957     #[test]
958     fn expected_type_if_let_with_leading_char() {
959         cov_mark::check!(expected_type_if_let_with_leading_char);
960         check_expected_type_and_name(
961             r#"
962 enum Foo { Bar, Baz, Quux }
963
964 fn foo() {
965     let f = Foo::Quux;
966     if let c$0 = f { }
967 }
968 "#,
969             expect![[r#"ty: Foo, name: ?"#]],
970         )
971     }
972
973     #[test]
974     fn expected_type_fn_ret_without_leading_char() {
975         cov_mark::check!(expected_type_fn_ret_without_leading_char);
976         check_expected_type_and_name(
977             r#"
978 fn foo() -> u32 {
979     $0
980 }
981 "#,
982             expect![[r#"ty: u32, name: ?"#]],
983         )
984     }
985
986     #[test]
987     fn expected_type_fn_ret_with_leading_char() {
988         cov_mark::check!(expected_type_fn_ret_with_leading_char);
989         check_expected_type_and_name(
990             r#"
991 fn foo() -> u32 {
992     c$0
993 }
994 "#,
995             expect![[r#"ty: u32, name: ?"#]],
996         )
997     }
998
999     #[test]
1000     fn expected_type_fn_ret_fn_ref_fully_typed() {
1001         check_expected_type_and_name(
1002             r#"
1003 fn foo() -> u32 {
1004     foo$0
1005 }
1006 "#,
1007             expect![[r#"ty: u32, name: ?"#]],
1008         )
1009     }
1010
1011     #[test]
1012     fn expected_type_closure_param_return() {
1013         // FIXME: make this work with `|| $0`
1014         check_expected_type_and_name(
1015             r#"
1016 //- minicore: fn
1017 fn foo() {
1018     bar(|| a$0);
1019 }
1020
1021 fn bar(f: impl FnOnce() -> u32) {}
1022 "#,
1023             expect![[r#"ty: u32, name: ?"#]],
1024         );
1025     }
1026
1027     #[test]
1028     fn expected_type_generic_function() {
1029         check_expected_type_and_name(
1030             r#"
1031 fn foo() {
1032     bar::<u32>($0);
1033 }
1034
1035 fn bar<T>(t: T) {}
1036 "#,
1037             expect![[r#"ty: u32, name: t"#]],
1038         );
1039     }
1040
1041     #[test]
1042     fn expected_type_generic_method() {
1043         check_expected_type_and_name(
1044             r#"
1045 fn foo() {
1046     S(1u32).bar($0);
1047 }
1048
1049 struct S<T>(T);
1050 impl<T> S<T> {
1051     fn bar(self, t: T) {}
1052 }
1053 "#,
1054             expect![[r#"ty: u32, name: t"#]],
1055         );
1056     }
1057 }