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::MatchGuard(it) => {
798                    let ty = it.condition().and_then(|e| sema.type_of_expr(&e)).map(TypeInfo::original);
799                    (ty, None)
800                },
801                ast::IdentPat(it) => {
802                    cov_mark::hit!(expected_type_if_let_with_leading_char);
803                    cov_mark::hit!(expected_type_match_arm_with_leading_char);
804                    let ty = sema.type_of_pat(&ast::Pat::from(it)).map(TypeInfo::original);
805                    (ty, None)
806                },
807                ast::TupleStructPat(it) => {
808                    let fields = sema.resolve_tuple_struct_pat_fields(&it);
809                    let nr = it.fields().take_while(|it| it.syntax().text_range().end() <= token.text_range().start()).count();
810                    let ty = fields.and_then(|fields| Some(rebase_ty(fields.get(nr)?.1.clone())));
811                    (ty, None)
812                },
813                ast::Fn(it) => {
814                    cov_mark::hit!(expected_type_fn_ret_with_leading_char);
815                    cov_mark::hit!(expected_type_fn_ret_without_leading_char);
816                    let def = sema.to_def(&it);
817                    (def.map(|def| rebase_ty(def.ret_type(sema.db))), None)
818                },
819                ast::ReturnExpr(it) => {
820                    let fn_ = sema.ancestors_with_macros(it.syntax().clone())
821                        .find_map(Either::<ast::Fn, ast::ClosureExpr>::cast);
822                    let ty = fn_.and_then(|f| match f {
823                        Either::Left(f) => Some(rebase_ty(sema.to_def(&f)?.ret_type(sema.db))),
824                        Either::Right(f) => {
825                            let ty = sema.type_of_expr(&f.into())?.original.as_callable(sema.db)?;
826                            Some(ty.return_type())
827                        },
828                    });
829                    (ty, None)
830                },
831                ast::BreakExpr(it) => {
832                    let ty = it.break_token()
833                        .and_then(|it| find_loops(sema, &it)?.next())
834                        .and_then(|expr| sema.type_of_expr(&expr));
835                    (ty.map(TypeInfo::original), None)
836                },
837                ast::ClosureExpr(it) => {
838                    let ty = sema.type_of_expr(&it.into());
839                    ty.and_then(|ty| ty.original.as_callable(sema.db))
840                        .map(|c| (Some(c.return_type()), None))
841                        .unwrap_or((None, None))
842                },
843                ast::ParamList(it) => {
844                    let closure = it.syntax().parent().and_then(ast::ClosureExpr::cast);
845                    let ty = closure
846                        .filter(|_| it.syntax().text_range().end() <= self_token.text_range().start())
847                        .and_then(|it| sema.type_of_expr(&it.into()));
848                    ty.and_then(|ty| ty.original.as_callable(sema.db))
849                        .map(|c| (Some(c.return_type()), None))
850                        .unwrap_or((None, None))
851                },
852                ast::Variant(it) => {
853                    let is_simple_field = |field: ast::TupleField| {
854                        let Some(ty) = field.ty() else { return true };
855                        matches!(ty, ast::Type::PathType(_)) && ty.generic_arg_list().is_none()
856                    };
857                    let is_simple_variant = matches!(
858                        it.field_list(),
859                        Some(ast::FieldList::TupleFieldList(list))
860                        if list.syntax().children_with_tokens().all(|it| it.kind() != T![,])
861                            && list.fields().next().is_none_or(is_simple_field)
862                    );
863                    (None, it.name().filter(|_| is_simple_variant).map(NameOrNameRef::Name))
864                },
865                ast::Stmt(_) => (None, None),
866                ast::Item(_) => (None, None),
867                _ => {
868                    match node.parent() {
869                        Some(n) => {
870                            node = n;
871                            continue;
872                        },
873                        None => (None, None),
874                    }
875                },
876            }
877        };
878    };
879    (ty.map(strip_refs), name)
880}
881
882fn classify_lifetime(
883    sema: &Semantics<'_, RootDatabase>,
884    original_file: &SyntaxNode,
885    lifetime: ast::Lifetime,
886) -> Option<LifetimeContext> {
887    let parent = lifetime.syntax().parent()?;
888    if parent.kind() == SyntaxKind::ERROR {
889        return None;
890    }
891
892    let lifetime =
893        find_node_at_offset::<ast::Lifetime>(original_file, lifetime.syntax().text_range().start());
894    let kind = match_ast! {
895        match parent {
896            ast::LifetimeParam(_) => LifetimeKind::LifetimeParam,
897            ast::BreakExpr(_) => LifetimeKind::LabelRef,
898            ast::ContinueExpr(_) => LifetimeKind::LabelRef,
899            ast::Label(_) => LifetimeKind::LabelDef,
900            _ => {
901                let def = lifetime.as_ref().and_then(|lt| sema.scope(lt.syntax())?.generic_def());
902                LifetimeKind::Lifetime { in_lifetime_param_bound: ast::TypeBound::can_cast(parent.kind()), def }
903            },
904        }
905    };
906
907    Some(LifetimeContext { kind })
908}
909
910fn classify_name(
911    sema: &Semantics<'_, RootDatabase>,
912    original_file: &SyntaxNode,
913    name: ast::Name,
914) -> Option<NameContext> {
915    let parent = name.syntax().parent()?;
916    let kind = match_ast! {
917        match parent {
918            ast::Const(_) => NameKind::Const,
919            ast::ConstParam(_) => NameKind::ConstParam,
920            ast::Enum(_) => NameKind::Enum,
921            ast::Fn(_) => NameKind::Function,
922            ast::IdentPat(bind_pat) => {
923                let mut pat_ctx = pattern_context_for(sema, original_file, bind_pat.into());
924                if let Some(record_field) = ast::RecordPatField::for_field_name(&name) {
925                    pat_ctx.record_pat = find_node_in_file_compensated(sema, original_file, &record_field.parent_record_pat());
926                }
927
928                NameKind::IdentPat(pat_ctx)
929            },
930            ast::MacroDef(_) => NameKind::MacroDef,
931            ast::MacroRules(_) => NameKind::MacroRules,
932            ast::Module(module) => NameKind::Module(module),
933            ast::RecordField(_) => NameKind::RecordField,
934            ast::Rename(_) => NameKind::Rename,
935            ast::SelfParam(_) => NameKind::SelfParam,
936            ast::Static(_) => NameKind::Static,
937            ast::Struct(_) => NameKind::Struct,
938            ast::Trait(_) => NameKind::Trait,
939            ast::TypeAlias(_) => NameKind::TypeAlias,
940            ast::TypeParam(_) => NameKind::TypeParam,
941            ast::Union(_) => NameKind::Union,
942            ast::Variant(_) => NameKind::Variant,
943            _ => return None,
944        }
945    };
946    let name = find_node_at_offset(original_file, name.syntax().text_range().start());
947    Some(NameContext { name, kind })
948}
949
950fn classify_name_ref<'db>(
951    sema: &Semantics<'db, RootDatabase>,
952    original_file: &SyntaxNode,
953    name_ref: ast::NameRef,
954    original_offset: TextSize,
955    parent: SyntaxNode,
956) -> Option<(NameRefContext<'db>, QualifierCtx)> {
957    let nameref = find_node_at_offset(original_file, original_offset);
958
959    let make_res = |kind| (NameRefContext { nameref: nameref.clone(), kind }, Default::default());
960
961    if let Some(record_field) = ast::RecordExprField::for_field_name(&name_ref) {
962        let dot_prefix = previous_non_trivia_token(name_ref.syntax().clone())
963            .is_some_and(|it| T![.] == it.kind());
964
965        return find_node_in_file_compensated(
966            sema,
967            original_file,
968            &record_field.parent_record_lit(),
969        )
970        .map(|expr| NameRefKind::RecordExpr { expr, dot_prefix })
971        .map(make_res);
972    }
973    if let Some(record_field) = ast::RecordPatField::for_field_name_ref(&name_ref) {
974        let kind = NameRefKind::Pattern(PatternContext {
975            param_ctx: None,
976            has_type_ascription: false,
977            ref_token: None,
978            mut_token: None,
979            record_pat: find_node_in_file_compensated(
980                sema,
981                original_file,
982                &record_field.parent_record_pat(),
983            ),
984            ..pattern_context_for(sema, original_file, record_field.parent_record_pat().into())
985        });
986        return Some(make_res(kind));
987    }
988
989    let field_expr_handle = |receiver, node| {
990        let receiver = find_opt_node_in_file(original_file, receiver);
991        let receiver_is_ambiguous_float_literal = match &receiver {
992            Some(ast::Expr::Literal(l)) => {
993                matches!(l.kind(), ast::LiteralKind::FloatNumber { .. })
994                    && l.syntax().last_token().is_some_and(|it| it.text().ends_with('.'))
995            }
996            _ => false,
997        };
998
999        let receiver_is_part_of_indivisible_expression = match &receiver {
1000            Some(ast::Expr::IfExpr(_)) => {
1001                let next_token_kind =
1002                    next_non_trivia_token(name_ref.syntax().clone()).map(|t| t.kind());
1003                next_token_kind == Some(SyntaxKind::ELSE_KW)
1004            }
1005            _ => false,
1006        };
1007        if receiver_is_part_of_indivisible_expression {
1008            return None;
1009        }
1010
1011        let mut receiver_ty = receiver.as_ref().and_then(|it| sema.type_of_expr(it));
1012        if receiver_is_ambiguous_float_literal {
1013            // `123.|` is parsed as a float but should actually be an integer.
1014            always!(receiver_ty.as_ref().is_none_or(|receiver_ty| receiver_ty.original.is_float()));
1015            receiver_ty =
1016                Some(TypeInfo { original: hir::BuiltinType::i32().ty(sema.db), adjusted: None });
1017        }
1018
1019        let kind = NameRefKind::DotAccess(DotAccess {
1020            receiver_ty,
1021            kind: DotAccessKind::Field { receiver_is_ambiguous_float_literal },
1022            receiver,
1023            ctx: DotAccessExprCtx {
1024                in_block_expr: is_in_block(node),
1025                in_breakable: is_in_breakable(node).unzip().0,
1026            },
1027        });
1028        Some(make_res(kind))
1029    };
1030
1031    let segment = match_ast! {
1032        match parent {
1033            ast::PathSegment(segment) => segment,
1034            ast::FieldExpr(field) => {
1035                return field_expr_handle(field.expr(), field.syntax());
1036            },
1037            ast::ExternCrate(_) => {
1038                let kind = NameRefKind::ExternCrate;
1039                return Some(make_res(kind));
1040            },
1041            ast::MethodCallExpr(method) => {
1042                let receiver = find_opt_node_in_file(original_file, method.receiver());
1043                let has_parens = has_parens(&method);
1044                if !has_parens && let Some(res) = field_expr_handle(method.receiver(), method.syntax()) {
1045                    return Some(res)
1046                }
1047                let kind = NameRefKind::DotAccess(DotAccess {
1048                    receiver_ty: receiver.as_ref().and_then(|it| sema.type_of_expr(it)),
1049                    kind: DotAccessKind::Method,
1050                    receiver,
1051                    ctx: DotAccessExprCtx { in_block_expr: is_in_block(method.syntax()), in_breakable: is_in_breakable(method.syntax()).unzip().0 }
1052                });
1053                return Some(make_res(kind));
1054            },
1055            _ => return None,
1056        }
1057    };
1058
1059    let path = segment.parent_path();
1060    let original_path = find_node_in_file_compensated(sema, original_file, &path);
1061
1062    let mut path_ctx = PathCompletionCtx {
1063        has_call_parens: false,
1064        has_macro_bang: false,
1065        qualified: Qualified::No,
1066        parent: None,
1067        path: path.clone(),
1068        original_path,
1069        kind: PathKind::Item { kind: ItemListKind::SourceFile },
1070        has_type_args: false,
1071        use_tree_parent: false,
1072    };
1073
1074    let func_update_record = |syn: &SyntaxNode| {
1075        if let Some(record_expr) = syn.ancestors().nth(2).and_then(ast::RecordExpr::cast) {
1076            find_node_in_file_compensated(sema, original_file, &record_expr)
1077        } else {
1078            None
1079        }
1080    };
1081    let prev_expr = |node: SyntaxNode| {
1082        let node = match node.parent().and_then(ast::ExprStmt::cast) {
1083            Some(stmt) => stmt.syntax().clone(),
1084            None => node,
1085        };
1086        let prev_sibling = non_trivia_sibling(node.into(), Direction::Prev)?.into_node()?;
1087
1088        match_ast! {
1089            match prev_sibling {
1090                ast::ExprStmt(stmt) => stmt.expr().filter(|_| stmt.semicolon_token().is_none()),
1091                ast::LetStmt(stmt) => stmt.initializer().filter(|_| stmt.semicolon_token().is_none()),
1092                ast::Expr(expr) => Some(expr),
1093                _ => None,
1094            }
1095        }
1096    };
1097    let after_incomplete_let = |node: SyntaxNode| {
1098        prev_expr(node).and_then(|it| it.syntax().parent()).and_then(ast::LetStmt::cast)
1099    };
1100    let before_else_kw = |node: &SyntaxNode| {
1101        node.parent()
1102            .and_then(ast::ExprStmt::cast)
1103            .filter(|stmt| stmt.semicolon_token().is_none())
1104            .and_then(|stmt| non_trivia_sibling(stmt.syntax().clone().into(), Direction::Next))
1105            .and_then(NodeOrToken::into_node)
1106            .filter(|next| next.kind() == SyntaxKind::ERROR)
1107            .and_then(|next| next.first_token())
1108            .is_some_and(|token| token.kind() == SyntaxKind::ELSE_KW)
1109    };
1110
1111    // We do not want to generate path completions when we are sandwiched between an item decl signature and its body.
1112    // ex. trait Foo $0 {}
1113    // in these cases parser recovery usually kicks in for our inserted identifier, causing it
1114    // to either be parsed as an ExprStmt or a ItemRecovery, depending on whether it is in a block
1115    // expression or an item list.
1116    // The following code checks if the body is missing, if it is we either cut off the body
1117    // from the item or it was missing in the first place
1118    let inbetween_body_and_decl_check = |node: SyntaxNode| {
1119        if let Some(NodeOrToken::Node(n)) =
1120            syntax::algo::non_trivia_sibling(node.into(), syntax::Direction::Prev)
1121            && let Some(item) = ast::Item::cast(n)
1122        {
1123            let is_inbetween = match &item {
1124                ast::Item::Const(it) => it.body().is_none() && it.semicolon_token().is_none(),
1125                ast::Item::Enum(it) => it.variant_list().is_none(),
1126                ast::Item::ExternBlock(it) => it.extern_item_list().is_none(),
1127                ast::Item::Fn(it) => it.body().is_none() && it.semicolon_token().is_none(),
1128                ast::Item::Impl(it) => it.assoc_item_list().is_none(),
1129                ast::Item::Module(it) => it.item_list().is_none() && it.semicolon_token().is_none(),
1130                ast::Item::Static(it) => it.body().is_none(),
1131                ast::Item::Struct(it) => {
1132                    it.field_list().is_none() && it.semicolon_token().is_none()
1133                }
1134                ast::Item::Trait(it) => it.assoc_item_list().is_none(),
1135                ast::Item::TypeAlias(it) => it.ty().is_none() && it.semicolon_token().is_none(),
1136                ast::Item::Union(it) => it.record_field_list().is_none(),
1137                _ => false,
1138            };
1139            if is_inbetween {
1140                return Some(item);
1141            }
1142        }
1143        None
1144    };
1145
1146    let generic_arg_location = |arg: ast::GenericArg| {
1147        let mut override_location = None;
1148        let location = find_opt_node_in_file_compensated(
1149            sema,
1150            original_file,
1151            arg.syntax().parent().and_then(ast::GenericArgList::cast),
1152        )
1153        .map(|args| {
1154            let mut in_trait = None;
1155            let param = (|| {
1156                let parent = args.syntax().parent()?;
1157                let params = match_ast! {
1158                    match parent {
1159                        ast::PathSegment(segment) => {
1160                            match sema.resolve_path(&segment.parent_path().top_path())? {
1161                                hir::PathResolution::Def(def) => match def {
1162                                    hir::ModuleDef::Function(func) => {
1163                                         sema.source(func)?.value.generic_param_list()
1164                                    }
1165                                    hir::ModuleDef::Adt(adt) => {
1166                                        sema.source(adt)?.value.generic_param_list()
1167                                    }
1168                                    hir::ModuleDef::EnumVariant(variant) => {
1169                                        sema.source(variant.parent_enum(sema.db))?.value.generic_param_list()
1170                                    }
1171                                    hir::ModuleDef::Trait(trait_) => {
1172                                        if let ast::GenericArg::AssocTypeArg(arg) = &arg {
1173                                            let arg_name = arg.name_ref()?;
1174                                            let arg_name = arg_name.text();
1175                                            for item in trait_.items_with_supertraits(sema.db) {
1176                                                match item {
1177                                                    hir::AssocItem::TypeAlias(assoc_ty)
1178                                                        if assoc_ty.name(sema.db).as_str() == arg_name => {
1179                                                            override_location = Some(TypeLocation::AssocTypeEq);
1180                                                            return None;
1181                                                        },
1182                                                    hir::AssocItem::Const(const_)
1183                                                        if const_.name(sema.db)?.as_str() == arg_name => {
1184                                                            override_location =  Some(TypeLocation::AssocConstEq);
1185                                                            return None;
1186                                                        },
1187                                                    _ => (),
1188                                                }
1189                                            }
1190                                            return None;
1191                                        } else {
1192                                            in_trait = Some(trait_);
1193                                            sema.source(trait_)?.value.generic_param_list()
1194                                        }
1195                                    }
1196                                    hir::ModuleDef::TypeAlias(ty_) => {
1197                                        sema.source(ty_)?.value.generic_param_list()
1198                                    }
1199                                    _ => None,
1200                                },
1201                                _ => None,
1202                            }
1203                        },
1204                        ast::MethodCallExpr(call) => {
1205                            let func = sema.resolve_method_call(&call)?;
1206                            sema.source(func)?.value.generic_param_list()
1207                        },
1208                        ast::AssocTypeArg(arg) => {
1209                            let trait_ = ast::PathSegment::cast(arg.syntax().parent()?.parent()?)?;
1210                            match sema.resolve_path(&trait_.parent_path().top_path())? {
1211                                hir::PathResolution::Def(hir::ModuleDef::Trait(trait_)) =>  {
1212                                        let arg_name = arg.name_ref()?;
1213                                        let arg_name = arg_name.text();
1214                                        let trait_items = trait_.items_with_supertraits(sema.db);
1215                                        let assoc_ty = trait_items.iter().find_map(|item| match item {
1216                                            hir::AssocItem::TypeAlias(assoc_ty) => {
1217                                                (assoc_ty.name(sema.db).as_str() == arg_name)
1218                                                    .then_some(assoc_ty)
1219                                            },
1220                                            _ => None,
1221                                        })?;
1222                                        sema.source(*assoc_ty)?.value.generic_param_list()
1223                                    }
1224                                _ => None,
1225                            }
1226                        },
1227                        _ => None,
1228                    }
1229                }?;
1230                // Determine the index of the argument in the `GenericArgList` and match it with
1231                // the corresponding parameter in the `GenericParamList`. Since lifetime parameters
1232                // are often omitted, ignore them for the purposes of matching the argument with
1233                // its parameter unless a lifetime argument is provided explicitly. That is, for
1234                // `struct S<'a, 'b, T>`, match `S::<$0>` to `T` and `S::<'a, $0, _>` to `'b`.
1235                // FIXME: This operates on the syntax tree and will produce incorrect results when
1236                // generic parameters are disabled by `#[cfg]` directives. It should operate on the
1237                // HIR, but the functionality necessary to do so is not exposed at the moment.
1238                let mut explicit_lifetime_arg = false;
1239                let arg_idx = arg
1240                    .syntax()
1241                    .siblings(Direction::Prev)
1242                    // Skip the node itself
1243                    .skip(1)
1244                    .map(|arg| if ast::LifetimeArg::can_cast(arg.kind()) { explicit_lifetime_arg = true })
1245                    .count();
1246                let param_idx = if explicit_lifetime_arg {
1247                    arg_idx
1248                } else {
1249                    // Lifetimes parameters always precede type and generic parameters,
1250                    // so offset the argument index by the total number of lifetime params
1251                    arg_idx + params.lifetime_params().count()
1252                };
1253                params.generic_params().nth(param_idx)
1254            })();
1255            (args, in_trait, param)
1256        });
1257        let (arg_list, of_trait, corresponding_param) = match location {
1258            Some((arg_list, of_trait, param)) => (Some(arg_list), of_trait, param),
1259            _ => (None, None, None),
1260        };
1261        override_location.unwrap_or(TypeLocation::GenericArg {
1262            args: arg_list,
1263            of_trait,
1264            corresponding_param,
1265        })
1266    };
1267
1268    let type_location = |node: &SyntaxNode| {
1269        let parent = node.parent()?;
1270        let res = match_ast! {
1271            match parent {
1272                ast::Const(it) => {
1273                    let name = find_opt_node_in_file(original_file, it.name())?;
1274                    let original = ast::Const::cast(name.syntax().parent()?)?;
1275                    TypeLocation::TypeAscription(TypeAscriptionTarget::Const(original.body()))
1276                },
1277                ast::Static(it) => {
1278                    let name = find_opt_node_in_file(original_file, it.name())?;
1279                    let original = ast::Static::cast(name.syntax().parent()?)?;
1280                    TypeLocation::TypeAscription(TypeAscriptionTarget::Const(original.body()))
1281                },
1282                ast::RetType(_) => {
1283                    let parent = match ast::Fn::cast(parent.parent()?) {
1284                        Some(it) => it.param_list(),
1285                        None => ast::ClosureExpr::cast(parent.parent()?)?.param_list(),
1286                    };
1287
1288                    let parent = find_opt_node_in_file(original_file, parent)?.syntax().parent()?;
1289                    let body = match_ast! {
1290                        match parent {
1291                            ast::ClosureExpr(it) => {
1292                                it.body()
1293                            },
1294                            ast::Fn(it) => {
1295                                it.body().map(ast::Expr::BlockExpr)
1296                            },
1297                            _ => return None,
1298                        }
1299                    };
1300                    let item = ast::Fn::cast(parent);
1301                    TypeLocation::TypeAscription(TypeAscriptionTarget::RetType { body, item })
1302                },
1303                ast::Param(it) => {
1304                    it.colon_token()?;
1305                    TypeLocation::TypeAscription(TypeAscriptionTarget::FnParam(find_opt_node_in_file(original_file, it.pat())))
1306                },
1307                ast::LetStmt(it) => {
1308                    it.colon_token()?;
1309                    TypeLocation::TypeAscription(TypeAscriptionTarget::Let(find_opt_node_in_file(original_file, it.pat())))
1310                },
1311                ast::Impl(it) => {
1312                    match it.trait_() {
1313                        Some(t) if t.syntax() == node => TypeLocation::ImplTrait,
1314                        _ => match it.self_ty() {
1315                            Some(t) if t.syntax() == node => TypeLocation::ImplTarget,
1316                            _ => return None,
1317                        },
1318                    }
1319                },
1320                ast::TypeBound(_) => TypeLocation::TypeBound,
1321                // is this case needed?
1322                ast::TypeBoundList(_) => TypeLocation::TypeBound,
1323                ast::GenericArg(it) => generic_arg_location(it),
1324                // is this case needed?
1325                ast::GenericArgList(it) => {
1326                    let args = find_opt_node_in_file_compensated(sema, original_file, Some(it));
1327                    TypeLocation::GenericArg { args, of_trait: None, corresponding_param: None }
1328                },
1329                ast::TupleField(_) => TypeLocation::TupleField,
1330                _ => return None,
1331            }
1332        };
1333        Some(res)
1334    };
1335
1336    let make_path_kind_expr = |expr: ast::Expr| {
1337        let it = expr.syntax();
1338        let prev_token = iter::successors(it.first_token(), |it| it.prev_token())
1339            .skip(1)
1340            .find(|it| !it.kind().is_trivia());
1341        let in_block_expr = is_in_block(it);
1342        let (in_loop_body, innermost_breakable) = is_in_breakable(it).unzip();
1343        let after_if_expr = is_after_if_expr(it.clone());
1344        let after_amp = prev_token.as_ref().is_some_and(|it| it.kind() == SyntaxKind::AMP);
1345        let ref_expr_parent = prev_token.and_then(|it| it.parent()).and_then(ast::RefExpr::cast);
1346        let (innermost_ret_ty, self_param) = {
1347            let find_ret_ty = |it: SyntaxNode| {
1348                if let Some(item) = ast::Item::cast(it.clone()) {
1349                    match item {
1350                        ast::Item::Fn(f) => Some(sema.to_def(&f).map(|it| it.ret_type(sema.db))),
1351                        ast::Item::MacroCall(_) => None,
1352                        _ => Some(None),
1353                    }
1354                } else {
1355                    let expr = ast::Expr::cast(it)?;
1356                    let callable = match expr {
1357                        // FIXME
1358                        // ast::Expr::BlockExpr(b) if b.async_token().is_some() || b.try_token().is_some() => sema.type_of_expr(b),
1359                        ast::Expr::ClosureExpr(_) => sema.type_of_expr(&expr),
1360                        _ => return None,
1361                    };
1362                    Some(
1363                        callable
1364                            .and_then(|c| c.adjusted().as_callable(sema.db))
1365                            .map(|it| it.return_type()),
1366                    )
1367                }
1368            };
1369            let fn_self_param =
1370                |fn_: ast::Fn| sema.to_def(&fn_).and_then(|it| it.self_param(sema.db));
1371            let closure_this_param = |closure: ast::ClosureExpr| {
1372                if closure.param_list()?.params().next()?.pat()?.syntax().text() != "this" {
1373                    return None;
1374                }
1375                sema.type_of_expr(&closure.into())
1376                    .and_then(|it| it.original.as_callable(sema.db))
1377                    .and_then(|it| it.params().into_iter().next())
1378            };
1379            let find_fn_self_param = |it: SyntaxNode| {
1380                match_ast! {
1381                    match it {
1382                        ast::Fn(fn_) => Some(fn_self_param(fn_).map(Either::Left)),
1383                        ast::ClosureExpr(f) => closure_this_param(f).map(Either::Right).map(Some),
1384                        ast::MacroCall(_) => None,
1385                        ast::Item(_) => Some(None),
1386                        _ => None,
1387                    }
1388                }
1389            };
1390
1391            match find_node_in_file_compensated(sema, original_file, &expr) {
1392                Some(it) => {
1393                    // buggy
1394                    let innermost_ret_ty = sema
1395                        .ancestors_with_macros(it.syntax().clone())
1396                        .find_map(find_ret_ty)
1397                        .flatten();
1398
1399                    let self_param = sema
1400                        .ancestors_with_macros(it.syntax().clone())
1401                        .find_map(find_fn_self_param)
1402                        .flatten();
1403                    (innermost_ret_ty, self_param)
1404                }
1405                None => (None, None),
1406            }
1407        };
1408        let innermost_breakable_ty = innermost_breakable
1409            .and_then(ast::Expr::cast)
1410            .and_then(|expr| find_node_in_file_compensated(sema, original_file, &expr))
1411            .and_then(|expr| sema.type_of_expr(&expr))
1412            .map(|ty| if ty.original.is_never() { ty.adjusted() } else { ty.original() });
1413        let is_func_update = func_update_record(it);
1414        let in_condition = is_in_condition(&expr);
1415        let after_incomplete_let = after_incomplete_let(it.clone()).is_some();
1416        let incomplete_expr_stmt =
1417            it.parent().and_then(ast::ExprStmt::cast).map(|it| it.semicolon_token().is_none());
1418        let before_else_kw = before_else_kw(it);
1419        let incomplete_let = left_ancestors(it.parent())
1420            .find_map(ast::LetStmt::cast)
1421            .is_some_and(|it| it.semicolon_token().is_none())
1422            || after_incomplete_let && incomplete_expr_stmt.unwrap_or(true) && !before_else_kw;
1423        let in_value = is_in_value(&expr);
1424        let impl_ = fetch_immediate_impl_or_trait(sema, original_file, expr.syntax())
1425            .and_then(Either::left);
1426
1427        let in_match_guard = match it.parent().and_then(ast::MatchArm::cast) {
1428            Some(arm) => arm
1429                .fat_arrow_token()
1430                .is_none_or(|arrow| it.text_range().start() < arrow.text_range().start()),
1431            None => false,
1432        };
1433
1434        PathKind::Expr {
1435            expr_ctx: PathExprCtx {
1436                in_block_expr,
1437                in_breakable: in_loop_body,
1438                after_if_expr,
1439                before_else_kw,
1440                in_condition,
1441                ref_expr_parent,
1442                after_amp,
1443                is_func_update,
1444                innermost_ret_ty,
1445                innermost_breakable_ty,
1446                self_param,
1447                in_value,
1448                incomplete_let,
1449                after_incomplete_let,
1450                impl_,
1451                in_match_guard,
1452            },
1453        }
1454    };
1455    let make_path_kind_type = |ty: ast::Type| {
1456        let location = type_location(ty.syntax());
1457        PathKind::Type { location: location.unwrap_or(TypeLocation::Other) }
1458    };
1459
1460    let kind_item = |it: &SyntaxNode| {
1461        let parent = it.parent()?;
1462        let kind = match_ast! {
1463            match parent {
1464                ast::ItemList(_) => PathKind::Item { kind: ItemListKind::Module },
1465                ast::AssocItemList(_) => PathKind::Item { kind: match parent.parent() {
1466                    Some(it) => match_ast! {
1467                        match it {
1468                            ast::Trait(_) => ItemListKind::Trait,
1469                            ast::Impl(it) => if it.trait_().is_some() {
1470                                ItemListKind::TraitImpl(find_node_in_file_compensated(sema, original_file, &it))
1471                            } else {
1472                                ItemListKind::Impl
1473                            },
1474                            _ => return None
1475                        }
1476                    },
1477                    None => return None,
1478                } },
1479                ast::ExternItemList(it) => {
1480                    let exn_blk = it.syntax().parent().and_then(ast::ExternBlock::cast);
1481                    PathKind::Item {
1482                        kind: ItemListKind::ExternBlock {
1483                            is_unsafe: exn_blk.and_then(|it| it.unsafe_token()).is_some(),
1484                        }
1485                    }
1486                },
1487                ast::SourceFile(_) => PathKind::Item { kind: ItemListKind::SourceFile },
1488                _ => return None,
1489            }
1490        };
1491        Some(kind)
1492    };
1493
1494    let mut kind_macro_call = |it: ast::MacroCall| {
1495        path_ctx.has_macro_bang = it.excl_token().is_some();
1496        let parent = it.syntax().parent()?;
1497        if let Some(kind) = kind_item(it.syntax()) {
1498            return Some(kind);
1499        }
1500        let kind = match_ast! {
1501            match parent {
1502                ast::MacroExpr(expr) => make_path_kind_expr(expr.into()),
1503                ast::MacroPat(it) => PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())},
1504                ast::MacroType(ty) => make_path_kind_type(ty.into()),
1505                _ => return None,
1506            }
1507        };
1508        Some(kind)
1509    };
1510    let make_path_kind_attr = |meta: ast::Meta| {
1511        let attr = meta.parent_attr()?;
1512        let kind = attr.kind();
1513        let attached = attr.syntax().parent()?;
1514        let is_trailing_outer_attr = kind != AttrKind::Inner
1515            && non_trivia_sibling(attr.syntax().clone().into(), syntax::Direction::Next).is_none();
1516        let annotated_item_kind = if is_trailing_outer_attr { None } else { Some(attached.kind()) };
1517        let derive_helpers = annotated_item_kind
1518            .filter(|kind| {
1519                matches!(
1520                    kind,
1521                    SyntaxKind::STRUCT
1522                        | SyntaxKind::ENUM
1523                        | SyntaxKind::UNION
1524                        | SyntaxKind::VARIANT
1525                        | SyntaxKind::TUPLE_FIELD
1526                        | SyntaxKind::RECORD_FIELD
1527                )
1528            })
1529            .and_then(|_| find_node_at_offset::<ast::Adt>(original_file, original_offset))
1530            .and_then(|adt| sema.derive_helpers_in_scope(&adt))
1531            .unwrap_or_default();
1532        Some(PathKind::Attr { attr_ctx: AttrCtx { kind, annotated_item_kind, derive_helpers } })
1533    };
1534
1535    // Infer the path kind
1536    let parent = path.syntax().parent()?;
1537    let kind = 'find_kind: {
1538        if parent.kind() == SyntaxKind::ERROR {
1539            if let Some(kind) = inbetween_body_and_decl_check(parent.clone()) {
1540                return Some(make_res(NameRefKind::Keyword(kind)));
1541            }
1542
1543            break 'find_kind kind_item(&parent)?;
1544        }
1545        match_ast! {
1546            match parent {
1547                ast::PathType(it) => make_path_kind_type(it.into()),
1548                ast::PathExpr(it) => {
1549                    if let Some(p) = it.syntax().parent() {
1550                        let p_kind = p.kind();
1551                        // The syntax node of interest, for which we want to check whether
1552                        // it is sandwiched between an item decl signature and its body.
1553                        let probe = if ast::ExprStmt::can_cast(p_kind) {
1554                            Some(p)
1555                        } else if ast::StmtList::can_cast(p_kind) {
1556                            Some(it.syntax().clone())
1557                        } else {
1558                            None
1559                        };
1560                        if let Some(kind) = probe.and_then(inbetween_body_and_decl_check) {
1561                            return Some(make_res(NameRefKind::Keyword(kind)));
1562                        }
1563                    }
1564
1565                    path_ctx.has_call_parens = it.syntax().parent().is_some_and(|it| ast::CallExpr::cast(it).is_some_and(|it| has_parens(&it)));
1566
1567                    make_path_kind_expr(it.into())
1568                },
1569                ast::TupleStructPat(it) => {
1570                    path_ctx.has_call_parens = true;
1571                    PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1572                },
1573                ast::RecordPat(it) => {
1574                    path_ctx.has_call_parens = true;
1575                    PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1576                },
1577                ast::PathPat(it) => {
1578                    PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())}
1579                },
1580                ast::MacroCall(it) => {
1581                    kind_macro_call(it)?
1582                },
1583                ast::Meta(meta) => make_path_kind_attr(meta)?,
1584                ast::VisibilityInner(it) => PathKind::Vis { has_in_token: it.in_token().is_some() },
1585                ast::UseTree(_) => PathKind::Use,
1586                // completing inside a qualifier
1587                ast::Path(parent) => {
1588                    path_ctx.parent = Some(parent.clone());
1589                    let parent = iter::successors(Some(parent), |it| it.parent_path()).last()?.syntax().parent()?;
1590                    match_ast! {
1591                        match parent {
1592                            ast::PathType(it) => make_path_kind_type(it.into()),
1593                            ast::PathExpr(it) => {
1594                                path_ctx.has_call_parens = it.syntax().parent().is_some_and(|it| ast::CallExpr::cast(it).is_some_and(|it| has_parens(&it)));
1595
1596                                make_path_kind_expr(it.into())
1597                            },
1598                            ast::TupleStructPat(it) => {
1599                                path_ctx.has_call_parens = true;
1600                                PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1601                            },
1602                            ast::RecordPat(it) => {
1603                                path_ctx.has_call_parens = true;
1604                                PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into()) }
1605                            },
1606                            ast::PathPat(it) => {
1607                                PathKind::Pat { pat_ctx: pattern_context_for(sema, original_file, it.into())}
1608                            },
1609                            ast::MacroCall(it) => {
1610                                kind_macro_call(it)?
1611                            },
1612                            ast::Meta(meta) => make_path_kind_attr(meta)?,
1613                            ast::VisibilityInner(it) => PathKind::Vis { has_in_token: it.in_token().is_some() },
1614                            ast::UseTree(_) => PathKind::Use,
1615                            ast::RecordExpr(it) => make_path_kind_expr(it.into()),
1616                            _ => return None,
1617                        }
1618                    }
1619                },
1620                ast::RecordExpr(it) => {
1621                    // A record expression in this position is usually a result of parsing recovery, so check that
1622                    if let Some(kind) = inbetween_body_and_decl_check(it.syntax().clone()) {
1623                        return Some(make_res(NameRefKind::Keyword(kind)));
1624                    }
1625                    make_path_kind_expr(it.into())
1626                },
1627                _ => return None,
1628            }
1629        }
1630    };
1631
1632    path_ctx.kind = kind;
1633    path_ctx.has_type_args = segment.generic_arg_list().is_some();
1634
1635    // calculate the qualifier context
1636    if let Some((qualifier, use_tree_parent)) = path_or_use_tree_qualifier(&path) {
1637        path_ctx.use_tree_parent = use_tree_parent;
1638        if !use_tree_parent && segment.coloncolon_token().is_some() {
1639            path_ctx.qualified = Qualified::Absolute;
1640        } else {
1641            let qualifier = qualifier
1642                .segment()
1643                .and_then(|it| find_node_in_file(original_file, &it))
1644                .map(|it| it.parent_path());
1645            if let Some(qualifier) = qualifier {
1646                let type_anchor = match qualifier.segment().and_then(|it| it.kind()) {
1647                    Some(ast::PathSegmentKind::Type { type_ref: Some(type_ref), trait_ref })
1648                        if qualifier.qualifier().is_none() =>
1649                    {
1650                        Some((type_ref, trait_ref))
1651                    }
1652                    _ => None,
1653                };
1654
1655                path_ctx.qualified = if let Some((ty, trait_ref)) = type_anchor {
1656                    let ty = match ty {
1657                        ast::Type::InferType(_) => None,
1658                        ty => sema.resolve_type(&ty),
1659                    };
1660                    let trait_ = trait_ref.and_then(|it| sema.resolve_trait(&it.path()?));
1661                    Qualified::TypeAnchor { ty, trait_ }
1662                } else {
1663                    let res = sema.resolve_path(&qualifier);
1664
1665                    // For understanding how and why super_chain_len is calculated the way it
1666                    // is check the documentation at its definition
1667                    let mut segment_count = 0;
1668                    let super_count = iter::successors(Some(qualifier.clone()), |p| p.qualifier())
1669                        .take_while(|p| {
1670                            p.segment()
1671                                .and_then(|s| {
1672                                    segment_count += 1;
1673                                    s.super_token()
1674                                })
1675                                .is_some()
1676                        })
1677                        .count();
1678
1679                    let super_chain_len =
1680                        if segment_count > super_count { None } else { Some(super_count) };
1681
1682                    Qualified::With { path: qualifier, resolution: res, super_chain_len }
1683                }
1684            };
1685        }
1686    } else if let Some(segment) = path.segment()
1687        && segment.coloncolon_token().is_some()
1688    {
1689        path_ctx.qualified = Qualified::Absolute;
1690    }
1691
1692    let mut qualifier_ctx = QualifierCtx::default();
1693    if path_ctx.is_trivial_path() {
1694        // fetch the full expression that may have qualifiers attached to it
1695        let top_node = match path_ctx.kind {
1696            PathKind::Expr { expr_ctx: PathExprCtx { in_block_expr: true, .. } } => {
1697                parent.ancestors().find(|it| ast::PathExpr::can_cast(it.kind())).and_then(|p| {
1698                    let parent = p.parent()?;
1699                    if ast::StmtList::can_cast(parent.kind()) {
1700                        Some(p)
1701                    } else if ast::ExprStmt::can_cast(parent.kind()) {
1702                        Some(parent)
1703                    } else {
1704                        None
1705                    }
1706                })
1707            }
1708            PathKind::Item { .. } => parent.ancestors().find(|it| it.kind() == SyntaxKind::ERROR),
1709            _ => None,
1710        };
1711        if let Some(top) = top_node {
1712            if let Some(NodeOrToken::Node(error_node)) =
1713                syntax::algo::non_trivia_sibling(top.clone().into(), syntax::Direction::Prev)
1714                && error_node.kind() == SyntaxKind::ERROR
1715            {
1716                for token in error_node.children_with_tokens().filter_map(NodeOrToken::into_token) {
1717                    match token.kind() {
1718                        SyntaxKind::UNSAFE_KW => qualifier_ctx.unsafe_tok = Some(token),
1719                        SyntaxKind::ASYNC_KW => qualifier_ctx.async_tok = Some(token),
1720                        SyntaxKind::SAFE_KW => qualifier_ctx.safe_tok = Some(token),
1721                        _ => {}
1722                    }
1723                }
1724                qualifier_ctx.vis_node = error_node.children().find_map(ast::Visibility::cast);
1725                qualifier_ctx.abi_node = error_node.children().find_map(ast::Abi::cast);
1726            }
1727
1728            if let PathKind::Item { .. } = path_ctx.kind
1729                && qualifier_ctx.none()
1730                && let Some(t) = top.first_token()
1731                && let Some(prev) =
1732                    t.prev_token().and_then(|t| syntax::algo::skip_trivia_token(t, Direction::Prev))
1733                && ![T![;], T!['}'], T!['{'], T![']']].contains(&prev.kind())
1734            {
1735                // This was inferred to be an item position path, but it seems
1736                // to be part of some other broken node which leaked into an item
1737                // list
1738                return None;
1739            }
1740        }
1741    }
1742    Some((NameRefContext { nameref, kind: NameRefKind::Path(path_ctx) }, qualifier_ctx))
1743}
1744
1745/// When writing in the middle of some code the following situation commonly occurs (`|` denotes the cursor):
1746/// ```ignore
1747/// value.method|
1748/// (1, 2, 3)
1749/// ```
1750/// Here, we want to complete the method parentheses & arguments (if the corresponding settings are on),
1751/// but the thing is parsed as a method call with parentheses. Therefore we use heuristics: if the parentheses
1752/// are on the next line, consider them non-existent.
1753fn has_parens(node: &dyn HasArgList) -> bool {
1754    let Some(arg_list) = node.arg_list() else { return false };
1755    if arg_list.l_paren_token().is_none() {
1756        return false;
1757    }
1758    let prev_siblings = iter::successors(arg_list.syntax().prev_sibling_or_token(), |it| {
1759        it.prev_sibling_or_token()
1760    });
1761    prev_siblings
1762        .take_while(|syntax| syntax.kind().is_trivia())
1763        .filter_map(|syntax| {
1764            syntax.into_token().filter(|token| token.kind() == SyntaxKind::WHITESPACE)
1765        })
1766        .all(|whitespace| !whitespace.text().contains('\n'))
1767}
1768
1769fn pattern_context_for(
1770    sema: &Semantics<'_, RootDatabase>,
1771    original_file: &SyntaxNode,
1772    pat: ast::Pat,
1773) -> PatternContext {
1774    let mut param_ctx = None;
1775
1776    let mut missing_variants = vec![];
1777    let is_pat_like = |kind| {
1778        ast::Pat::can_cast(kind)
1779            || ast::RecordPatField::can_cast(kind)
1780            || ast::RecordPatFieldList::can_cast(kind)
1781    };
1782
1783    let (refutability, has_type_ascription) = pat
1784        .syntax()
1785        .ancestors()
1786        .find(|it| !is_pat_like(it.kind()))
1787        .map_or((PatternRefutability::Irrefutable, false), |node| {
1788            let refutability = match_ast! {
1789                match node {
1790                    ast::LetStmt(let_) => return (PatternRefutability::Refutable, let_.ty().is_some()),
1791                    ast::Param(param) => {
1792                        let has_type_ascription = param.ty().is_some();
1793                        param_ctx = (|| {
1794                            let fake_param_list = param.syntax().parent().and_then(ast::ParamList::cast)?;
1795                            let param_list = find_node_in_file_compensated(sema, original_file, &fake_param_list)?;
1796                            let param_list_owner = param_list.syntax().parent()?;
1797                            let kind = match_ast! {
1798                                match param_list_owner {
1799                                    ast::ClosureExpr(closure) => ParamKind::Closure(closure),
1800                                    ast::Fn(fn_) => ParamKind::Function(fn_),
1801                                    _ => return None,
1802                                }
1803                            };
1804                            Some(ParamContext {
1805                                param_list, param, kind
1806                            })
1807                        })();
1808                        return (PatternRefutability::Irrefutable, has_type_ascription)
1809                    },
1810                    ast::MatchArm(match_arm) => {
1811                       let missing_variants_opt = match_arm
1812                            .syntax()
1813                            .parent()
1814                            .and_then(ast::MatchArmList::cast)
1815                            .and_then(|match_arm_list| {
1816                                match_arm_list
1817                                .syntax()
1818                                .parent()
1819                                .and_then(ast::MatchExpr::cast)
1820                                .and_then(|match_expr| {
1821                                    let expr_opt = find_opt_node_in_file(original_file, match_expr.expr());
1822
1823                                    expr_opt.and_then(|expr| {
1824                                        sema.type_of_expr(&expr)?
1825                                        .adjusted()
1826                                        .autoderef(sema.db)
1827                                        .find_map(|ty| match ty.as_adt() {
1828                                            Some(hir::Adt::Enum(e)) => Some(e),
1829                                            _ => None,
1830                                        }).map(|enum_| enum_.variants(sema.db))
1831                                    })
1832                                }).map(|variants| variants.iter().filter_map(|variant| {
1833                                        let variant_name = variant.name(sema.db);
1834
1835                                        let variant_already_present = match_arm_list.arms().any(|arm| {
1836                                            arm.pat().and_then(|pat| {
1837                                                let pat_already_present = pat.syntax().to_string().contains(variant_name.as_str());
1838                                                pat_already_present.then_some(pat_already_present)
1839                                            }).is_some()
1840                                        });
1841
1842                                        (!variant_already_present).then_some(*variant)
1843                                    }).collect::<Vec<EnumVariant>>())
1844                        });
1845
1846                        if let Some(missing_variants_) = missing_variants_opt {
1847                            missing_variants = missing_variants_;
1848                        };
1849
1850                        PatternRefutability::Refutable
1851                    },
1852                    ast::LetExpr(_) => PatternRefutability::Refutable,
1853                    ast::ForExpr(_) => PatternRefutability::Irrefutable,
1854                    _ => PatternRefutability::Irrefutable,
1855                }
1856            };
1857            (refutability, false)
1858        });
1859    let (ref_token, mut_token) = match &pat {
1860        ast::Pat::IdentPat(it) => (it.ref_token(), it.mut_token()),
1861        _ => (None, None),
1862    };
1863
1864    // Only suggest name in let-stmt or fn param
1865    let should_suggest_name = matches!(
1866            &pat,
1867            ast::Pat::IdentPat(it)
1868                if it.syntax()
1869                .parent().is_some_and(|node| {
1870                    let kind = node.kind();
1871                    ast::LetStmt::can_cast(kind) || ast::Param::can_cast(kind)
1872                })
1873    );
1874
1875    PatternContext {
1876        refutability,
1877        param_ctx,
1878        has_type_ascription,
1879        should_suggest_name,
1880        after_if_expr: is_after_if_expr(pat.syntax().clone()),
1881        parent_pat: pat.syntax().parent().and_then(ast::Pat::cast),
1882        mut_token,
1883        ref_token,
1884        record_pat: None,
1885        impl_or_trait: fetch_immediate_impl_or_trait(sema, original_file, pat.syntax()),
1886        missing_variants,
1887    }
1888}
1889
1890fn fetch_immediate_impl_or_trait(
1891    sema: &Semantics<'_, RootDatabase>,
1892    original_file: &SyntaxNode,
1893    node: &SyntaxNode,
1894) -> Option<Either<ast::Impl, ast::Trait>> {
1895    let mut ancestors = ancestors_in_file_compensated(sema, original_file, node)?
1896        .filter_map(ast::Item::cast)
1897        .filter(|it| !matches!(it, ast::Item::MacroCall(_)));
1898
1899    match ancestors.next()? {
1900        ast::Item::Const(_) | ast::Item::Fn(_) | ast::Item::TypeAlias(_) => (),
1901        ast::Item::Impl(it) => return Some(Either::Left(it)),
1902        ast::Item::Trait(it) => return Some(Either::Right(it)),
1903        _ => return None,
1904    }
1905    match ancestors.next()? {
1906        ast::Item::Impl(it) => Some(Either::Left(it)),
1907        ast::Item::Trait(it) => Some(Either::Right(it)),
1908        _ => None,
1909    }
1910}
1911
1912/// Attempts to find `node` inside `syntax` via `node`'s text range.
1913/// If the fake identifier has been inserted after this node or inside of this node use the `_compensated` version instead.
1914fn find_opt_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: Option<N>) -> Option<N> {
1915    find_node_in_file(syntax, &node?)
1916}
1917
1918/// Attempts to find `node` inside `syntax` via `node`'s text range.
1919/// If the fake identifier has been inserted after this node or inside of this node use the `_compensated` version instead.
1920fn find_node_in_file<N: AstNode>(syntax: &SyntaxNode, node: &N) -> Option<N> {
1921    let syntax_range = syntax.text_range();
1922    let range = node.syntax().text_range();
1923    let intersection = range.intersect(syntax_range)?;
1924    syntax.covering_element(intersection).ancestors().find_map(N::cast)
1925}
1926
1927/// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1928/// for the offset introduced by the fake ident.
1929/// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1930fn find_node_in_file_compensated<N: AstNode>(
1931    sema: &Semantics<'_, RootDatabase>,
1932    in_file: &SyntaxNode,
1933    node: &N,
1934) -> Option<N> {
1935    ancestors_in_file_compensated(sema, in_file, node.syntax())?.find_map(N::cast)
1936}
1937
1938fn ancestors_in_file_compensated<'sema>(
1939    sema: &'sema Semantics<'_, RootDatabase>,
1940    in_file: &SyntaxNode,
1941    node: &SyntaxNode,
1942) -> Option<impl Iterator<Item = SyntaxNode> + 'sema> {
1943    let syntax_range = in_file.text_range();
1944    let range = node.text_range();
1945    let end = range.end().checked_sub(TextSize::try_from(COMPLETION_MARKER.len()).ok()?)?;
1946    if end < range.start() {
1947        return None;
1948    }
1949    let range = TextRange::new(range.start(), end);
1950    // our inserted ident could cause `range` to go outside of the original syntax, so cap it
1951    let intersection = range.intersect(syntax_range)?;
1952    let node = match in_file.covering_element(intersection) {
1953        NodeOrToken::Node(node) => node,
1954        NodeOrToken::Token(tok) => tok.parent()?,
1955    };
1956    Some(sema.ancestors_with_macros(node))
1957}
1958
1959/// Attempts to find `node` inside `syntax` via `node`'s text range while compensating
1960/// for the offset introduced by the fake ident..
1961/// This is wrong if `node` comes before the insertion point! Use `find_node_in_file` instead.
1962fn find_opt_node_in_file_compensated<N: AstNode>(
1963    sema: &Semantics<'_, RootDatabase>,
1964    syntax: &SyntaxNode,
1965    node: Option<N>,
1966) -> Option<N> {
1967    find_node_in_file_compensated(sema, syntax, &node?)
1968}
1969
1970fn path_or_use_tree_qualifier(path: &ast::Path) -> Option<(ast::Path, bool)> {
1971    if let Some(qual) = path.qualifier() {
1972        return Some((qual, false));
1973    }
1974    let use_tree_list = path.syntax().ancestors().find_map(ast::UseTreeList::cast)?;
1975    let use_tree = use_tree_list.syntax().parent().and_then(ast::UseTree::cast)?;
1976    Some((use_tree.path()?, true))
1977}
1978
1979fn left_ancestors(node: Option<SyntaxNode>) -> impl Iterator<Item = SyntaxNode> {
1980    node.into_iter().flat_map(|node| {
1981        let end = node.text_range().end();
1982        node.ancestors().take_while(move |it| it.text_range().end() == end)
1983    })
1984}
1985
1986fn is_in_token_of_for_loop(path: &ast::Path) -> bool {
1987    // oh my ...
1988    (|| {
1989        let expr = path.syntax().parent().and_then(ast::PathExpr::cast)?;
1990        let for_expr = expr.syntax().parent().and_then(ast::ForExpr::cast)?;
1991        if for_expr.in_token().is_some() {
1992            return Some(false);
1993        }
1994        let pat = for_expr.pat()?;
1995        let next_sibl = next_non_trivia_sibling(pat.syntax().clone().into())?;
1996        Some(match next_sibl {
1997            syntax::NodeOrToken::Node(n) => {
1998                n.text_range().start() == path.syntax().text_range().start()
1999            }
2000            syntax::NodeOrToken::Token(t) => {
2001                t.text_range().start() == path.syntax().text_range().start()
2002            }
2003        })
2004    })()
2005    .unwrap_or(false)
2006}
2007
2008fn is_in_breakable(node: &SyntaxNode) -> Option<(BreakableKind, SyntaxNode)> {
2009    node.ancestors()
2010        .take_while(|it| it.kind() != SyntaxKind::FN && it.kind() != SyntaxKind::CLOSURE_EXPR)
2011        .find_map(|it| {
2012            let (breakable, loop_body) = match_ast! {
2013                match it {
2014                    ast::ForExpr(it) => (BreakableKind::For, it.loop_body()?),
2015                    ast::WhileExpr(it) => (BreakableKind::While, it.loop_body()?),
2016                    ast::LoopExpr(it) => (BreakableKind::Loop, it.loop_body()?),
2017                    ast::BlockExpr(it) => return it.label().map(|_| (BreakableKind::Block, it.syntax().clone())),
2018                    _ => return None,
2019                }
2020            };
2021            loop_body.syntax().text_range().contains_range(node.text_range())
2022                .then_some((breakable, it))
2023        })
2024}
2025
2026fn is_in_block(node: &SyntaxNode) -> bool {
2027    if has_in_newline_expr_first(node) {
2028        return true;
2029    };
2030    node.parent()
2031        .map(|node| ast::ExprStmt::can_cast(node.kind()) || ast::StmtList::can_cast(node.kind()))
2032        .unwrap_or(false)
2033}
2034
2035/// Similar to `has_parens`, heuristic sensing incomplete statement before ambiguous `Expr`
2036///
2037/// Heuristic:
2038///
2039/// If the `PathExpr` is left part of the `Expr` and there is a newline after the `PathExpr`,
2040/// it is considered that the `PathExpr` is not part of the `Expr`.
2041fn has_in_newline_expr_first(node: &SyntaxNode) -> bool {
2042    if ast::PathExpr::can_cast(node.kind())
2043        && let Some(NodeOrToken::Token(next)) = node.next_sibling_or_token()
2044        && next.kind() == SyntaxKind::WHITESPACE
2045        && next.text().contains('\n')
2046        && let Some(stmt_like) = node
2047            .ancestors()
2048            .take_while(|it| it.text_range().start() == node.text_range().start())
2049            .filter_map(Either::<ast::ExprStmt, ast::Expr>::cast)
2050            .last()
2051    {
2052        stmt_like.syntax().parent().and_then(ast::StmtList::cast).is_some()
2053    } else {
2054        false
2055    }
2056}
2057
2058fn is_after_if_expr(node: SyntaxNode) -> bool {
2059    let node = match node.parent().and_then(Either::<ast::ExprStmt, ast::MatchArm>::cast) {
2060        Some(stmt) => stmt.syntax().clone(),
2061        None => node,
2062    };
2063    let Some(prev_token) = previous_non_trivia_token(node) else { return false };
2064    prev_token
2065        .parent_ancestors()
2066        .take_while(|it| it.text_range().end() == prev_token.text_range().end())
2067        .find_map(ast::IfExpr::cast)
2068        .is_some()
2069}
2070
2071fn next_non_trivia_token(e: impl Into<SyntaxElement>) -> Option<SyntaxToken> {
2072    let mut token = match e.into() {
2073        SyntaxElement::Node(n) => n.last_token()?,
2074        SyntaxElement::Token(t) => t,
2075    }
2076    .next_token();
2077    while let Some(inner) = token {
2078        if !inner.kind().is_trivia() {
2079            return Some(inner);
2080        } else {
2081            token = inner.next_token();
2082        }
2083    }
2084    None
2085}
2086
2087fn next_non_trivia_sibling(ele: SyntaxElement) -> Option<SyntaxElement> {
2088    let mut e = ele;
2089    while let Some(next) = e.next_sibling_or_token() {
2090        if !next.kind().is_trivia() {
2091            return Some(next);
2092        } else {
2093            e = next;
2094        }
2095    }
2096    None
2097}
2098
2099fn prev_special_biased_token_at_trivia(mut token: SyntaxToken) -> SyntaxToken {
2100    while token.kind().is_trivia()
2101        && let Some(prev) = token.prev_token()
2102        && let T![=]
2103        | T![+=]
2104        | T![/=]
2105        | T![*=]
2106        | T![%=]
2107        | T![>>=]
2108        | T![<<=]
2109        | T![-=]
2110        | T![|=]
2111        | T![&=]
2112        | T![^=]
2113        | T![|]
2114        | T![return]
2115        | T![break]
2116        | T![continue]
2117        | T![lifetime_ident] = prev.kind()
2118    {
2119        token = prev
2120    }
2121    token
2122}