Skip to main content

ide_completion/context/
analysis.rs

1//! Module responsible for analyzing the code surrounding the cursor for completion.
2use std::iter;
3
4use hir::{EnumVariant, ExpandResult, InFile, Semantics, Type, TypeInfo};
5use ide_db::{
6    RootDatabase, active_parameter::ActiveParameter, syntax_helpers::node_ext::find_loops,
7};
8use itertools::{Either, Itertools};
9use stdx::always;
10use syntax::{
11    AstNode, AstToken, Direction, NodeOrToken, SyntaxElement, SyntaxKind, SyntaxNode, SyntaxToken,
12    T, TextRange, TextSize,
13    algo::{
14        self, ancestors_at_offset, find_node_at_offset, non_trivia_sibling,
15        previous_non_trivia_token,
16    },
17    ast::{
18        self, AttrKind, HasArgList, HasGenericArgs, HasGenericParams, HasLoopBody, HasName,
19        NameOrNameRef,
20    },
21    match_ast,
22};
23
24use crate::{
25    completions::postfix::{is_in_condition, is_in_value},
26    context::{
27        AttrCtx, BreakableKind, COMPLETION_MARKER, CompletionAnalysis, DotAccess, DotAccessExprCtx,
28        DotAccessKind, ItemListKind, LifetimeContext, LifetimeKind, NameContext, NameKind,
29        NameRefContext, NameRefKind, ParamContext, ParamKind, PathCompletionCtx, PathExprCtx,
30        PathKind, PatternContext, PatternRefutability, Qualified, QualifierCtx,
31        TypeAscriptionTarget, TypeLocation,
32    },
33};
34
35#[derive(Debug)]
36struct ExpansionResult {
37    original_file: SyntaxNode,
38    speculative_file: SyntaxNode,
39    /// The offset in the original file.
40    original_offset: TextSize,
41    /// The offset in the speculatively expanded file.
42    speculative_offset: TextSize,
43    fake_ident_token: SyntaxToken,
44    derive_ctx: Option<(SyntaxNode, SyntaxNode, TextSize, ast::Attr)>,
45}
46
47pub(super) struct AnalysisResult<'db> {
48    pub(super) analysis: CompletionAnalysis<'db>,
49    pub(super) expected: (Option<Type<'db>>, Option<ast::NameOrNameRef>),
50    pub(super) qualifier_ctx: QualifierCtx,
51    /// the original token of the expanded file
52    pub(super) token: SyntaxToken,
53    /// The offset in the original file.
54    pub(super) original_offset: TextSize,
55}
56
57pub(super) fn expand_and_analyze<'db>(
58    sema: &Semantics<'db, RootDatabase>,
59    original_file: InFile<SyntaxNode>,
60    speculative_file: SyntaxNode,
61    offset: TextSize,
62    original_token: &SyntaxToken,
63) -> Option<AnalysisResult<'db>> {
64    // as we insert after the offset, right biased will *always* pick the identifier no matter
65    // if there is an ident already typed or not
66    let fake_ident_token = speculative_file.token_at_offset(offset).right_biased()?;
67    // the relative offset between the cursor and the *identifier* token we are completing on
68    let relative_offset = offset - fake_ident_token.text_range().start();
69    // make the offset point to the start of the original token, as that is what the
70    // intermediate offsets calculated in expansion always points to
71    let offset = offset - relative_offset;
72    let expansion = expand_maybe_stop(
73        sema,
74        original_file.clone(),
75        speculative_file.clone(),
76        offset,
77        fake_ident_token.clone(),
78        relative_offset,
79    )
80    .unwrap_or(ExpansionResult {
81        original_file: original_file.value,
82        speculative_file,
83        original_offset: offset,
84        speculative_offset: fake_ident_token.text_range().start(),
85        fake_ident_token,
86        derive_ctx: None,
87    });
88
89    // add the relative offset back, so that left_biased finds the proper token
90    let original_offset = expansion.original_offset + relative_offset;
91    let token = expansion.original_file.token_at_offset(original_offset).left_biased()?;
92
93    analyze(sema, expansion, original_token, &token).map(|(analysis, expected, qualifier_ctx)| {
94        AnalysisResult { analysis, expected, qualifier_ctx, token, original_offset }
95    })
96}
97
98fn token_at_offset_ignore_whitespace(file: &SyntaxNode, offset: TextSize) -> Option<SyntaxToken> {
99    let token = file.token_at_offset(offset).left_biased()?;
100    algo::skip_whitespace_token(token, Direction::Prev)
101}
102
103/// Expand attributes and macro calls at the current cursor position for both the original file
104/// and fake file repeatedly. As soon as one of the two expansions fail we stop so the original
105/// and speculative states stay in sync.
106///
107/// We do this by recursively expanding all macros and picking the best possible match. We cannot just
108/// choose the first expansion each time because macros can expand to something that does not include
109/// our completion marker, e.g.:
110///
111/// ```ignore
112/// macro_rules! helper { ($v:ident) => {} }
113/// macro_rules! my_macro {
114///     ($v:ident) => {
115///         helper!($v);
116///         $v
117///     };
118/// }
119///
120/// my_macro!(complete_me_here);
121/// ```
122/// If we would expand the first thing we encounter only (which in fact this method used to do), we would
123/// be unable to complete here, because we would be walking directly into the void. So we instead try
124/// *every* possible path.
125///
126/// This can also creates discrepancies between the speculative and real expansions: because we insert
127/// tokens, we insert characters, which means if we try the second occurrence it may not be at the same
128/// position in the original and speculative file. We take an educated guess here, and for each token
129/// that we check, we subtract `COMPLETION_MARKER.len()`. This may not be accurate because proc macros
130/// can insert the text of the completion marker in other places while removing the span, but this is
131/// the best we can do.
132fn expand_maybe_stop(
133    sema: &Semantics<'_, RootDatabase>,
134    original_file: InFile<SyntaxNode>,
135    speculative_file: SyntaxNode,
136    original_offset: TextSize,
137    fake_ident_token: SyntaxToken,
138    relative_offset: TextSize,
139) -> Option<ExpansionResult> {
140    if let result @ Some(_) = expand(
141        sema,
142        original_file.clone(),
143        speculative_file.clone(),
144        original_offset,
145        fake_ident_token.clone(),
146        relative_offset,
147    ) {
148        return result;
149    }
150
151    // We can't check whether the fake expansion is inside macro call, because that requires semantic info.
152    // But hopefully checking just the real one should be enough.
153    if token_at_offset_ignore_whitespace(&original_file.value, original_offset + relative_offset)
154        .is_some_and(|original_token| {
155            !sema.is_inside_macro_call(original_file.with_value(&original_token))
156        })
157    {
158        // Recursion base case.
159        Some(ExpansionResult {
160            original_file: original_file.value,
161            speculative_file,
162            original_offset,
163            speculative_offset: fake_ident_token.text_range().start(),
164            fake_ident_token,
165            derive_ctx: None,
166        })
167    } else {
168        None
169    }
170}
171
172fn expand(
173    sema: &Semantics<'_, RootDatabase>,
174    original_file: InFile<SyntaxNode>,
175    speculative_file: SyntaxNode,
176    original_offset: TextSize,
177    fake_ident_token: SyntaxToken,
178    relative_offset: TextSize,
179) -> Option<ExpansionResult> {
180    let _p = tracing::info_span!("CompletionContext::expand").entered();
181
182    let parent_item =
183        |item: &ast::Item| item.syntax().ancestors().skip(1).find_map(ast::Item::cast);
184    let original_node = token_at_offset_ignore_whitespace(&original_file.value, original_offset)
185        .and_then(|token| token.parent_ancestors().find_map(ast::Item::cast));
186    let ancestor_items = iter::successors(
187        Option::zip(
188            original_node,
189            find_node_at_offset::<ast::Item>(
190                &speculative_file,
191                fake_ident_token.text_range().start(),
192            ),
193        ),
194        |(a, b)| parent_item(a).zip(parent_item(b)),
195    );
196
197    // first try to expand attributes as these are always the outermost macro calls
198    'ancestors: for (actual_item, item_with_fake_ident) in ancestor_items {
199        match (
200            sema.expand_attr_macro(&actual_item),
201            sema.speculative_expand_attr_macro(
202                &actual_item,
203                &item_with_fake_ident,
204                fake_ident_token.clone(),
205            ),
206        ) {
207            // maybe parent items have attributes, so continue walking the ancestors
208            (None, None) => continue 'ancestors,
209            // successful expansions
210            (
211                Some(ExpandResult { value: actual_expansion, err: _ }),
212                Some((fake_expansion, fake_mapped_tokens)),
213            ) => {
214                let mut accumulated_offset_from_fake_tokens = 0;
215                let actual_range = actual_expansion.text_range().end();
216                let result = fake_mapped_tokens
217                    .into_iter()
218                    .filter_map(|(fake_mapped_token, rank)| {
219                        let accumulated_offset = accumulated_offset_from_fake_tokens;
220                        if !fake_mapped_token.text().contains(COMPLETION_MARKER) {
221                            // Proc macros can make the same span with different text, we don't
222                            // want them to participate in completion because the macro author probably
223                            // didn't intend them to.
224                            return None;
225                        }
226                        accumulated_offset_from_fake_tokens += COMPLETION_MARKER.len();
227
228                        let new_offset = fake_mapped_token.text_range().start()
229                            - TextSize::new(accumulated_offset as u32);
230                        if new_offset + relative_offset > actual_range {
231                            // offset outside of bounds from the original expansion,
232                            // stop here to prevent problems from happening
233                            return None;
234                        }
235                        let result = expand_maybe_stop(
236                            sema,
237                            actual_expansion.clone(),
238                            fake_expansion.clone(),
239                            new_offset,
240                            fake_mapped_token,
241                            relative_offset,
242                        )?;
243                        Some((result, rank))
244                    })
245                    .min_by_key(|(_, rank)| *rank)
246                    .map(|(result, _)| result);
247                if result.is_some() {
248                    return result;
249                }
250            }
251            // exactly one expansion failed, inconsistent state so stop expanding completely
252            _ => break 'ancestors,
253        }
254    }
255
256    // No attributes have been expanded, so look for macro_call! token trees or derive token trees
257    let orig_tt = ancestors_at_offset(&original_file.value, original_offset)
258        .map_while(Either::<ast::TokenTree, ast::Meta>::cast)
259        .last()?;
260    let spec_tt = ancestors_at_offset(&speculative_file, fake_ident_token.text_range().start())
261        .map_while(Either::<ast::TokenTree, ast::Meta>::cast)
262        .last()?;
263
264    let (tts, attrs) = match (orig_tt, spec_tt) {
265        (Either::Left(orig_tt), Either::Left(spec_tt)) => {
266            let attrs = orig_tt
267                .syntax()
268                .parent()
269                .and_then(ast::Meta::cast)
270                .and_then(|it| it.parent_attr())
271                .zip(
272                    spec_tt
273                        .syntax()
274                        .parent()
275                        .and_then(ast::Meta::cast)
276                        .and_then(|it| it.parent_attr()),
277                );
278            (Some((orig_tt, spec_tt)), attrs)
279        }
280        (Either::Right(orig_path), Either::Right(spec_path)) => {
281            (None, orig_path.parent_attr().zip(spec_path.parent_attr()))
282        }
283        _ => return None,
284    };
285
286    // Expand pseudo-derive expansion aka `derive(Debug$0)`
287    if let Some((orig_attr, spec_attr)) = attrs
288        && let Some(orig_meta) = orig_attr.meta()
289    {
290        // FIXME: Support speculative expansion with `cfg_attr`.
291        if let (Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) = (
292            sema.expand_derive_as_pseudo_attr_macro(&orig_meta),
293            sema.speculative_expand_derive_as_pseudo_attr_macro(
294                &orig_attr,
295                &spec_attr,
296                fake_ident_token.clone(),
297            ),
298        ) && let Some((fake_mapped_token, _)) =
299            fake_mapped_tokens.into_iter().min_by_key(|(_, rank)| *rank)
300        {
301            return Some(ExpansionResult {
302                original_file: original_file.value,
303                speculative_file,
304                original_offset,
305                speculative_offset: fake_ident_token.text_range().start(),
306                fake_ident_token,
307                derive_ctx: Some((
308                    actual_expansion,
309                    fake_expansion,
310                    fake_mapped_token.text_range().start(),
311                    orig_attr,
312                )),
313            });
314        }
315
316        if let Some(spec_adt) =
317            spec_attr.syntax().ancestors().find_map(ast::Item::cast).and_then(|it| match it {
318                ast::Item::Struct(it) => Some(ast::Adt::Struct(it)),
319                ast::Item::Enum(it) => Some(ast::Adt::Enum(it)),
320                ast::Item::Union(it) => Some(ast::Adt::Union(it)),
321                _ => None,
322            })
323        {
324            // might be the path of derive helper or a token tree inside of one
325            if let Some(helpers) = sema.derive_helper(&orig_attr) {
326                for (_mac, file) in helpers {
327                    if let Some((fake_expansion, fake_mapped_tokens)) = sema.speculative_expand_raw(
328                        file,
329                        spec_adt.syntax(),
330                        fake_ident_token.clone(),
331                    ) {
332                        // we are inside a derive helper token tree, treat this as being inside
333                        // the derive expansion
334                        let actual_expansion = sema.parse_or_expand(file.into());
335                        let mut accumulated_offset_from_fake_tokens = 0;
336                        let actual_range = actual_expansion.text_range().end();
337                        let result = fake_mapped_tokens
338                            .into_iter()
339                            .filter_map(|(fake_mapped_token, rank)| {
340                                let accumulated_offset = accumulated_offset_from_fake_tokens;
341                                if !fake_mapped_token.text().contains(COMPLETION_MARKER) {
342                                    // Proc macros can make the same span with different text, we don't
343                                    // want them to participate in completion because the macro author probably
344                                    // didn't intend them to.
345                                    return None;
346                                }
347                                accumulated_offset_from_fake_tokens += COMPLETION_MARKER.len();
348
349                                let new_offset = fake_mapped_token.text_range().start()
350                                    - TextSize::new(accumulated_offset as u32);
351                                if new_offset + relative_offset > actual_range {
352                                    // offset outside of bounds from the original expansion,
353                                    // stop here to prevent problems from happening
354                                    return None;
355                                }
356                                let result = expand_maybe_stop(
357                                    sema,
358                                    InFile::new(file.into(), actual_expansion.clone()),
359                                    fake_expansion.clone(),
360                                    new_offset,
361                                    fake_mapped_token,
362                                    relative_offset,
363                                )?;
364                                Some((result, rank))
365                            })
366                            .min_by_key(|(_, rank)| *rank)
367                            .map(|(result, _)| result);
368                        if result.is_some() {
369                            return result;
370                        }
371                    }
372                }
373            }
374        }
375        // at this point we won't have any more successful expansions, so stop
376        return None;
377    }
378
379    // Expand fn-like macro calls
380    let (orig_tt, spec_tt) = tts?;
381    let (actual_macro_call, macro_call_with_fake_ident) = (
382        orig_tt.syntax().parent().and_then(ast::MacroCall::cast)?,
383        spec_tt.syntax().parent().and_then(ast::MacroCall::cast)?,
384    );
385    let mac_call_path0 = actual_macro_call.path().as_ref().map(|s| s.syntax().text());
386    let mac_call_path1 = macro_call_with_fake_ident.path().as_ref().map(|s| s.syntax().text());
387
388    // inconsistent state, stop expanding
389    if mac_call_path0 != mac_call_path1 {
390        return None;
391    }
392    let speculative_args = macro_call_with_fake_ident.token_tree()?;
393
394    match (
395        sema.expand_macro_call(&actual_macro_call),
396        sema.speculative_expand_macro_call(&actual_macro_call, &speculative_args, fake_ident_token),
397    ) {
398        // successful expansions
399        (Some(actual_expansion), Some((fake_expansion, fake_mapped_tokens))) => {
400            let mut accumulated_offset_from_fake_tokens = 0;
401            let actual_range = actual_expansion.text_range().end();
402            fake_mapped_tokens
403                .into_iter()
404                .filter_map(|(fake_mapped_token, rank)| {
405                    let accumulated_offset = accumulated_offset_from_fake_tokens;
406                    if !fake_mapped_token.text().contains(COMPLETION_MARKER) {
407                        // Proc macros can make the same span with different text, we don't
408                        // want them to participate in completion because the macro author probably
409                        // didn't intend them to.
410                        return None;
411                    }
412                    accumulated_offset_from_fake_tokens += COMPLETION_MARKER.len();
413
414                    let new_offset = fake_mapped_token.text_range().start()
415                        - TextSize::new(accumulated_offset as u32);
416                    if new_offset + relative_offset > actual_range {
417                        // offset outside of bounds from the original expansion,
418                        // stop here to prevent problems from happening
419                        return None;
420                    }
421                    let result = expand_maybe_stop(
422                        sema,
423                        actual_expansion.clone(),
424                        fake_expansion.clone(),
425                        new_offset,
426                        fake_mapped_token,
427                        relative_offset,
428                    )?;
429                    Some((result, rank))
430                })
431                .min_by_key(|(_, rank)| *rank)
432                .map(|(result, _)| result)
433        }
434        // at least one expansion failed, we won't have anything to expand from this point
435        // onwards so break out
436        _ => None,
437    }
438}
439
440/// Fill the completion context, this is what does semantic reasoning about the surrounding context
441/// of the completion location.
442fn analyze<'db>(
443    sema: &Semantics<'db, RootDatabase>,
444    expansion_result: ExpansionResult,
445    original_token: &SyntaxToken,
446    self_token: &SyntaxToken,
447) -> Option<(CompletionAnalysis<'db>, (Option<Type<'db>>, Option<ast::NameOrNameRef>), QualifierCtx)>
448{
449    let _p = tracing::info_span!("CompletionContext::analyze").entered();
450    let ExpansionResult {
451        original_file,
452        speculative_file,
453        original_offset: _,
454        speculative_offset,
455        fake_ident_token,
456        derive_ctx,
457    } = expansion_result;
458
459    if original_token.kind() != self_token.kind()
460        // FIXME: This check can be removed once we use speculative database forking for completions
461        && !(original_token.kind().is_punct() || original_token.kind().is_trivia())
462        && !(SyntaxKind::is_any_identifier(original_token.kind())
463            && SyntaxKind::is_any_identifier(self_token.kind()))
464    {
465        return None;
466    }
467
468    // Overwrite the path kind for derives
469    if let Some((original_file, file_with_fake_ident, offset, origin_attr)) = derive_ctx
470        && let Some(origin_meta) = origin_attr.meta()
471    {
472        if let Some(ast::NameLike::NameRef(name_ref)) =
473            find_node_at_offset(&file_with_fake_ident, offset)
474        {
475            let parent = name_ref.syntax().parent()?;
476            let (mut nameref_ctx, _) =
477                classify_name_ref(sema, &original_file, name_ref, offset, parent)?;
478            if let NameRefKind::Path(path_ctx) = &mut nameref_ctx.kind {
479                path_ctx.kind = PathKind::Derive {
480                    existing_derives: sema
481                        .resolve_derive_macro(&origin_meta)
482                        .into_iter()
483                        .flatten()
484                        .flatten()
485                        .collect(),
486                };
487            }
488            return Some((
489                CompletionAnalysis::NameRef(nameref_ctx),
490                (None, None),
491                QualifierCtx::default(),
492            ));
493        }
494        return None;
495    }
496
497    let Some(name_like) = find_node_at_offset(&speculative_file, speculative_offset) else {
498        let analysis = if let Some(original) = ast::String::cast(original_token.clone()) {
499            CompletionAnalysis::String { original, expanded: ast::String::cast(self_token.clone()) }
500        } else {
501            // Fix up trailing whitespace problem
502            // #[attr(foo = $0
503            let token = syntax::algo::skip_trivia_token(self_token.clone(), Direction::Prev)?;
504            let p = token.parent()?;
505            if p.kind() == SyntaxKind::TOKEN_TREE
506                && p.ancestors().any(|it| it.kind() == SyntaxKind::TOKEN_TREE_META)
507            {
508                let colon_prefix = previous_non_trivia_token(self_token.clone())
509                    .is_some_and(|it| T![:] == it.kind());
510
511                CompletionAnalysis::UnexpandedAttrTT {
512                    fake_attribute_under_caret: fake_ident_token
513                        .parent_ancestors()
514                        .find_map(ast::TokenTreeMeta::cast),
515                    colon_prefix,
516                    extern_crate: p.ancestors().find_map(ast::ExternCrate::cast),
517                }
518            } else if p.kind() == SyntaxKind::TOKEN_TREE
519                && p.ancestors().any(|it| ast::Macro::can_cast(it.kind()))
520            {
521                if let Some([_ident, colon, _name, dollar]) = fake_ident_token
522                    .siblings_with_tokens(Direction::Prev)
523                    .filter(|it| !it.kind().is_trivia())
524                    .take(4)
525                    .collect_array()
526                    && dollar.kind() == T![$]
527                    && colon.kind() == T![:]
528                {
529                    CompletionAnalysis::MacroSegment
530                } else {
531                    return None;
532                }
533            } else if find_node_at_offset::<ast::CfgPredicate>(
534                &speculative_file,
535                speculative_offset,
536            )
537            .is_some()
538            {
539                CompletionAnalysis::CfgPredicate
540            } else {
541                return None;
542            }
543        };
544        return Some((analysis, (None, None), QualifierCtx::default()));
545    };
546
547    let expected = expected_type_and_name(sema, self_token, &name_like);
548    let mut qual_ctx = QualifierCtx::default();
549    let analysis = match name_like {
550        ast::NameLike::Lifetime(lifetime) => {
551            CompletionAnalysis::Lifetime(classify_lifetime(sema, &original_file, lifetime)?)
552        }
553        ast::NameLike::NameRef(name_ref) => {
554            let parent = name_ref.syntax().parent()?;
555            let (nameref_ctx, qualifier_ctx) = classify_name_ref(
556                sema,
557                &original_file,
558                name_ref,
559                expansion_result.original_offset,
560                parent,
561            )?;
562
563            if let NameRefContext {
564                kind:
565                    NameRefKind::Path(PathCompletionCtx { kind: PathKind::Expr { .. }, path, .. }, ..),
566                ..
567            } = &nameref_ctx
568                && is_in_token_of_for_loop(path)
569            {
570                // for pat $0
571                // there is nothing to complete here except `in` keyword
572                // don't bother populating the context
573                // Ideally this special casing wouldn't be needed, but the parser recovers
574                return None;
575            }
576
577            qual_ctx = qualifier_ctx;
578            CompletionAnalysis::NameRef(nameref_ctx)
579        }
580        ast::NameLike::Name(name) => {
581            let name_ctx = classify_name(sema, &original_file, name)?;
582            CompletionAnalysis::Name(name_ctx)
583        }
584    };
585    Some((analysis, expected, qual_ctx))
586}
587
588/// Calculate the expected type and name of the cursor position.
589fn expected_type_and_name<'db>(
590    sema: &Semantics<'db, RootDatabase>,
591    self_token: &SyntaxToken,
592    name_like: &ast::NameLike,
593) -> (Option<Type<'db>>, Option<NameOrNameRef>) {
594    let token = prev_special_biased_token_at_trivia(self_token.clone());
595    let mut node = match token.parent() {
596        Some(it) => it,
597        None => return (None, None),
598    };
599
600    let strip_refs = |mut ty: Type<'db>| match name_like {
601        ast::NameLike::NameRef(n) => {
602            let p = match n.syntax().parent() {
603                Some(it) => it,
604                None => return ty,
605            };
606            let top_syn = match_ast! {
607                match p {
608                    ast::FieldExpr(e) => e
609                        .syntax()
610                        .ancestors()
611                        .take_while(|it| ast::FieldExpr::can_cast(it.kind()))
612                        .last(),
613                    ast::PathSegment(e) => e
614                        .syntax()
615                        .ancestors()
616                        .skip(1)
617                        .take_while(|it| ast::Path::can_cast(it.kind()) || ast::PathExpr::can_cast(it.kind()))
618                        .find(|it| ast::PathExpr::can_cast(it.kind())),
619                    _ => None
620                }
621            };
622            let top_syn = match top_syn {
623                Some(it) => it,
624                None => return ty,
625            };
626            let refs_level = top_syn
627                .ancestors()
628                .skip(1)
629                .map_while(Either::<ast::RefExpr, ast::PrefixExpr>::cast)
630                .take_while(|it| match it {
631                    Either::Left(_) => true,
632                    Either::Right(prefix) => prefix.op_kind() == Some(ast::UnaryOp::Deref),
633                })
634                .fold(0i32, |level, expr| match expr {
635                    Either::Left(_) => level + 1,
636                    Either::Right(_) => level - 1,
637                });
638            for _ in 0..refs_level {
639                cov_mark::hit!(expected_type_fn_param_ref);
640                ty = ty.strip_reference();
641            }
642            for _ in refs_level..0 {
643                cov_mark::hit!(expected_type_fn_param_deref);
644                ty = ty.add_reference(sema.db, hir::Mutability::Shared);
645            }
646            ty
647        }
648        _ => ty,
649    };
650
651    let mut generic_def = None;
652    let mut rebase_ty = {
653        let node = node.clone();
654        move |ty: hir::Type<'db>| {
655            let def = *generic_def
656                .get_or_insert_with(|| sema.scope(&node).and_then(|scope| scope.generic_def()));
657            def.and_then(|def| ty.try_rebase_into_owner(sema.db, def))
658                .unwrap_or_else(|| ty.instantiate_with_errors())
659        }
660    };
661    let (ty, name) = loop {
662        break match_ast! {
663            match node {
664                ast::LetStmt(it) => {
665                    cov_mark::hit!(expected_type_let_with_leading_char);
666                    cov_mark::hit!(expected_type_let_without_leading_char);
667                    let ty = it.pat()
668                        .and_then(|pat| sema.type_of_pat(&pat))
669                        .or_else(|| it.initializer().and_then(|it| sema.type_of_expr(&it)))
670                        .map(TypeInfo::original)
671                        .filter(|ty| {
672                            // don't infer the let type if the expr is a function,
673                            // preventing parenthesis from vanishing
674                            it.ty().is_some() || !ty.is_fn()
675                        });
676                    let name = match it.pat() {
677                        Some(ast::Pat::IdentPat(ident)) => ident.name().map(NameOrNameRef::Name),
678                        Some(_) | None => None,
679                    };
680
681                    (ty, name)
682                },
683                ast::LetExpr(it) => {
684                    cov_mark::hit!(expected_type_if_let_without_leading_char);
685                    let ty = it.pat()
686                        .and_then(|pat| sema.type_of_pat(&pat))
687                        .or_else(|| it.expr().and_then(|it| sema.type_of_expr(&it)))
688                        .map(TypeInfo::original);
689                    (ty, None)
690                },
691                ast::BinExpr(it) => {
692                    if let Some(ast::BinaryOp::Assignment { op: None }) = it.op_kind() {
693                        let ty = it.lhs()
694                            .and_then(|lhs| sema.type_of_expr(&lhs))
695                            .or_else(|| it.rhs().and_then(|rhs| sema.type_of_expr(&rhs)))
696                            .map(TypeInfo::original);
697                        (ty, None)
698                    } else if let Some(ast::BinaryOp::LogicOp(_)) = it.op_kind() {
699                        let ty = sema.type_of_expr(&it.clone().into()).map(TypeInfo::original);
700                        (ty, None)
701                    } else {
702                        (None, None)
703                    }
704                },
705                ast::ArgList(_) => {
706                    cov_mark::hit!(expected_type_fn_param);
707                    ActiveParameter::at_token(
708                        sema,
709                        token.clone(),
710                    ).map(|ap| {
711                        let name = ap.ident().map(NameOrNameRef::Name);
712                        (Some(ap.ty), name)
713                    })
714                    .unwrap_or((None, None))
715                },
716                ast::RecordExprFieldList(it) => {
717                    // wouldn't try {} be nice...
718                    (|| {
719                        if token.kind() == T![..]
720                            ||token.prev_token().map(|t| t.kind()) == Some(T![..])
721                        {
722                            cov_mark::hit!(expected_type_struct_func_update);
723                            let record_expr = it.syntax().parent().and_then(ast::RecordExpr::cast)?;
724                            let ty = sema.type_of_expr(&record_expr.into())?;
725                            Some((
726                                Some(ty.original),
727                                None
728                            ))
729                        } else {
730                            cov_mark::hit!(expected_type_struct_field_without_leading_char);
731                            cov_mark::hit!(expected_type_struct_field_followed_by_comma);
732                            let expr_field = previous_non_trivia_token(token.clone())?.parent().and_then(ast::RecordExprField::cast)?;
733                            let (_, _, ty) = sema.resolve_record_field(&expr_field)?;
734                            Some((
735                                Some(ty),
736                                expr_field.field_name().map(NameOrNameRef::NameRef),
737                            ))
738                        }
739                    })().unwrap_or((None, None))
740                },
741                ast::RecordExprField(it) => {
742                    let field_ty = sema.resolve_record_field(&it).map(|(_, _, ty)| ty);
743                    let field_name = it.field_name().map(NameOrNameRef::NameRef);
744                    if let Some(expr) = it.expr() {
745                        cov_mark::hit!(expected_type_struct_field_with_leading_char);
746                        let ty = field_ty
747                            .or_else(|| sema.type_of_expr(&expr).map(TypeInfo::original));
748                        (ty, field_name)
749                    } else {
750                        (field_ty, field_name)
751                    }
752                },
753                // match foo { $0 }
754                // match foo { ..., pat => $0 }
755                ast::MatchExpr(it) => {
756                    let on_arrow = previous_non_trivia_token(token.clone()).is_some_and(|it| T![=>] == it.kind());
757
758                    let ty = if on_arrow {
759                        // match foo { ..., pat => $0 }
760                        cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
761                        cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
762                        sema.type_of_expr(&it.into())
763                    } else {
764                        // match foo { $0 }
765                        cov_mark::hit!(expected_type_match_arm_without_leading_char);
766                        it.expr().and_then(|e| sema.type_of_expr(&e))
767                    }.map(TypeInfo::original);
768                    (ty, None)
769                },
770                ast::MatchArm(it) => {
771                    let on_arrow = previous_non_trivia_token(token.clone()).is_some_and(|it| T![=>] == it.kind());
772                    let in_body = it.expr().is_some_and(|it| it.syntax().text_range().contains_range(token.text_range()));
773                    let match_expr = it.parent_match();
774
775                    let ty = if on_arrow || in_body {
776                        // match foo { ..., pat => $0 }
777                        cov_mark::hit!(expected_type_match_arm_body_without_leading_char);
778                        cov_mark::hit!(expected_type_match_arm_body_with_leading_char);
779                        sema.type_of_expr(&match_expr.into())
780                    } else {
781                        // match foo { $0 }
782                        cov_mark::hit!(expected_type_match_arm_without_leading_char);
783                        match_expr.expr().and_then(|e| sema.type_of_expr(&e))
784                    }.map(TypeInfo::original);
785                    (ty, None)
786                },
787                ast::IfExpr(it) => {
788                    let ty = if let Some(body) = it.then_branch()
789                        && token.text_range().end() > body.syntax().text_range().start()
790                    {
791                        sema.type_of_expr(&body.into())
792                    } else {
793                        it.condition().and_then(|e| sema.type_of_expr(&e))
794                    }.map(TypeInfo::original);
795                    (ty, None)
796                },
797                ast::IdentPat(it) => {
798                    cov_mark::hit!(expected_type_if_let_with_leading_char);
799                    cov_mark::hit!(expected_type_match_arm_with_leading_char);
800                    let ty = sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
801                    (ty, None)
802                },
803                ast::TupleStructPat(it) => {
804                    let fields = sema.resolve_tuple_struct_pat_fields(&it);
805                    let nr = it.fields().take_while(|it| it.syntax().text_range().end() <= token.text_range().start()).count();
806                    let ty = fields.and_then(|fields| Some(rebase_ty(fields.get(nr)?.1.clone())));
807                    (ty, None)
808                },
809                ast::Fn(it) => {
810                    cov_mark::hit!(expected_type_fn_ret_with_leading_char);
811                    cov_mark::hit!(expected_type_fn_ret_without_leading_char);
812                    let def = sema.to_def(&it);
813                    (def.map(|def| rebase_ty(def.ret_type(sema.db))), None)
814                },
815                ast::ReturnExpr(it) => {
816                    let fn_ = sema.ancestors_with_macros(it.syntax().clone())
817                        .find_map(Either::<ast::Fn, ast::ClosureExpr>::cast);
818                    let ty = fn_.and_then(|f| match f {
819                        Either::Left(f) => Some(rebase_ty(sema.to_def(&f)?.ret_type(sema.db))),
820                        Either::Right(f) => {
821                            let ty = sema.type_of_expr(&f.into())?.original.as_callable(sema.db)?;
822                            Some(ty.return_type())
823                        },
824                    });
825                    (ty, None)
826                },
827                ast::BreakExpr(it) => {
828                    let ty = it.break_token()
829                        .and_then(|it| find_loops(sema, &it)?.next())
830                        .and_then(|expr| sema.type_of_expr(&expr));
831                    (ty.map(TypeInfo::original), None)
832                },
833                ast::ClosureExpr(it) => {
834                    let ty = sema.type_of_expr(&it.into());
835                    ty.and_then(|ty| ty.original.as_callable(sema.db))
836                        .map(|c| (Some(c.return_type()), None))
837                        .unwrap_or((None, None))
838                },
839                ast::ParamList(it) => {
840                    let closure = it.syntax().parent().and_then(ast::ClosureExpr::cast);
841                    let ty = closure
842                        .filter(|_| it.syntax().text_range().end() <= self_token.text_range().start())
843                        .and_then(|it| sema.type_of_expr(&it.into()));
844                    ty.and_then(|ty| ty.original.as_callable(sema.db))
845                        .map(|c| (Some(c.return_type()), None))
846                        .unwrap_or((None, None))
847                },
848                ast::Variant(it) => {
849                    let is_simple_field = |field: ast::TupleField| {
850                        let Some(ty) = field.ty() else { return true };
851                        matches!(ty, ast::Type::PathType(_)) && ty.generic_arg_list().is_none()
852                    };
853                    let is_simple_variant = matches!(
854                        it.field_list(),
855                        Some(ast::FieldList::TupleFieldList(list))
856                        if list.syntax().children_with_tokens().all(|it| it.kind() != T![,])
857                            && list.fields().next().is_none_or(is_simple_field)
858                    );
859                    (None, it.name().filter(|_| is_simple_variant).map(NameOrNameRef::Name))
860                },
861                ast::Stmt(_) => (None, None),
862                ast::Item(_) => (None, None),
863                _ => {
864                    match node.parent() {
865                        Some(n) => {
866                            node = n;
867                            continue;
868                        },
869                        None => (None, None),
870                    }
871                },
872            }
873        };
874    };
875    (ty.map(strip_refs), name)
876}
877
878fn classify_lifetime(
879    sema: &Semantics<'_, RootDatabase>,
880    original_file: &SyntaxNode,
881    lifetime: ast::Lifetime,
882) -> Option<LifetimeContext> {
883    let parent = lifetime.syntax().parent()?;
884    if parent.kind() == SyntaxKind::ERROR {
885        return None;
886    }
887
888    let lifetime =
889        find_node_at_offset::<ast::Lifetime>(original_file, lifetime.syntax().text_range().start());
890    let kind = match_ast! {
891        match parent {
892            ast::LifetimeParam(_) => LifetimeKind::LifetimeParam,
893            ast::BreakExpr(_) => LifetimeKind::LabelRef,
894            ast::ContinueExpr(_) => LifetimeKind::LabelRef,
895            ast::Label(_) => LifetimeKind::LabelDef,
896            _ => {
897                let def = lifetime.as_ref().and_then(|lt| sema.scope(lt.syntax())?.generic_def());
898                LifetimeKind::Lifetime { in_lifetime_param_bound: ast::TypeBound::can_cast(parent.kind()), def }
899            },
900        }
901    };
902
903    Some(LifetimeContext { kind })
904}
905
906fn classify_name(
907    sema: &Semantics<'_, RootDatabase>,
908    original_file: &SyntaxNode,
909    name: ast::Name,
910) -> Option<NameContext> {
911    let parent = name.syntax().parent()?;
912    let kind = match_ast! {
913        match parent {
914            ast::Const(_) => NameKind::Const,
915            ast::ConstParam(_) => NameKind::ConstParam,
916            ast::Enum(_) => NameKind::Enum,
917            ast::Fn(_) => NameKind::Function,
918            ast::IdentPat(bind_pat) => {
919                let mut pat_ctx = pattern_context_for(sema, original_file, bind_pat.into());
920                if let Some(record_field) = ast::RecordPatField::for_field_name(&name) {
921                    pat_ctx.record_pat = find_node_in_file_compensated(sema, original_file, &record_field.parent_record_pat());
922                }
923
924                NameKind::IdentPat(pat_ctx)
925            },
926            ast::MacroDef(_) => NameKind::MacroDef,
927            ast::MacroRules(_) => NameKind::MacroRules,
928            ast::Module(module) => NameKind::Module(module),
929            ast::RecordField(_) => NameKind::RecordField,
930            ast::Rename(_) => NameKind::Rename,
931            ast::SelfParam(_) => NameKind::SelfParam,
932            ast::Static(_) => NameKind::Static,
933            ast::Struct(_) => NameKind::Struct,
934            ast::Trait(_) => NameKind::Trait,
935            ast::TypeAlias(_) => NameKind::TypeAlias,
936            ast::TypeParam(_) => NameKind::TypeParam,
937            ast::Union(_) => NameKind::Union,
938            ast::Variant(_) => NameKind::Variant,
939            _ => return None,
940        }
941    };
942    let name = find_node_at_offset(original_file, name.syntax().text_range().start());
943    Some(NameContext { name, kind })
944}
945
946fn classify_name_ref<'db>(
947    sema: &Semantics<'db, RootDatabase>,
948    original_file: &SyntaxNode,
949    name_ref: ast::NameRef,
950    original_offset: TextSize,
951    parent: SyntaxNode,
952) -> Option<(NameRefContext<'db>, QualifierCtx)> {
953    let nameref = find_node_at_offset(original_file, original_offset);
954
955    let make_res = |kind| (NameRefContext { nameref: nameref.clone(), kind }, Default::default());
956
957    if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
958        let dot_prefix = previous_non_trivia_token(name_ref.syntax().clone())
959            .is_some_and(|it| T![.] == it.kind());
960
961        return find_node_in_file_compensated(
962            sema,
963            original_file,
964            &record_field.parent_record_lit(),
965        )
966        .map(|expr| NameRefKind::RecordExpr { expr, dot_prefix })
967        .map(make_res);
968    }
969    if let Some(record_field) = ast::RecordPatField::for_field_name_ref(&name_ref) {
970        let kind = NameRefKind::Pattern(PatternContext {
971            param_ctx: None,
972            has_type_ascription: false,
973            ref_token: None,
974            mut_token: None,
975            record_pat: find_node_in_file_compensated(
976                sema,
977                original_file,
978                &record_field.parent_record_pat(),
979            ),
980            ..pattern_context_for(sema, original_file, record_field.parent_record_pat().into())
981        });
982        return Some(make_res(kind));
983    }
984
985    let field_expr_handle = |receiver, node| {
986        let receiver = find_opt_node_in_file(original_file, receiver);
987        let receiver_is_ambiguous_float_literal = match &receiver {
988            Some(ast::Expr::Literal(l)) => {
989                matches!(l.kind(), ast::LiteralKind::FloatNumber { .. })
990                    && l.syntax().last_token().is_some_and(|it| it.text().ends_with('.'))
991            }
992            _ => false,
993        };
994
995        let receiver_is_part_of_indivisible_expression = match &receiver {
996            Some(ast::Expr::IfExpr(_)) => {
997                let next_token_kind =
998                    next_non_trivia_token(name_ref.syntax().clone()).map(|t| t.kind());
999                next_token_kind == Some(SyntaxKind::ELSE_KW)
1000            }
1001            _ => false,
1002        };
1003        if receiver_is_part_of_indivisible_expression {
1004            return None;
1005        }
1006
1007        let mut receiver_ty = receiver.as_ref().and_then(|it| sema.type_of_expr(it));
1008        if receiver_is_ambiguous_float_literal {
1009            // `123.|` is parsed as a float but should actually be an integer.
1010            always!(receiver_ty.as_ref().is_none_or(|receiver_ty| receiver_ty.original.is_float()));
1011            receiver_ty =
1012                Some(TypeInfo { original: hir::BuiltinType::i32().ty(sema.db), adjusted: None });
1013        }
1014
1015        let kind = NameRefKind::DotAccess(DotAccess {
1016            receiver_ty,
1017            kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal },
1018            receiver,
1019            ctx: DotAccessExprCtx {
1020                in_block_expr: is_in_block(node),
1021                in_breakable: is_in_breakable(node).unzip().0,
1022            },
1023        });
1024        Some(make_res(kind))
1025    };
1026
1027    let segment = match_ast! {
1028        match parent {
1029            ast::PathSegment(segment) => segment,
1030            ast::FieldExpr(field) => {
1031                return field_expr_handle(field.expr(), field.syntax());
1032            },
1033            ast::ExternCrate(_) => {
1034                let kind = NameRefKind::ExternCrate;
1035                return Some(make_res(kind));
1036            },
1037            ast::MethodCallExpr(method) => {
1038                let receiver = find_opt_node_in_file(original_file, method.receiver());
1039                let has_parens = has_parens(&method);
1040                if !has_parens && let Some(res) = field_expr_handle(method.receiver(), method.syntax()) {
1041                    return Some(res)
1042                }
1043                let kind = NameRefKind::DotAccess(DotAccess {
1044                    receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1045                    kind: DotAccessKind::Method,
1046                    receiver,
1047                    ctx: DotAccessExprCtx { in_block_expr: is_in_block(method.syntax()), in_breakable: is_in_breakable(method.syntax()).unzip().0 }
1048                });
1049                return Some(make_res(kind));
1050            },
1051            _ => return None,
1052        }
1053    };
1054
1055    let path = segment.parent_path();
1056    let original_path = find_node_in_file_compensated(sema, original_file, &path);
1057
1058    let mut path_ctx = PathCompletionCtx {
1059        has_call_parens: false,
1060        has_macro_bang: false,
1061        qualified: Qualified::No,
1062        parent: None,
1063        path: path.clone(),
1064        original_path,
1065        kind: PathKind::Item { kind: ItemListKind::SourceFile },
1066        has_type_args: false,
1067        use_tree_parent: false,
1068    };
1069
1070    let func_update_record = |syn: &SyntaxNode| {
1071        if let Some(record_expr) = syn.ancestors().nth(2).and_then(ast::RecordExpr::cast) {
1072            find_node_in_file_compensated(sema, original_file, &record_expr)
1073        } else {
1074            None
1075        }
1076    };
1077    let prev_expr = |node: SyntaxNode| {
1078        let node = match node.parent().and_then(ast::ExprStmt::cast) {
1079            Some(stmt) => stmt.syntax().clone(),
1080            None => node,
1081        };
1082        let prev_sibling = non_trivia_sibling(node.into(), Direction::Prev)?.into_node()?;
1083
1084        match_ast! {
1085            match prev_sibling {
1086                ast::ExprStmt(stmt) => stmt.expr().filter(|_| stmt.semicolon_token().is_none()),
1087                ast::LetStmt(stmt) => stmt.initializer().filter(|_| stmt.semicolon_token().is_none()),
1088                ast::Expr(expr) => Some(expr),
1089                _ => None,
1090            }
1091        }
1092    };
1093    let after_incomplete_let = |node: SyntaxNode| {
1094        prev_expr(node).and_then(|it| it.syntax().parent()).and_then(ast::LetStmt::cast)
1095    };
1096    let before_else_kw = |node: &SyntaxNode| {
1097        node.parent()
1098            .and_then(ast::ExprStmt::cast)
1099            .filter(|stmt| stmt.semicolon_token().is_none())
1100            .and_then(|stmt| non_trivia_sibling(stmt.syntax().clone().into(), Direction::Next))
1101            .and_then(NodeOrToken::into_node)
1102            .filter(|next| next.kind() == SyntaxKind::ERROR)
1103            .and_then(|next| next.first_token())
1104            .is_some_and(|token| token.kind() == SyntaxKind::ELSE_KW)
1105    };
1106
1107    // We do not want to generate path completions when we are sandwiched between an item decl signature and its body.
1108    // ex. trait Foo $0 {}
1109    // in these cases parser recovery usually kicks in for our inserted identifier, causing it
1110    // to either be parsed as an ExprStmt or a ItemRecovery, depending on whether it is in a block
1111    // expression or an item list.
1112    // The following code checks if the body is missing, if it is we either cut off the body
1113    // from the item or it was missing in the first place
1114    let inbetween_body_and_decl_check = |node: SyntaxNode| {
1115        if let Some(NodeOrToken::Node(n)) =
1116            syntax::algo::non_trivia_sibling(node.into(), syntax::Direction::Prev)
1117            && let Some(item) = ast::Item::cast(n)
1118        {
1119            let is_inbetween = match &item {
1120                ast::Item::Const(it) => it.body().is_none() && it.semicolon_token().is_none(),
1121                ast::Item::Enum(it) => it.variant_list().is_none(),
1122                ast::Item::ExternBlock(it) => it.extern_item_list().is_none(),
1123                ast::Item::Fn(it) => it.body().is_none() && it.semicolon_token().is_none(),
1124                ast::Item::Impl(it) => it.assoc_item_list().is_none(),
1125                ast::Item::Module(it) => it.item_list().is_none() && it.semicolon_token().is_none(),
1126                ast::Item::Static(it) => it.body().is_none(),
1127                ast::Item::Struct(it) => {
1128                    it.field_list().is_none() && it.semicolon_token().is_none()
1129                }
1130                ast::Item::Trait(it) => it.assoc_item_list().is_none(),
1131                ast::Item::TypeAlias(it) => it.ty().is_none() && it.semicolon_token().is_none(),
1132                ast::Item::Union(it) => it.record_field_list().is_none(),
1133                _ => false,
1134            };
1135            if is_inbetween {
1136                return Some(item);
1137            }
1138        }
1139        None
1140    };
1141
1142    let generic_arg_location = |arg: ast::GenericArg| {
1143        let mut override_location = None;
1144        let location = find_opt_node_in_file_compensated(
1145            sema,
1146            original_file,
1147            arg.syntax().parent().and_then(ast::GenericArgList::cast),
1148        )
1149        .map(|args| {
1150            let mut in_trait = None;
1151            let param = (|| {
1152                let parent = args.syntax().parent()?;
1153                let params = match_ast! {
1154                    match parent {
1155                        ast::PathSegment(segment) => {
1156                            match sema.resolve_path(&segment.parent_path().top_path())? {
1157                                hir::PathResolution::Def(def) => match def {
1158                                    hir::ModuleDef::Function(func) => {
1159                                         sema.source(func)?.value.generic_param_list()
1160                                    }
1161                                    hir::ModuleDef::Adt(adt) => {
1162                                        sema.source(adt)?.value.generic_param_list()
1163                                    }
1164                                    hir::ModuleDef::EnumVariant(variant) => {
1165                                        sema.source(variant.parent_enum(sema.db))?.value.generic_param_list()
1166                                    }
1167                                    hir::ModuleDef::Trait(trait_) => {
1168                                        if let ast::GenericArg::AssocTypeArg(arg) = &arg {
1169                                            let arg_name = arg.name_ref()?;
1170                                            let arg_name = arg_name.text();
1171                                            for item in trait_.items_with_supertraits(sema.db) {
1172                                                match item {
1173                                                    hir::AssocItem::TypeAlias(assoc_ty)
1174                                                        if assoc_ty.name(sema.db).as_str() == arg_name => {
1175                                                            override_location = Some(TypeLocation::AssocTypeEq);
1176                                                            return None;
1177                                                        },
1178                                                    hir::AssocItem::Const(const_)
1179                                                        if const_.name(sema.db)?.as_str() == arg_name => {
1180                                                            override_location =  Some(TypeLocation::AssocConstEq);
1181                                                            return None;
1182                                                        },
1183                                                    _ => (),
1184                                                }
1185                                            }
1186                                            return None;
1187                                        } else {
1188                                            in_trait = Some(trait_);
1189                                            sema.source(trait_)?.value.generic_param_list()
1190                                        }
1191                                    }
1192                                    hir::ModuleDef::TypeAlias(ty_) => {
1193                                        sema.source(ty_)?.value.generic_param_list()
1194                                    }
1195                                    _ => None,
1196                                },
1197                                _ => None,
1198                            }
1199                        },
1200                        ast::MethodCallExpr(call) => {
1201                            let func = sema.resolve_method_call(&call)?;
1202                            sema.source(func)?.value.generic_param_list()
1203                        },
1204                        ast::AssocTypeArg(arg) => {
1205                            let trait_ = ast::PathSegment::cast(arg.syntax().parent()?.parent()?)?;
1206                            match sema.resolve_path(&trait_.parent_path().top_path())? {
1207                                hir::PathResolution::Def(hir::ModuleDef::Trait(trait_)) =>  {
1208                                        let arg_name = arg.name_ref()?;
1209                                        let arg_name = arg_name.text();
1210                                        let trait_items = trait_.items_with_supertraits(sema.db);
1211                                        let assoc_ty = trait_items.iter().find_map(|item| match item {
1212                                            hir::AssocItem::TypeAlias(assoc_ty) => {
1213                                                (assoc_ty.name(sema.db).as_str() == arg_name)
1214                                                    .then_some(assoc_ty)
1215                                            },
1216                                            _ => None,
1217                                        })?;
1218                                        sema.source(*assoc_ty)?.value.generic_param_list()
1219                                    }
1220                                _ => None,
1221                            }
1222                        },
1223                        _ => None,
1224                    }
1225                }?;
1226                // Determine the index of the argument in the `GenericArgList` and match it with
1227                // the corresponding parameter in the `GenericParamList`. Since lifetime parameters
1228                // are often omitted, ignore them for the purposes of matching the argument with
1229                // its parameter unless a lifetime argument is provided explicitly. That is, for
1230                // `struct S<'a, 'b, T>`, match `S::<$0>` to `T` and `S::<'a, $0, _>` to `'b`.
1231                // FIXME: This operates on the syntax tree and will produce incorrect results when
1232                // generic parameters are disabled by `#[cfg]` directives. It should operate on the
1233                // HIR, but the functionality necessary to do so is not exposed at the moment.
1234                let mut explicit_lifetime_arg = false;
1235                let arg_idx = arg
1236                    .syntax()
1237                    .siblings(Direction::Prev)
1238                    // Skip the node itself
1239                    .skip(1)
1240                    .map(|arg| if ast::LifetimeArg::can_cast(arg.kind()) { explicit_lifetime_arg = true })
1241                    .count();
1242                let param_idx = if explicit_lifetime_arg {
1243                    arg_idx
1244                } else {
1245                    // Lifetimes parameters always precede type and generic parameters,
1246                    // so offset the argument index by the total number of lifetime params
1247                    arg_idx + params.lifetime_params().count()
1248                };
1249                params.generic_params().nth(param_idx)
1250            })();
1251            (args, in_trait, param)
1252        });
1253        let (arg_list, of_trait, corresponding_param) = match location {
1254            Some((arg_list, of_trait, param)) => (Some(arg_list), of_trait, param),
1255            _ => (None, None, None),
1256        };
1257        override_location.unwrap_or(TypeLocation::GenericArg {
1258            args: arg_list,
1259            of_trait,
1260            corresponding_param,
1261        })
1262    };
1263
1264    let type_location = |node: &SyntaxNode| {
1265        let parent = node.parent()?;
1266        let res = match_ast! {
1267            match parent {
1268                ast::Const(it) => {
1269                    let name = find_opt_node_in_file(original_file, it.name())?;
1270                    let original = ast::Const::cast(name.syntax().parent()?)?;
1271                    TypeLocation::TypeAscription(TypeAscriptionTarget::Const(original.body()))
1272                },
1273                ast::Static(it) => {
1274                    let name = find_opt_node_in_file(original_file, it.name())?;
1275                    let original = ast::Static::cast(name.syntax().parent()?)?;
1276                    TypeLocation::TypeAscription(TypeAscriptionTarget::Const(original.body()))
1277                },
1278                ast::RetType(_) => {
1279                    let parent = match ast::Fn::cast(parent.parent()?) {
1280                        Some(it) => it.param_list(),
1281                        None => ast::ClosureExpr::cast(parent.parent()?)?.param_list(),
1282                    };
1283
1284                    let parent = find_opt_node_in_file(original_file, parent)?.syntax().parent()?;
1285                    let body = match_ast! {
1286                        match parent {
1287                            ast::ClosureExpr(it) => {
1288                                it.body()
1289                            },
1290                            ast::Fn(it) => {
1291                                it.body().map(ast::Expr::BlockExpr)
1292                            },
1293                            _ => return None,
1294                        }
1295                    };
1296                    let item = ast::Fn::cast(parent);
1297                    TypeLocation::TypeAscription(TypeAscriptionTarget::RetType { body, item })
1298                },
1299                ast::Param(it) => {
1300                    it.colon_token()?;
1301                    TypeLocation::TypeAscription(TypeAscriptionTarget::FnParam(find_opt_node_in_file(original_file, it.pat())))
1302                },
1303                ast::LetStmt(it) => {
1304                    it.colon_token()?;
1305                    TypeLocation::TypeAscription(TypeAscriptionTarget::Let(find_opt_node_in_file(original_file, it.pat())))
1306                },
1307                ast::Impl(it) => {
1308                    match it.trait_() {
1309                        Some(t) if t.syntax() == node => TypeLocation::ImplTrait,
1310                        _ => match it.self_ty() {
1311                            Some(t) if t.syntax() == node => TypeLocation::ImplTarget,
1312                            _ => return None,
1313                        },
1314                    }
1315                },
1316                ast::TypeBound(_) => TypeLocation::TypeBound,
1317                // is this case needed?
1318                ast::TypeBoundList(_) => TypeLocation::TypeBound,
1319                ast::GenericArg(it) => generic_arg_location(it),
1320                // is this case needed?
1321                ast::GenericArgList(it) => {
1322                    let args = find_opt_node_in_file_compensated(sema, original_file, Some(it));
1323                    TypeLocation::GenericArg { args, of_trait: None, corresponding_param: None }
1324                },
1325                ast::TupleField(_) => TypeLocation::TupleField,
1326                _ => return None,
1327            }
1328        };
1329        Some(res)
1330    };
1331
1332    let make_path_kind_expr = |expr: ast::Expr| {
1333        let it = expr.syntax();
1334        let prev_token = iter::successors(it.first_token(), |it| it.prev_token())
1335            .skip(1)
1336            .find(|it| !it.kind().is_trivia());
1337        let in_block_expr = is_in_block(it);
1338        let (in_loop_body, innermost_breakable) = is_in_breakable(it).unzip();
1339        let after_if_expr = is_after_if_expr(it.clone());
1340        let after_amp = prev_token.as_ref().is_some_and(|it| it.kind() == SyntaxKind::AMP);
1341        let ref_expr_parent = prev_token.and_then(|it| it.parent()).and_then(ast::RefExpr::cast);
1342        let (innermost_ret_ty, self_param) = {
1343            let find_ret_ty = |it: SyntaxNode| {
1344                if let Some(item) = ast::Item::cast(it.clone()) {
1345                    match item {
1346                        ast::Item::Fn(f) => Some(sema.to_def(&f).map(|it| it.ret_type(sema.db))),
1347                        ast::Item::MacroCall(_) => None,
1348                        _ => Some(None),
1349                    }
1350                } else {
1351                    let expr = ast::Expr::cast(it)?;
1352                    let callable = match expr {
1353                        // FIXME
1354                        // ast::Expr::BlockExpr(b) if b.async_token().is_some() || b.try_token().is_some() => sema.type_of_expr(b),
1355                        ast::Expr::ClosureExpr(_) => sema.type_of_expr(&expr),
1356                        _ => return None,
1357                    };
1358                    Some(
1359                        callable
1360                            .and_then(|c| c.adjusted().as_callable(sema.db))
1361                            .map(|it| it.return_type()),
1362                    )
1363                }
1364            };
1365            let fn_self_param =
1366                |fn_: ast::Fn| sema.to_def(&fn_).and_then(|it| it.self_param(sema.db));
1367            let closure_this_param = |closure: ast::ClosureExpr| {
1368                if closure.param_list()?.params().next()?.pat()?.syntax().text() != "this" {
1369                    return None;
1370                }
1371                sema.type_of_expr(&closure.into())
1372                    .and_then(|it| it.original.as_callable(sema.db))
1373                    .and_then(|it| it.params().into_iter().next())
1374            };
1375            let find_fn_self_param = |it: SyntaxNode| {
1376                match_ast! {
1377                    match it {
1378                        ast::Fn(fn_) => Some(fn_self_param(fn_).map(Either::Left)),
1379                        ast::ClosureExpr(f) => closure_this_param(f).map(Either::Right).map(Some),
1380                        ast::MacroCall(_) => None,
1381                        ast::Item(_) => Some(None),
1382                        _ => None,
1383                    }
1384                }
1385            };
1386
1387            match find_node_in_file_compensated(sema, original_file, &expr) {
1388                Some(it) => {
1389                    // buggy
1390                    let innermost_ret_ty = sema
1391                        .ancestors_with_macros(it.syntax().clone())
1392                        .find_map(find_ret_ty)
1393                        .flatten();
1394
1395                    let self_param = sema
1396                        .ancestors_with_macros(it.syntax().clone())
1397                        .find_map(find_fn_self_param)
1398                        .flatten();
1399                    (innermost_ret_ty, self_param)
1400                }
1401                None => (None, None),
1402            }
1403        };
1404        let innermost_breakable_ty = innermost_breakable
1405            .and_then(ast::Expr::cast)
1406            .and_then(|expr| find_node_in_file_compensated(sema, original_file, &expr))
1407            .and_then(|expr| sema.type_of_expr(&expr))
1408            .map(|ty| if ty.original.is_never() { ty.adjusted() } else { ty.original() });
1409        let is_func_update = func_update_record(it);
1410        let in_condition = is_in_condition(&expr);
1411        let after_incomplete_let = after_incomplete_let(it.clone()).is_some();
1412        let incomplete_expr_stmt =
1413            it.parent().and_then(ast::ExprStmt::cast).map(|it| it.semicolon_token().is_none());
1414        let before_else_kw = before_else_kw(it);
1415        let incomplete_let = left_ancestors(it.parent())
1416            .find_map(ast::LetStmt::cast)
1417            .is_some_and(|it| it.semicolon_token().is_none())
1418            || after_incomplete_let && incomplete_expr_stmt.unwrap_or(true) && !before_else_kw;
1419        let in_value = is_in_value(&expr);
1420        let impl_ = fetch_immediate_impl_or_trait(sema, original_file, expr.syntax())
1421            .and_then(Either::left);
1422
1423        let in_match_guard = match it.parent().and_then(ast::MatchArm::cast) {
1424            Some(arm) => arm
1425                .fat_arrow_token()
1426                .is_none_or(|arrow| it.text_range().start() < arrow.text_range().start()),
1427            None => false,
1428        };
1429
1430        PathKind::Expr {
1431            expr_ctx: PathExprCtx {
1432                in_block_expr,
1433                in_breakable: in_loop_body,
1434                after_if_expr,
1435                before_else_kw,
1436                in_condition,
1437                ref_expr_parent,
1438                after_amp,
1439                is_func_update,
1440                innermost_ret_ty,
1441                innermost_breakable_ty,
1442                self_param,
1443                in_value,
1444                incomplete_let,
1445                after_incomplete_let,
1446                impl_,
1447                in_match_guard,
1448            },
1449        }
1450    };
1451    let make_path_kind_type = |ty: ast::Type| {
1452        let location = type_location(ty.syntax());
1453        PathKind::Type { location: location.unwrap_or(TypeLocation::Other) }
1454    };
1455
1456    let kind_item = |it: &SyntaxNode| {
1457        let parent = it.parent()?;
1458        let kind = match_ast! {
1459            match parent {
1460                ast::ItemList(_) => PathKind::Item { kind: ItemListKind::Module },
1461                ast::AssocItemList(_) => PathKind::Item { kind: match parent.parent() {
1462                    Some(it) => match_ast! {
1463                        match it {
1464                            ast::Trait(_) => ItemListKind::Trait,
1465                            ast::Impl(it) => if it.trait_().is_some() {
1466                                ItemListKind::TraitImpl(find_node_in_file_compensated(sema, original_file, &it))
1467                            } else {
1468                                ItemListKind::Impl
1469                            },
1470                            _ => return None
1471                        }
1472                    },
1473                    None => return None,
1474                } },
1475                ast::ExternItemList(it) => {
1476                    let exn_blk = it.syntax().parent().and_then(ast::ExternBlock::cast);
1477                    PathKind::Item {
1478                        kind: ItemListKind::ExternBlock {
1479                            is_unsafe: exn_blk.and_then(|it| it.unsafe_token()).is_some(),
1480                        }
1481                    }
1482                },
1483                ast::SourceFile(_) => PathKind::Item { kind: ItemListKind::SourceFile },
1484                _ => return None,
1485            }
1486        };
1487        Some(kind)
1488    };
1489
1490    let mut kind_macro_call = |it: ast::MacroCall| {
1491        path_ctx.has_macro_bang = it.excl_token().is_some();
1492        let parent = it.syntax().parent()?;
1493        if let Some(kind) = kind_item(it.syntax()) {
1494            return Some(kind);
1495        }
1496        let kind = match_ast! {
1497            match parent {
1498                ast::MacroExpr(expr) => make_path_kind_expr(expr.into()),
1499                ast::MacroPat(it) => PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())},
1500                ast::MacroType(ty) => make_path_kind_type(ty.into()),
1501                _ => return None,
1502            }
1503        };
1504        Some(kind)
1505    };
1506    let make_path_kind_attr = |meta: ast::Meta| {
1507        let attr = meta.parent_attr()?;
1508        let kind = attr.kind();
1509        let attached = attr.syntax().parent()?;
1510        let is_trailing_outer_attr = kind != AttrKind::Inner
1511            && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1512        let annotated_item_kind = if is_trailing_outer_attr { None } else { Some(attached.kind()) };
1513        let derive_helpers = annotated_item_kind
1514            .filter(|kind| {
1515                matches!(
1516                    kind,
1517                    SyntaxKind::STRUCT
1518                        | SyntaxKind::ENUM
1519                        | SyntaxKind::UNION
1520                        | SyntaxKind::VARIANT
1521                        | SyntaxKind::TUPLE_FIELD
1522                        | SyntaxKind::RECORD_FIELD
1523                )
1524            })
1525            .and_then(|_| find_node_at_offset::<ast::Adt>(original_file, original_offset))
1526            .and_then(|adt| sema.derive_helpers_in_scope(&adt))
1527            .unwrap_or_default();
1528        Some(PathKind::Attr { attr_ctx: AttrCtx { kind, annotated_item_kind, derive_helpers } })
1529    };
1530
1531    // Infer the path kind
1532    let parent = path.syntax().parent()?;
1533    let kind = 'find_kind: {
1534        if parent.kind() == SyntaxKind::ERROR {
1535            if let Some(kind) = inbetween_body_and_decl_check(parent.clone()) {
1536                return Some(make_res(NameRefKind::Keyword(kind)));
1537            }
1538
1539            break 'find_kind kind_item(&parent)?;
1540        }
1541        match_ast! {
1542            match parent {
1543                ast::PathType(it) => make_path_kind_type(it.into()),
1544                ast::PathExpr(it) => {
1545                    if let Some(p) = it.syntax().parent() {
1546                        let p_kind = p.kind();
1547                        // The syntax node of interest, for which we want to check whether
1548                        // it is sandwiched between an item decl signature and its body.
1549                        let probe = if ast::ExprStmt::can_cast(p_kind) {
1550                            Some(p)
1551                        } else if ast::StmtList::can_cast(p_kind) {
1552                            Some(it.syntax().clone())
1553                        } else {
1554                            None
1555                        };
1556                        if let Some(kind) = probe.and_then(inbetween_body_and_decl_check) {
1557                            return Some(make_res(NameRefKind::Keyword(kind)));
1558                        }
1559                    }
1560
1561                    path_ctx.has_call_parens = it.syntax().parent().is_some_and(|it| ast::CallExpr::cast(it).is_some_and(|it| has_parens(&it)));
1562
1563                    make_path_kind_expr(it.into())
1564                },
1565                ast::TupleStructPat(it) => {
1566                    path_ctx.has_call_parens = true;
1567                    PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1568                },
1569                ast::RecordPat(it) => {
1570                    path_ctx.has_call_parens = true;
1571                    PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1572                },
1573                ast::PathPat(it) => {
1574                    PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())}
1575                },
1576                ast::MacroCall(it) => {
1577                    kind_macro_call(it)?
1578                },
1579                ast::Meta(meta) => make_path_kind_attr(meta)?,
1580                ast::VisibilityInner(it) => PathKind::Vis { has_in_token: it.in_token().is_some() },
1581                ast::UseTree(_) => PathKind::Use,
1582                // completing inside a qualifier
1583                ast::Path(parent) => {
1584                    path_ctx.parent = Some(parent.clone());
1585                    let parent = iter::successors(Some(parent), |it| it.parent_path()).last()?.syntax().parent()?;
1586                    match_ast! {
1587                        match parent {
1588                            ast::PathType(it) => make_path_kind_type(it.into()),
1589                            ast::PathExpr(it) => {
1590                                path_ctx.has_call_parens = it.syntax().parent().is_some_and(|it| ast::CallExpr::cast(it).is_some_and(|it| has_parens(&it)));
1591
1592                                make_path_kind_expr(it.into())
1593                            },
1594                            ast::TupleStructPat(it) => {
1595                                path_ctx.has_call_parens = true;
1596                                PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1597                            },
1598                            ast::RecordPat(it) => {
1599                                path_ctx.has_call_parens = true;
1600                                PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1601                            },
1602                            ast::PathPat(it) => {
1603                                PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())}
1604                            },
1605                            ast::MacroCall(it) => {
1606                                kind_macro_call(it)?
1607                            },
1608                            ast::Meta(meta) => make_path_kind_attr(meta)?,
1609                            ast::VisibilityInner(it) => PathKind::Vis { has_in_token: it.in_token().is_some() },
1610                            ast::UseTree(_) => PathKind::Use,
1611                            ast::RecordExpr(it) => make_path_kind_expr(it.into()),
1612                            _ => return None,
1613                        }
1614                    }
1615                },
1616                ast::RecordExpr(it) => {
1617                    // A record expression in this position is usually a result of parsing recovery, so check that
1618                    if let Some(kind) = inbetween_body_and_decl_check(it.syntax().clone()) {
1619                        return Some(make_res(NameRefKind::Keyword(kind)));
1620                    }
1621                    make_path_kind_expr(it.into())
1622                },
1623                _ => return None,
1624            }
1625        }
1626    };
1627
1628    path_ctx.kind = kind;
1629    path_ctx.has_type_args = segment.generic_arg_list().is_some();
1630
1631    // calculate the qualifier context
1632    if let Some((qualifier, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1633        path_ctx.use_tree_parent = use_tree_parent;
1634        if !use_tree_parent && segment.coloncolon_token().is_some() {
1635            path_ctx.qualified = Qualified::Absolute;
1636        } else {
1637            let qualifier = qualifier
1638                .segment()
1639                .and_then(|it| find_node_in_file(original_file, &it))
1640                .map(|it| it.parent_path());
1641            if let Some(qualifier) = qualifier {
1642                let type_anchor = match qualifier.segment().and_then(|it| it.kind()) {
1643                    Some(ast::PathSegmentKind::Type { type_ref: Some(type_ref), trait_ref })
1644                        if qualifier.qualifier().is_none() =>
1645                    {
1646                        Some((type_ref, trait_ref))
1647                    }
1648                    _ => None,
1649                };
1650
1651                path_ctx.qualified = if let Some((ty, trait_ref)) = type_anchor {
1652                    let ty = match ty {
1653                        ast::Type::InferType(_) => None,
1654                        ty => sema.resolve_type(&ty),
1655                    };
1656                    let trait_ = trait_ref.and_then(|it| sema.resolve_trait(&it.path()?));
1657                    Qualified::TypeAnchor { ty, trait_ }
1658                } else {
1659                    let res = sema.resolve_path(&qualifier);
1660
1661                    // For understanding how and why super_chain_len is calculated the way it
1662                    // is check the documentation at it's definition
1663                    let mut segment_count = 0;
1664                    let super_count = iter::successors(Some(qualifier.clone()), |p| p.qualifier())
1665                        .take_while(|p| {
1666                            p.segment()
1667                                .and_then(|s| {
1668                                    segment_count += 1;
1669                                    s.super_token()
1670                                })
1671                                .is_some()
1672                        })
1673                        .count();
1674
1675                    let super_chain_len =
1676                        if segment_count > super_count { None } else { Some(super_count) };
1677
1678                    Qualified::With { path: qualifier, resolution: res, super_chain_len }
1679                }
1680            };
1681        }
1682    } else if let Some(segment) = path.segment()
1683        && segment.coloncolon_token().is_some()
1684    {
1685        path_ctx.qualified = Qualified::Absolute;
1686    }
1687
1688    let mut qualifier_ctx = QualifierCtx::default();
1689    if path_ctx.is_trivial_path() {
1690        // fetch the full expression that may have qualifiers attached to it
1691        let top_node = match path_ctx.kind {
1692            PathKind::Expr { expr_ctx: PathExprCtx { in_block_expr: true, .. } } => {
1693                parent.ancestors().find(|it| ast::PathExpr::can_cast(it.kind())).and_then(|p| {
1694                    let parent = p.parent()?;
1695                    if ast::StmtList::can_cast(parent.kind()) {
1696                        Some(p)
1697                    } else if ast::ExprStmt::can_cast(parent.kind()) {
1698                        Some(parent)
1699                    } else {
1700                        None
1701                    }
1702                })
1703            }
1704            PathKind::Item { .. } => parent.ancestors().find(|it| it.kind() == SyntaxKind::ERROR),
1705            _ => None,
1706        };
1707        if let Some(top) = top_node {
1708            if let Some(NodeOrToken::Node(error_node)) =
1709                syntax::algo::non_trivia_sibling(top.clone().into(), syntax::Direction::Prev)
1710                && error_node.kind() == SyntaxKind::ERROR
1711            {
1712                for token in error_node.children_with_tokens().filter_map(NodeOrToken::into_token) {
1713                    match token.kind() {
1714                        SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token),
1715                        SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token),
1716                        SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token),
1717                        _ => {}
1718                    }
1719                }
1720                qualifier_ctx.vis_node = error_node.children().find_map(ast::Visibility::cast);
1721                qualifier_ctx.abi_node = error_node.children().find_map(ast::Abi::cast);
1722            }
1723
1724            if let PathKind::Item { .. } = path_ctx.kind
1725                && qualifier_ctx.none()
1726                && let Some(t) = top.first_token()
1727                && let Some(prev) =
1728                    t.prev_token().and_then(|t| syntax::algo::skip_trivia_token(t, Direction::Prev))
1729                && ![T![;], T!['}'], T!['{'], T![']']].contains(&prev.kind())
1730            {
1731                // This was inferred to be an item position path, but it seems
1732                // to be part of some other broken node which leaked into an item
1733                // list
1734                return None;
1735            }
1736        }
1737    }
1738    Some((NameRefContext { nameref, kind: NameRefKind::Path(path_ctx) }, qualifier_ctx))
1739}
1740
1741/// When writing in the middle of some code the following situation commonly occurs (`|` denotes the cursor):
1742/// ```ignore
1743/// value.method|
1744/// (1, 2, 3)
1745/// ```
1746/// Here, we want to complete the method parentheses & arguments (if the corresponding settings are on),
1747/// but the thing is parsed as a method call with parentheses. Therefore we use heuristics: if the parentheses
1748/// are on the next line, consider them non-existent.
1749fn has_parens(node: &dyn HasArgList) -> bool {
1750    let Some(arg_list) = node.arg_list() else { return false };
1751    if arg_list.l_paren_token().is_none() {
1752        return false;
1753    }
1754    let prev_siblings = iter::successors(arg_list.syntax().prev_sibling_or_token(), |it| {
1755        it.prev_sibling_or_token()
1756    });
1757    prev_siblings
1758        .take_while(|syntax| syntax.kind().is_trivia())
1759        .filter_map(|syntax| {
1760            syntax.into_token().filter(|token| token.kind() == SyntaxKind::WHITESPACE)
1761        })
1762        .all(|whitespace| !whitespace.text().contains('\n'))
1763}
1764
1765fn pattern_context_for(
1766    sema: &Semantics<'_, RootDatabase>,
1767    original_file: &SyntaxNode,
1768    pat: ast::Pat,
1769) -> PatternContext {
1770    let mut param_ctx = None;
1771
1772    let mut missing_variants = vec![];
1773    let is_pat_like = |kind| {
1774        ast::Pat::can_cast(kind)
1775            || ast::RecordPatField::can_cast(kind)
1776            || ast::RecordPatFieldList::can_cast(kind)
1777    };
1778
1779    let (refutability, has_type_ascription) = pat
1780        .syntax()
1781        .ancestors()
1782        .find(|it| !is_pat_like(it.kind()))
1783        .map_or((PatternRefutability::Irrefutable, false), |node| {
1784            let refutability = match_ast! {
1785                match node {
1786                    ast::LetStmt(let_) => return (PatternRefutability::Refutable, let_.ty().is_some()),
1787                    ast::Param(param) => {
1788                        let has_type_ascription = param.ty().is_some();
1789                        param_ctx = (|| {
1790                            let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1791                            let param_list = find_node_in_file_compensated(sema, original_file, &fake_param_list)?;
1792                            let param_list_owner = param_list.syntax().parent()?;
1793                            let kind = match_ast! {
1794                                match param_list_owner {
1795                                    ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1796                                    ast::Fn(fn_) => ParamKind::Function(fn_),
1797                                    _ => return None,
1798                                }
1799                            };
1800                            Some(ParamContext {
1801                                param_list, param, kind
1802                            })
1803                        })();
1804                        return (PatternRefutability::Irrefutable, has_type_ascription)
1805                    },
1806                    ast::MatchArm(match_arm) => {
1807                       let missing_variants_opt = match_arm
1808                            .syntax()
1809                            .parent()
1810                            .and_then(ast::MatchArmList::cast)
1811                            .and_then(|match_arm_list| {
1812                                match_arm_list
1813                                .syntax()
1814                                .parent()
1815                                .and_then(ast::MatchExpr::cast)
1816                                .and_then(|match_expr| {
1817                                    let expr_opt = find_opt_node_in_file(original_file, match_expr.expr());
1818
1819                                    expr_opt.and_then(|expr| {
1820                                        sema.type_of_expr(&expr)?
1821                                        .adjusted()
1822                                        .autoderef(sema.db)
1823                                        .find_map(|ty| match ty.as_adt() {
1824                                            Some(hir::Adt::Enum(e)) => Some(e),
1825                                            _ => None,
1826                                        }).map(|enum_| enum_.variants(sema.db))
1827                                    })
1828                                }).map(|variants| variants.iter().filter_map(|variant| {
1829                                        let variant_name = variant.name(sema.db);
1830
1831                                        let variant_already_present = match_arm_list.arms().any(|arm| {
1832                                            arm.pat().and_then(|pat| {
1833                                                let pat_already_present = pat.syntax().to_string().contains(variant_name.as_str());
1834                                                pat_already_present.then_some(pat_already_present)
1835                                            }).is_some()
1836                                        });
1837
1838                                        (!variant_already_present).then_some(*variant)
1839                                    }).collect::<Vec<EnumVariant>>())
1840                        });
1841
1842                        if let Some(missing_variants_) = missing_variants_opt {
1843                            missing_variants = missing_variants_;
1844                        };
1845
1846                        PatternRefutability::Refutable
1847                    },
1848                    ast::LetExpr(_) => PatternRefutability::Refutable,
1849                    ast::ForExpr(_) => PatternRefutability::Irrefutable,
1850                    _ => PatternRefutability::Irrefutable,
1851                }
1852            };
1853            (refutability, false)
1854        });
1855    let (ref_token, mut_token) = match &pat {
1856        ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1857        _ => (None, None),
1858    };
1859
1860    // Only suggest name in let-stmt or fn param
1861    let should_suggest_name = matches!(
1862            &pat,
1863            ast::Pat::IdentPat(it)
1864                if it.syntax()
1865                .parent().is_some_and(|node| {
1866                    let kind = node.kind();
1867                    ast::LetStmt::can_cast(kind) || ast::Param::can_cast(kind)
1868                })
1869    );
1870
1871    PatternContext {
1872        refutability,
1873        param_ctx,
1874        has_type_ascription,
1875        should_suggest_name,
1876        after_if_expr: is_after_if_expr(pat.syntax().clone()),
1877        parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1878        mut_token,
1879        ref_token,
1880        record_pat: None,
1881        impl_or_trait: fetch_immediate_impl_or_trait(sema, original_file, pat.syntax()),
1882        missing_variants,
1883    }
1884}
1885
1886fn fetch_immediate_impl_or_trait(
1887    sema: &Semantics<'_, RootDatabase>,
1888    original_file: &SyntaxNode,
1889    node: &SyntaxNode,
1890) -> Option<Either<ast::Impl, ast::Trait>> {
1891    let mut ancestors = ancestors_in_file_compensated(sema, original_file, node)?
1892        .filter_map(ast::Item::cast)
1893        .filter(|it| !matches!(it, ast::Item::MacroCall(_)));
1894
1895    match ancestors.next()? {
1896        ast::Item::Const(_) | ast::Item::Fn(_) | ast::Item::TypeAlias(_) => (),
1897        ast::Item::Impl(it) => return Some(Either::Left(it)),
1898        ast::Item::Trait(it) => return Some(Either::Right(it)),
1899        _ => return None,
1900    }
1901    match ancestors.next()? {
1902        ast::Item::Impl(it) => Some(Either::Left(it)),
1903        ast::Item::Trait(it) => Some(Either::Right(it)),
1904        _ => None,
1905    }
1906}
1907
1908/// Attempts to find `node` inside `syntax` via `node`'s text range.
1909/// If the fake identifier has been inserted after this node or inside of this node use the `_compensated` version instead.
1910fn find_opt_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: Option<N>) -> Option<N> {
1911    find_node_in_file(syntax, &node?)
1912}
1913
1914/// Attempts to find `node` inside `syntax` via `node`'s text range.
1915/// If the fake identifier has been inserted after this node or inside of this node use the `_compensated` version instead.
1916fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1917    let syntax_range = syntax.text_range();
1918    let range = node.syntax().text_range();
1919    let intersection = range.intersect(syntax_range)?;
1920    syntax.covering_element(intersection).ancestors().find_map(N::cast)
1921}
1922
1923/// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1924/// for the offset introduced by the fake ident.
1925/// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1926fn find_node_in_file_compensated<N: AstNode>(
1927    sema: &Semantics<'_, RootDatabase>,
1928    in_file: &SyntaxNode,
1929    node: &N,
1930) -> Option<N> {
1931    ancestors_in_file_compensated(sema, in_file, node.syntax())?.find_map(N::cast)
1932}
1933
1934fn ancestors_in_file_compensated<'sema>(
1935    sema: &'sema Semantics<'_, RootDatabase>,
1936    in_file: &SyntaxNode,
1937    node: &SyntaxNode,
1938) -> Option<impl Iterator<Item = SyntaxNode> + 'sema> {
1939    let syntax_range = in_file.text_range();
1940    let range = node.text_range();
1941    let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1942    if end < range.start() {
1943        return None;
1944    }
1945    let range = TextRange::new(range.start(), end);
1946    // our inserted ident could cause `range` to go outside of the original syntax, so cap it
1947    let intersection = range.intersect(syntax_range)?;
1948    let node = match in_file.covering_element(intersection) {
1949        NodeOrToken::Node(node) => node,
1950        NodeOrToken::Token(tok) => tok.parent()?,
1951    };
1952    Some(sema.ancestors_with_macros(node))
1953}
1954
1955/// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1956/// for the offset introduced by the fake ident..
1957/// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1958fn find_opt_node_in_file_compensated<N: AstNode>(
1959    sema: &Semantics<'_, RootDatabase>,
1960    syntax: &SyntaxNode,
1961    node: Option<N>,
1962) -> Option<N> {
1963    find_node_in_file_compensated(sema, syntax, &node?)
1964}
1965
1966fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1967    if let Some(qual) = path.qualifier() {
1968        return Some((qual, false));
1969    }
1970    let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1971    let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1972    Some((use_tree.path()?, true))
1973}
1974
1975fn left_ancestors(node: Option<SyntaxNode>) -> impl Iterator<Item = SyntaxNode> {
1976    node.into_iter().flat_map(|node| {
1977        let end = node.text_range().end();
1978        node.ancestors().take_while(move |it| it.text_range().end() == end)
1979    })
1980}
1981
1982fn is_in_token_of_for_loop(path: &ast::Path) -> bool {
1983    // oh my ...
1984    (|| {
1985        let expr = path.syntax().parent().and_then(ast::PathExpr::cast)?;
1986        let for_expr = expr.syntax().parent().and_then(ast::ForExpr::cast)?;
1987        if for_expr.in_token().is_some() {
1988            return Some(false);
1989        }
1990        let pat = for_expr.pat()?;
1991        let next_sibl = next_non_trivia_sibling(pat.syntax().clone().into())?;
1992        Some(match next_sibl {
1993            syntax::NodeOrToken::Node(n) => {
1994                n.text_range().start() == path.syntax().text_range().start()
1995            }
1996            syntax::NodeOrToken::Token(t) => {
1997                t.text_range().start() == path.syntax().text_range().start()
1998            }
1999        })
2000    })()
2001    .unwrap_or(false)
2002}
2003
2004fn is_in_breakable(node: &SyntaxNode) -> Option<(BreakableKind, SyntaxNode)> {
2005    node.ancestors()
2006        .take_while(|it| it.kind() != SyntaxKind::FN && it.kind() != SyntaxKind::CLOSURE_EXPR)
2007        .find_map(|it| {
2008            let (breakable, loop_body) = match_ast! {
2009                match it {
2010                    ast::ForExpr(it) => (BreakableKind::For, it.loop_body()?),
2011                    ast::WhileExpr(it) => (BreakableKind::While, it.loop_body()?),
2012                    ast::LoopExpr(it) => (BreakableKind::Loop, it.loop_body()?),
2013                    ast::BlockExpr(it) => return it.label().map(|_| (BreakableKind::Block, it.syntax().clone())),
2014                    _ => return None,
2015                }
2016            };
2017            loop_body.syntax().text_range().contains_range(node.text_range())
2018                .then_some((breakable, it))
2019        })
2020}
2021
2022fn is_in_block(node: &SyntaxNode) -> bool {
2023    if has_in_newline_expr_first(node) {
2024        return true;
2025    };
2026    node.parent()
2027        .map(|node| ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind()))
2028        .unwrap_or(false)
2029}
2030
2031/// Similar to `has_parens`, heuristic sensing incomplete statement before ambiguous `Expr`
2032///
2033/// Heuristic:
2034///
2035/// If the `PathExpr` is left part of the `Expr` and there is a newline after the `PathExpr`,
2036/// it is considered that the `PathExpr` is not part of the `Expr`.
2037fn has_in_newline_expr_first(node: &SyntaxNode) -> bool {
2038    if ast::PathExpr::can_cast(node.kind())
2039        && let Some(NodeOrToken::Token(next)) = node.next_sibling_or_token()
2040        && next.kind() == SyntaxKind::WHITESPACE
2041        && next.text().contains('\n')
2042        && let Some(stmt_like) = node
2043            .ancestors()
2044            .take_while(|it| it.text_range().start() == node.text_range().start())
2045            .filter_map(Either::<ast::ExprStmt, ast::Expr>::cast)
2046            .last()
2047    {
2048        stmt_like.syntax().parent().and_then(ast::StmtList::cast).is_some()
2049    } else {
2050        false
2051    }
2052}
2053
2054fn is_after_if_expr(node: SyntaxNode) -> bool {
2055    let node = match node.parent().and_then(Either::<ast::ExprStmt, ast::MatchArm>::cast) {
2056        Some(stmt) => stmt.syntax().clone(),
2057        None => node,
2058    };
2059    let Some(prev_token) = previous_non_trivia_token(node) else { return false };
2060    prev_token
2061        .parent_ancestors()
2062        .take_while(|it| it.text_range().end() == prev_token.text_range().end())
2063        .find_map(ast::IfExpr::cast)
2064        .is_some()
2065}
2066
2067fn next_non_trivia_token(e: impl Into<SyntaxElement>) -> Option<SyntaxToken> {
2068    let mut token = match e.into() {
2069        SyntaxElement::Node(n) => n.last_token()?,
2070        SyntaxElement::Token(t) => t,
2071    }
2072    .next_token();
2073    while let Some(inner) = token {
2074        if !inner.kind().is_trivia() {
2075            return Some(inner);
2076        } else {
2077            token = inner.next_token();
2078        }
2079    }
2080    None
2081}
2082
2083fn next_non_trivia_sibling(ele: SyntaxElement) -> Option<SyntaxElement> {
2084    let mut e = ele;
2085    while let Some(next) = e.next_sibling_or_token() {
2086        if !next.kind().is_trivia() {
2087            return Some(next);
2088        } else {
2089            e = next;
2090        }
2091    }
2092    None
2093}
2094
2095fn prev_special_biased_token_at_trivia(mut token: SyntaxToken) -> SyntaxToken {
2096    while token.kind().is_trivia()
2097        && let Some(prev) = token.prev_token()
2098        && let T![=]
2099        | T![+=]
2100        | T![/=]
2101        | T![*=]
2102        | T![%=]
2103        | T![>>=]
2104        | T![<<=]
2105        | T![-=]
2106        | T![|=]
2107        | T![&=]
2108        | T![^=]
2109        | T![|]
2110        | T![return]
2111        | T![break]
2112        | T![continue]
2113        | T![lifetime_ident] = prev.kind()
2114    {
2115        token = prev
2116    }
2117    token
2118}