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