Skip to main content

hir/
source_analyzer.rs

1//! Lookup hir elements using positions in the source code. This is a lossy
2//! transformation: in general, a single source might correspond to several
3//! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on
4//! modules.
5//!
6//! So, this modules should not be used during hir construction, it exists
7//! purely for "IDE needs".
8use std::{
9    cell::OnceCell,
10    iter::{self, once},
11};
12
13use either::Either;
14use hir_def::{
15    AdtId, AssocItemId, CallableDefId, ConstId, DefWithBodyId, ExpressionStoreOwnerId, FieldId,
16    FunctionId, GenericDefId, HasModule, LocalFieldId, LoweringMode, ModuleDefId, StructId,
17    VariantId,
18    expr_store::{
19        Body, BodySourceMap, ExpressionStore, ExpressionStoreSourceMap, HygieneId,
20        lower::{ExprCollector, lower_generic_params},
21        path::Path,
22        scope::{ExprScopes, ScopeId},
23    },
24    hir::{BindingId, Expr, ExprId, ExprOrPatId, Pat, PatId, generics::GenericParams},
25    lang_item::LangItems,
26    nameres::MacroSubNs,
27    resolver::{ResolveValueResult, Resolver, TypeNs, ValueNs, resolver_for_scope},
28    type_ref::{ConstRef, Mutability, TypeRefId},
29    visibility::Visibility,
30};
31use hir_expand::{
32    HirFileId, InFile,
33    mod_path::{ModPath, PathKind, path},
34    name::{AsName, Name},
35};
36use hir_ide::{
37    Adjustment, InferBodyId, InferenceResult, LifetimeElisionKind, LifetimeLoweringMode,
38    ParamEnvAndCrate, TyLoweringContext, TyLoweringInferVarsCtx,
39    diagnostics::{
40        InsideUnsafeBlock, record_literal_missing_fields, record_pattern_missing_fields,
41        unsafe_operations,
42    },
43    lang_items::lang_items_for_bin_op,
44    method_resolution::{self, CandidateId},
45    next_solver::{
46        AliasTy, DbInterner, DefaultAny, EarlyBinder, ErrorGuaranteed, GenericArgs, ParamEnv,
47        Region, Ty, TyKind, TypingMode, infer::DbInternerInferExt,
48    },
49    traits::{WherePredicateEvaluation, structurally_normalize_ty, where_predicate_must_hold},
50};
51use intern::sym;
52use itertools::Itertools;
53use rustc_hash::FxHashSet;
54use rustc_type_ir::{
55    AliasTyKind,
56    inherent::{IntoKind, Term as _, Ty as _},
57};
58use smallvec::SmallVec;
59use stdx::never;
60use syntax::{
61    SyntaxKind, SyntaxNode, TextRange, TextSize,
62    ast::{self, AstNode, RangeItem, RangeOp},
63};
64
65use crate::{
66    Adt, AnyFunctionId, AssocItem, BindingMode, BuiltinAttr, BuiltinType, Callable, Const,
67    DeriveHelper, EnumVariant, Field, Function, GenericSubstitution, Local, Macro, ModuleDef,
68    PredicateEvaluationResult, SemanticsImpl, Static, Struct, ToolModule, Trait, TupleField, Type,
69    TypeAlias, TypeOwnerId,
70    db::HirDatabase,
71    semantics::{PathResolution, PathResolutionPerNs},
72};
73
74/// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of
75/// original source files. It should not be used inside the HIR itself.
76#[derive(Debug)]
77pub(crate) struct SourceAnalyzer<'db> {
78    pub(crate) file_id: HirFileId,
79    pub(crate) resolver: Resolver<'db>,
80    pub(crate) body_or_sig: Option<BodyOrSig<'db>>,
81    pub(crate) type_owner: TypeOwnerId,
82    pub(crate) infer_body: Option<InferBodyId<'db>>,
83}
84
85#[derive(Debug)]
86pub(crate) enum BodyOrSig<'db> {
87    Body {
88        def: DefWithBodyId,
89        body: &'db Body,
90        source_map: &'db BodySourceMap,
91        infer: Option<&'db InferenceResult<'db>>,
92    },
93    VariantFields {
94        def: VariantId,
95        store: &'db ExpressionStore,
96        source_map: &'db ExpressionStoreSourceMap,
97        infer: Option<&'db InferenceResult<'db>>,
98    },
99    Sig {
100        def: GenericDefId,
101        store: &'db ExpressionStore,
102        source_map: &'db ExpressionStoreSourceMap,
103        infer: Option<&'db InferenceResult<'db>>,
104        #[expect(dead_code)]
105        generics: &'db GenericParams,
106    },
107}
108
109impl<'db> SourceAnalyzer<'db> {
110    pub(crate) fn new_for_body(
111        db: &'db dyn HirDatabase,
112        def: DefWithBodyId,
113        node: InFile<&SyntaxNode>,
114        offset: Option<TextSize>,
115    ) -> SourceAnalyzer<'db> {
116        Self::new_for_body_(db, def, node, offset, Some(InferenceResult::of(db, def)))
117    }
118
119    pub(crate) fn new_for_body_no_infer(
120        db: &'db dyn HirDatabase,
121        def: DefWithBodyId,
122        node: InFile<&SyntaxNode>,
123        offset: Option<TextSize>,
124    ) -> SourceAnalyzer<'db> {
125        Self::new_for_body_(db, def, node, offset, None)
126    }
127
128    pub(crate) fn new_for_body_(
129        db: &'db dyn HirDatabase,
130        def: DefWithBodyId,
131        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
132        offset: Option<TextSize>,
133        infer: Option<&'db InferenceResult<'db>>,
134    ) -> SourceAnalyzer<'db> {
135        let (body, source_map) = Body::with_source_map(db, def);
136        let scopes = ExprScopes::of(db, def);
137        let scope = match offset {
138            None => scope_for(db, scopes, source_map, node),
139            Some(offset) => {
140                debug_assert!(
141                    node.text_range().contains_inclusive(offset),
142                    "{:?} not in {:?}",
143                    offset,
144                    node.text_range()
145                );
146                scope_for_offset(db, scopes, source_map, node.file_id, offset)
147            }
148        };
149        let (scope, _expr) = scope.unzip();
150        let resolver = resolver_for_scope(db, def, scope);
151        SourceAnalyzer {
152            resolver,
153            body_or_sig: Some(BodyOrSig::Body { def, body, source_map, infer }),
154            file_id,
155            type_owner: def.generic_def(db).into(),
156            infer_body: Some(def.into()),
157        }
158    }
159
160    pub(crate) fn new_generic_def(
161        db: &'db dyn HirDatabase,
162        sema: &SemanticsImpl<'db>,
163        def: GenericDefId,
164        node: InFile<&SyntaxNode>,
165        offset: Option<TextSize>,
166    ) -> SourceAnalyzer<'db> {
167        Self::new_generic_def_(db, sema, def, node, offset, true)
168    }
169
170    pub(crate) fn new_generic_def_no_infer(
171        db: &'db dyn HirDatabase,
172        sema: &SemanticsImpl<'db>,
173        def: GenericDefId,
174        node: InFile<&SyntaxNode>,
175        offset: Option<TextSize>,
176    ) -> SourceAnalyzer<'db> {
177        Self::new_generic_def_(db, sema, def, node, offset, false)
178    }
179
180    pub(crate) fn new_generic_def_(
181        db: &'db dyn HirDatabase,
182        sema: &SemanticsImpl<'db>,
183        def: GenericDefId,
184        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
185        offset: Option<TextSize>,
186        infer: bool,
187    ) -> SourceAnalyzer<'db> {
188        let (generics, store, source_map) = GenericParams::with_source_map(db, def);
189        let scopes = ExprScopes::of(db, def);
190        let scope = match offset {
191            None => scope_for(db, scopes, source_map, node),
192            Some(offset) => {
193                debug_assert!(
194                    node.text_range().contains_inclusive(offset),
195                    "{:?} not in {:?}",
196                    offset,
197                    node.text_range()
198                );
199                scope_for_offset(db, scopes, source_map, node.file_id, offset)
200            }
201        };
202        let (scope, expr) = scope.unzip();
203        let resolver = resolver_for_scope(db, def, scope);
204        let infer_body = expr.and_then(|expr| {
205            sema.infer_body_for_expr_or_pat(
206                ExpressionStoreOwnerId::Signature(def),
207                store,
208                expr.into(),
209            )
210        });
211        let infer = if infer && let Some(infer_body) = infer_body {
212            Some(InferenceResult::of(db, infer_body))
213        } else {
214            None
215        };
216        SourceAnalyzer {
217            resolver,
218            body_or_sig: Some(BodyOrSig::Sig { def, store, source_map, generics, infer }),
219            file_id,
220            type_owner: def.into(),
221            infer_body,
222        }
223    }
224
225    pub(crate) fn new_variant_body(
226        db: &'db dyn HirDatabase,
227        sema: &SemanticsImpl<'db>,
228        def: VariantId,
229        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,
230        offset: Option<TextSize>,
231        infer: bool,
232    ) -> SourceAnalyzer<'db> {
233        let (fields, source_map) = def.fields_with_source_map(db);
234        let scopes = ExprScopes::of(db, def);
235        let scope = match offset {
236            None => scope_for(db, scopes, source_map, node),
237            Some(offset) => {
238                debug_assert!(
239                    node.text_range().contains_inclusive(offset),
240                    "{:?} not in {:?}",
241                    offset,
242                    node.text_range()
243                );
244                scope_for_offset(db, scopes, source_map, node.file_id, offset)
245            }
246        };
247        let (scope, expr) = scope.unzip();
248        let resolver = resolver_for_scope(db, def, scope);
249        let infer_body = expr.and_then(|expr| {
250            sema.infer_body_for_expr_or_pat(
251                ExpressionStoreOwnerId::VariantFields(def),
252                &fields.store,
253                expr.into(),
254            )
255        });
256        let infer = if infer && let Some(infer_body) = infer_body {
257            Some(InferenceResult::of(db, infer_body))
258        } else {
259            None
260        };
261        SourceAnalyzer {
262            resolver,
263            body_or_sig: Some(BodyOrSig::VariantFields {
264                def,
265                store: &fields.store,
266                source_map,
267                infer,
268            }),
269            file_id,
270            type_owner: GenericDefId::from(def.adt_id(db)).into(),
271            infer_body,
272        }
273    }
274
275    pub(crate) fn new_for_resolver(
276        resolver: Resolver<'db>,
277        node: InFile<&SyntaxNode>,
278    ) -> SourceAnalyzer<'db> {
279        SourceAnalyzer {
280            type_owner: resolver
281                .generic_def()
282                .map(Into::into)
283                .unwrap_or_else(|| TypeOwnerId::NoParams(resolver.krate())),
284            resolver,
285            body_or_sig: None,
286            file_id: node.file_id,
287            infer_body: None,
288        }
289    }
290
291    fn owner(&self) -> Option<ExpressionStoreOwnerId> {
292        self.body_or_sig.as_ref().map(|it| match *it {
293            BodyOrSig::VariantFields { def, .. } => def.into(),
294            BodyOrSig::Sig { def, .. } => def.into(),
295            BodyOrSig::Body { def, .. } => def.into(),
296        })
297    }
298
299    fn infer(&self) -> Option<&'db InferenceResult<'db>> {
300        self.body_or_sig.as_ref().and_then(|it| match *it {
301            BodyOrSig::VariantFields { infer, .. }
302            | BodyOrSig::Sig { infer, .. }
303            | BodyOrSig::Body { infer, .. } => infer,
304        })
305    }
306
307    pub(crate) fn ty(&self, ty: Ty<'db>) -> Type<'db> {
308        Type { owner: self.type_owner, ty: EarlyBinder::bind(ty) }
309    }
310
311    pub(crate) fn def(
312        &self,
313    ) -> Option<(
314        ExpressionStoreOwnerId,
315        &'db ExpressionStore,
316        &'db ExpressionStoreSourceMap,
317        Option<&'db InferenceResult<'db>>,
318    )> {
319        self.body_or_sig.as_ref().map(|it| match *it {
320            BodyOrSig::VariantFields { def, store, source_map, infer, .. } => {
321                (def.into(), store, source_map, infer)
322            }
323            BodyOrSig::Sig { def, store, source_map, infer, .. } => {
324                (def.into(), store, source_map, infer)
325            }
326            BodyOrSig::Body { def, body, source_map, infer, .. } => {
327                (def.into(), &body.store, &source_map.store, infer)
328            }
329        })
330    }
331
332    pub(crate) fn store(&self) -> Option<&'db ExpressionStore> {
333        self.body_or_sig.as_ref().map(|it| match *it {
334            BodyOrSig::Sig { store, .. } => store,
335            BodyOrSig::VariantFields { store, .. } => store,
336            BodyOrSig::Body { body, .. } => &body.store,
337        })
338    }
339
340    pub(crate) fn store_sm(&self) -> Option<&'db ExpressionStoreSourceMap> {
341        self.body_or_sig.as_ref().map(|it| match *it {
342            BodyOrSig::Sig { source_map, .. } => source_map,
343            BodyOrSig::VariantFields { source_map, .. } => source_map,
344            BodyOrSig::Body { source_map, .. } => &source_map.store,
345        })
346    }
347
348    fn param_and<'a>(&self, param_env: ParamEnv<'a>) -> ParamEnvAndCrate<'a> {
349        ParamEnvAndCrate { param_env, krate: self.resolver.krate() }
350    }
351
352    fn trait_environment(&self, db: &'db dyn HirDatabase) -> ParamEnvAndCrate<'db> {
353        self.param_and(self.body_or_sig.as_ref().map_or_else(ParamEnv::empty, |body_or_sig| {
354            let def = match *body_or_sig {
355                BodyOrSig::Body { def, .. } => def.generic_def(db),
356                BodyOrSig::VariantFields { def, .. } => match def {
357                    VariantId::EnumVariantId(def) => def.loc(db).parent.into(),
358                    VariantId::StructId(def) => def.into(),
359                    VariantId::UnionId(def) => def.into(),
360                },
361                BodyOrSig::Sig { def, .. } => def,
362            };
363            db.trait_environment(def)
364        }))
365    }
366
367    pub(crate) fn evaluate_where_clause(
368        &self,
369        db: &'db dyn HirDatabase,
370        where_clause: ast::WhereClause,
371    ) -> PredicateEvaluationResult {
372        let Some(owner) = self.owner() else {
373            // FIXME
374            return PredicateEvaluationResult::unsupported(
375                "predicate evaluation is only supported inside an item",
376            );
377        };
378        let generic_def = owner.generic_def(db);
379        let module = generic_def.module(db);
380        let (store, params, _) = lower_generic_params(
381            db,
382            module,
383            generic_def,
384            self.file_id,
385            None,
386            Some(where_clause),
387            LoweringMode::Ide,
388        );
389        let predicates = params.where_predicates();
390        if predicates.is_empty() {
391            return PredicateEvaluationResult::holds("predicate does not impose any obligations");
392        }
393
394        let env = self.trait_environment(db);
395        for predicate in predicates {
396            match where_predicate_must_hold(
397                db,
398                &self.resolver,
399                &store,
400                owner,
401                generic_def,
402                env,
403                predicate,
404            ) {
405                WherePredicateEvaluation::Holds | WherePredicateEvaluation::NoObligations => {}
406                WherePredicateEvaluation::HasErrors => {
407                    return PredicateEvaluationResult::invalid(
408                        "predicate contains unresolved names or invalid type syntax",
409                    );
410                }
411                WherePredicateEvaluation::NotProven => {
412                    return PredicateEvaluationResult::not_proven("predicate is not known to hold");
413                }
414            }
415        }
416
417        PredicateEvaluationResult::holds("predicate holds")
418    }
419
420    pub(crate) fn expr_id(&self, expr: ast::Expr) -> Option<ExprOrPatId> {
421        let src = InFile { file_id: self.file_id, value: expr };
422        self.store_sm()?.node_expr(src.as_ref())
423    }
424
425    fn pat_id(&self, pat: &ast::Pat) -> Option<ExprOrPatId> {
426        let src = InFile { file_id: self.file_id, value: pat };
427        self.store_sm()?.node_pat(src)
428    }
429
430    fn type_id(&self, pat: &ast::Type) -> Option<TypeRefId> {
431        let src = InFile { file_id: self.file_id, value: pat };
432        self.store_sm()?.node_type(src)
433    }
434
435    fn binding_id_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingId> {
436        let pat_id = self.pat_id(&pat.clone().into())?;
437        if let Pat::Bind { id, .. } = self.store()?[pat_id.as_pat()?] { Some(id) } else { None }
438    }
439
440    pub(crate) fn expr_adjustments(&self, expr: &ast::Expr) -> Option<&[Adjustment]> {
441        // It is safe to omit destructuring assignments here because they have no adjustments (neither
442        // expressions nor patterns).
443        let expr_id = self.expr_id(expr.clone())?.as_expr()?;
444        let infer = self.infer()?;
445        infer.expr_adjustment(expr_id)
446    }
447
448    pub(crate) fn type_of_type(
449        &self,
450        db: &'db dyn HirDatabase,
451        ty: &ast::Type,
452    ) -> Option<Type<'db>> {
453        let interner = DbInterner::new_no_crate(db);
454
455        let type_ref = self.type_id(ty)?;
456
457        let generic_def = self.resolver.generic_def()?;
458        let generics = OnceCell::new();
459        let mut vars_cts = VarsCtx { types: interner.default_types(), infer: self.infer() };
460        let ty = TyLoweringContext::new(
461            db,
462            &self.resolver,
463            self.store()?,
464            self.resolver.expression_store_owner().unwrap_or_else(|| generic_def.into()),
465            generic_def,
466            &generics,
467            // FIXME: Is this correct here? Anyway that should impact mostly diagnostics, which we don't emit here
468            // (this can impact the lifetimes generated, e.g. in `const` they won't be `'static`, but this seems like a
469            // small problem).
470            LifetimeElisionKind::Infer,
471            LifetimeLoweringMode::LateParam,
472        )
473        .with_interning_mode(LoweringMode::Ide)
474        .with_infer_vars_behavior(Some(&mut vars_cts))
475        .lower_ty(type_ref);
476
477        struct VarsCtx<'a, 'db> {
478            types: &'a DefaultAny<'db>,
479            infer: Option<&'a InferenceResult<'db>>,
480        }
481
482        impl<'db> TyLoweringInferVarsCtx<'db> for VarsCtx<'_, 'db> {
483            fn next_ty_var(&mut self, span: hir_ide::Span) -> Ty<'db> {
484                let term_ref = match span {
485                    hir_ide::Span::TypeRefId(type_ref) => type_ref.into(),
486                    _ => return self.types.types.error,
487                };
488
489                self.infer
490                    .and_then(|infer| infer.term_of_term_placeholder(term_ref))
491                    .and_then(|term| term.as_type())
492                    .unwrap_or(self.types.types.error)
493            }
494            fn next_const_var(&mut self, span: hir_ide::Span) -> hir_ide::next_solver::Const<'db> {
495                let term_ref = match span {
496                    hir_ide::Span::TypeRefId(type_ref) => type_ref.into(),
497                    hir_ide::Span::ExprId(expr) => ConstRef { expr }.into(),
498                    _ => return self.types.consts.error,
499                };
500
501                self.infer
502                    .and_then(|infer| infer.term_of_term_placeholder(term_ref))
503                    .and_then(|generic_arg| generic_arg.as_const())
504                    .unwrap_or(self.types.consts.error)
505            }
506            fn next_region_var(&mut self, _span: hir_ide::Span) -> Region<'db> {
507                self.types.regions.error
508            }
509        }
510
511        Some(self.ty(ty))
512    }
513
514    pub(crate) fn expr_is_diverging(
515        &self,
516        _db: &'db dyn HirDatabase,
517        expr: &ast::Expr,
518    ) -> Option<bool> {
519        let expr_id = self.expr_id(expr.clone())?;
520        let store = self.store()?;
521        let infer = self.infer()?;
522        Some(self.expr_id_is_diverging(store, infer, expr_id))
523    }
524
525    fn expr_id_is_diverging(
526        &self,
527        store: &ExpressionStore,
528        infer: &InferenceResult<'_>,
529        expr_id: ExprOrPatId,
530    ) -> bool {
531        // FIXME: This is an approximation, perhaps we need to store a set of diverging exprs in inference?
532        if infer.type_of_expr_or_pat(expr_id).is_some_and(|ty| ty.is_never()) {
533            true
534        } else if let ExprOrPatId::ExprId(expr_id) = expr_id
535            && let Expr::Block { tail: Some(tail), .. } = store[expr_id]
536        {
537            self.expr_id_is_diverging(store, infer, tail.into())
538        } else {
539            false
540        }
541    }
542
543    pub(crate) fn type_of_expr(
544        &self,
545        _db: &'db dyn HirDatabase,
546        expr: &ast::Expr,
547    ) -> Option<(Type<'db>, Option<Type<'db>>)> {
548        let expr_id = self.expr_id(expr.clone())?;
549        let infer = self.infer()?;
550        let coerced = expr_id
551            .as_expr()
552            .and_then(|expr_id| infer.expr_adjustment(expr_id))
553            .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.as_ref()));
554        let ty = infer.expr_or_pat_ty(expr_id);
555        let mk_ty = |ty: Ty<'db>| self.ty(ty);
556        Some((mk_ty(ty), coerced.map(mk_ty)))
557    }
558
559    pub(crate) fn type_of_pat(
560        &self,
561        _db: &'db dyn HirDatabase,
562        pat: &ast::Pat,
563    ) -> Option<(Type<'db>, Option<Type<'db>>)> {
564        let expr_or_pat_id = self.pat_id(pat)?;
565        let infer = self.infer()?;
566        let coerced = match expr_or_pat_id {
567            ExprOrPatId::ExprId(idx) => infer
568                .expr_adjustment(idx)
569                .and_then(|adjusts| adjusts.last())
570                .map(|adjust| adjust.target.as_ref()),
571            ExprOrPatId::PatId(idx) => infer
572                .pat_adjustment(idx)
573                .and_then(|adjusts| adjusts.last())
574                .map(|adjust| adjust.source.as_ref()),
575        };
576
577        let ty = infer.expr_or_pat_ty(expr_or_pat_id);
578        let mk_ty = |ty: Ty<'db>| self.ty(ty);
579        Some((mk_ty(ty), coerced.map(mk_ty)))
580    }
581
582    pub(crate) fn type_of_binding_in_pat(
583        &self,
584        _db: &'db dyn HirDatabase,
585        pat: &ast::IdentPat,
586    ) -> Option<Type<'db>> {
587        let binding_id = self.binding_id_of_pat(pat)?;
588        let infer = self.infer()?;
589        let ty = infer.binding_ty(binding_id);
590        let mk_ty = |ty: Ty<'db>| self.ty(ty);
591        Some(mk_ty(ty))
592    }
593
594    pub(crate) fn type_of_self(
595        &self,
596        _db: &'db dyn HirDatabase,
597        _param: &ast::SelfParam,
598    ) -> Option<Type<'db>> {
599        let binding = match self.body_or_sig.as_ref()? {
600            BodyOrSig::Sig { .. } | BodyOrSig::VariantFields { .. } => return None,
601            BodyOrSig::Body { body, .. } => body.self_param?.formal,
602        };
603        let ty = self.infer()?.binding_ty(binding);
604        Some(self.ty(ty))
605    }
606
607    pub(crate) fn binding_mode_of_pat(
608        &self,
609        _db: &'db dyn HirDatabase,
610        pat: &ast::IdentPat,
611    ) -> Option<BindingMode> {
612        let id = self.pat_id(&pat.clone().into())?;
613        let infer = self.infer()?;
614        Some(match infer.binding_mode(id.as_pat()?)? {
615            hir_ide::BindingMode(hir_ide::ByRef::No, _) => BindingMode::Move,
616            hir_ide::BindingMode(hir_ide::ByRef::Yes(hir_ide::next_solver::Mutability::Mut), _) => {
617                BindingMode::Ref(Mutability::Mut)
618            }
619            hir_ide::BindingMode(hir_ide::ByRef::Yes(hir_ide::next_solver::Mutability::Not), _) => {
620                BindingMode::Ref(Mutability::Shared)
621            }
622        })
623    }
624    pub(crate) fn pattern_adjustments(
625        &self,
626        _db: &'db dyn HirDatabase,
627        pat: &ast::Pat,
628    ) -> Option<SmallVec<[Type<'db>; 1]>> {
629        let pat_id = self.pat_id(pat)?;
630        let infer = self.infer()?;
631        Some(
632            infer
633                .pat_adjustment(pat_id.as_pat()?)?
634                .iter()
635                .map(|adjust| self.ty(adjust.source.as_ref()))
636                .collect(),
637        )
638    }
639
640    pub(crate) fn resolve_method_call_as_callable(
641        &self,
642        db: &'db dyn HirDatabase,
643        call: &ast::MethodCallExpr,
644    ) -> Option<Callable<'db>> {
645        let expr_id = self.expr_id(call.clone().into())?.as_expr()?;
646        let (func, args) = self.infer()?.method_resolution(expr_id)?;
647        let interner = DbInterner::new_no_crate(db);
648        let ty = db.value_ty(func.into())?.instantiate(interner, args).skip_norm_wip();
649        let ty = self.ty(ty);
650        let mut res = ty.as_callable(db)?;
651        res.is_bound_method = true;
652        Some(res)
653    }
654
655    pub(crate) fn resolve_method_call(
656        &self,
657        db: &'db dyn HirDatabase,
658        call: &ast::MethodCallExpr,
659    ) -> Option<Function> {
660        let expr_id = self.expr_id(call.clone().into())?.as_expr()?;
661        let (f_in_trait, substs) = self.infer()?.method_resolution(expr_id)?;
662
663        Some(self.resolve_impl_method_or_trait_def(db, f_in_trait, substs))
664    }
665
666    pub(crate) fn resolve_method_call_fallback(
667        &self,
668        db: &'db dyn HirDatabase,
669        call: &ast::MethodCallExpr,
670    ) -> Option<(Either<Function, Field>, Option<GenericSubstitution<'db>>)> {
671        let expr_id = self.expr_id(call.clone().into())?.as_expr()?;
672        let inference_result = self.infer()?;
673        match inference_result.method_resolution(expr_id) {
674            Some((f_in_trait, substs)) => {
675                let (fn_, subst) =
676                    self.resolve_impl_method_or_trait_def_with_subst(db, f_in_trait, substs);
677                Some((
678                    Either::Left(fn_),
679                    GenericSubstitution::new_from_fn(fn_, subst, self.type_owner),
680                ))
681            }
682            None => {
683                inference_result.field_resolution(expr_id).and_then(Either::left).map(|field| {
684                    (Either::Right(field.into()), self.field_subst(expr_id, inference_result, db))
685                })
686            }
687        }
688    }
689
690    pub(crate) fn resolve_expr_as_callable(
691        &self,
692        db: &'db dyn HirDatabase,
693        call: &ast::Expr,
694    ) -> Option<Callable<'db>> {
695        let (orig, adjusted) = self.type_of_expr(db, &call.clone())?;
696        adjusted.unwrap_or(orig).as_callable(db)
697    }
698
699    pub(crate) fn resolve_field(
700        &self,
701        field: &ast::FieldExpr,
702    ) -> Option<Either<Field, TupleField<'db>>> {
703        let def = self.infer_body?;
704        let expr_id = self.expr_id(field.clone().into())?.as_expr()?;
705        self.infer()?.field_resolution(expr_id).map(|it| {
706            it.map_either(Into::into, |f| TupleField { owner: def, tuple: f.tuple, index: f.index })
707        })
708    }
709
710    fn field_subst(
711        &self,
712        field_expr: ExprId,
713        infer: &InferenceResult<'_>,
714        _db: &'db dyn HirDatabase,
715    ) -> Option<GenericSubstitution<'db>> {
716        let body = self.store()?;
717        if let Expr::Field { expr: object_expr, name: _ } = body[field_expr] {
718            let (adt, subst) = infer.type_of_expr_with_adjust(object_expr)?.as_adt()?;
719            return Some(GenericSubstitution::new(adt.into(), subst, self.type_owner));
720        }
721        None
722    }
723
724    pub(crate) fn resolve_field_fallback(
725        &self,
726        db: &'db dyn HirDatabase,
727        field: &ast::FieldExpr,
728    ) -> Option<(Either<Either<Field, TupleField<'db>>, Function>, Option<GenericSubstitution<'db>>)>
729    {
730        let def = self.infer_body?;
731        let expr_id = self.expr_id(field.clone().into())?.as_expr()?;
732        let inference_result = self.infer()?;
733        match inference_result.field_resolution(expr_id) {
734            Some(field) => match field {
735                Either::Left(field) => Some((
736                    Either::Left(Either::Left(field.into())),
737                    self.field_subst(expr_id, inference_result, db),
738                )),
739                Either::Right(field) => Some((
740                    Either::Left(Either::Right(TupleField {
741                        owner: def,
742                        tuple: field.tuple,
743                        index: field.index,
744                    })),
745                    None,
746                )),
747            },
748            None => inference_result.method_resolution(expr_id).map(|(f, substs)| {
749                let (f, subst) = self.resolve_impl_method_or_trait_def_with_subst(db, f, substs);
750                (Either::Right(f), GenericSubstitution::new_from_fn(f, subst, self.type_owner))
751            }),
752        }
753    }
754
755    pub(crate) fn resolve_range_pat(
756        &self,
757        db: &'db dyn HirDatabase,
758        range_pat: &ast::RangePat,
759    ) -> Option<StructId> {
760        self.resolve_range_struct(
761            db,
762            range_pat.op_kind()?,
763            range_pat.start().is_some(),
764            range_pat.end().is_some(),
765        )
766    }
767
768    pub(crate) fn resolve_range_expr(
769        &self,
770        db: &'db dyn HirDatabase,
771        range_expr: &ast::RangeExpr,
772    ) -> Option<StructId> {
773        self.resolve_range_struct(
774            db,
775            range_expr.op_kind()?,
776            range_expr.start().is_some(),
777            range_expr.end().is_some(),
778        )
779    }
780
781    fn resolve_range_struct(
782        &self,
783        db: &'db dyn HirDatabase,
784        op_kind: RangeOp,
785        has_start: bool,
786        has_end: bool,
787    ) -> Option<StructId> {
788        let has_new_range = self.resolver.top_level_def_map().features().new_range;
789        let lang_items = self.lang_items(db);
790        match (op_kind, has_start, has_end) {
791            (RangeOp::Exclusive, false, false) => lang_items.RangeFull,
792            (RangeOp::Exclusive, false, true) => lang_items.RangeTo,
793            (RangeOp::Exclusive, true, false) => {
794                if has_new_range {
795                    lang_items.RangeFromCopy
796                } else {
797                    lang_items.RangeFrom
798                }
799            }
800            (RangeOp::Exclusive, true, true) => {
801                if has_new_range {
802                    lang_items.RangeCopy
803                } else {
804                    lang_items.Range
805                }
806            }
807            (RangeOp::Inclusive, false, true) => {
808                if has_new_range {
809                    lang_items.RangeToInclusiveCopy
810                } else {
811                    lang_items.RangeToInclusive
812                }
813            }
814            (RangeOp::Inclusive, true, true) => {
815                if has_new_range {
816                    lang_items.RangeInclusiveCopy
817                } else {
818                    lang_items.RangeInclusiveStruct
819                }
820            }
821            // [E0586] inclusive ranges must be bounded at the end
822            (RangeOp::Inclusive, false, false) => None,
823            (RangeOp::Inclusive, true, false) => None,
824        }
825    }
826
827    pub(crate) fn resolve_await_to_poll(
828        &self,
829        db: &'db dyn HirDatabase,
830        await_expr: &ast::AwaitExpr,
831    ) -> Option<Function> {
832        let mut ty = self.ty_of_expr(await_expr.expr()?)?;
833
834        let into_future_trait = self
835            .resolver
836            .resolve_known_trait(db, &path![core::future::IntoFuture])
837            .map(Trait::from);
838
839        if let Some(into_future_trait) = into_future_trait {
840            let type_ = self.ty(ty);
841            if type_.impls_trait(db, into_future_trait, &[]) {
842                let items = into_future_trait.items(db);
843                let into_future_type = items.into_iter().find_map(|item| match item {
844                    AssocItem::TypeAlias(alias)
845                        if alias.name(db) == Name::new_symbol_root(sym::IntoFuture) =>
846                    {
847                        Some(alias)
848                    }
849                    _ => None,
850                })?;
851                let future_trait = type_.normalize_trait_assoc_type(db, &[], into_future_type)?;
852                ty = future_trait.ty.skip_binder();
853            }
854        }
855
856        let poll_fn = self.lang_items(db).FuturePoll?;
857        // HACK: subst for `poll()` coincides with that for `Future` because `poll()` itself
858        // doesn't have any generic parameters, so we skip building another subst for `poll()`.
859        let substs = GenericArgs::new_from_slice(&[ty.into()]);
860        Some(self.resolve_impl_method_or_trait_def(db, poll_fn, substs))
861    }
862
863    pub(crate) fn resolve_prefix_expr(
864        &self,
865        db: &'db dyn HirDatabase,
866        prefix_expr: &ast::PrefixExpr,
867    ) -> Option<Function> {
868        let lang_items = self.lang_items(db);
869        let (_op_trait, op_fn) = match prefix_expr.op_kind()? {
870            ast::UnaryOp::Deref => {
871                // This can be either `Deref::deref` or `DerefMut::deref_mut`.
872                // Since deref kind is inferenced and stored in `InferenceResult.method_resolution`,
873                // use that result to find out which one it is.
874                let (deref_trait, deref) = (lang_items.Deref?, lang_items.Deref_deref?);
875                self.infer()
876                    .and_then(|infer| {
877                        let expr = self.expr_id(prefix_expr.clone().into())?.as_expr()?;
878                        let (func, _) = infer.method_resolution(expr)?;
879                        let (deref_mut_trait, deref_mut) =
880                            (lang_items.DerefMut?, lang_items.DerefMut_deref_mut?);
881                        if func == deref_mut { Some((deref_mut_trait, deref_mut)) } else { None }
882                    })
883                    .unwrap_or((deref_trait, deref))
884            }
885            ast::UnaryOp::Not => (lang_items.Not?, lang_items.Not_not?),
886            ast::UnaryOp::Neg => (lang_items.Neg?, lang_items.Neg_neg?),
887        };
888
889        let ty = self.ty_of_expr(prefix_expr.expr()?)?;
890
891        // HACK: subst for all methods coincides with that for their trait because the methods
892        // don't have any generic parameters, so we skip building another subst for the methods.
893        let substs = GenericArgs::new_from_slice(&[ty.into()]);
894
895        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
896    }
897
898    pub(crate) fn resolve_index_expr(
899        &self,
900        db: &'db dyn HirDatabase,
901        index_expr: &ast::IndexExpr,
902    ) -> Option<Function> {
903        let base_ty = self.ty_of_expr(index_expr.base()?)?;
904        let index_ty = self.ty_of_expr(index_expr.index()?)?;
905        let lang_items = self.lang_items(db);
906
907        let (_index_trait, index_fn) = (lang_items.Index?, lang_items.Index_index?);
908        let op_fn = self
909            .infer()
910            .and_then(|infer| {
911                let expr = self.expr_id(index_expr.clone().into())?.as_expr()?;
912                let (func, _) = infer.method_resolution(expr)?;
913                let (_index_mut_trait, index_mut_fn) =
914                    (lang_items.IndexMut_index_mut?, lang_items.IndexMut_index_mut?);
915                if func == index_mut_fn { Some(index_mut_fn) } else { None }
916            })
917            .unwrap_or(index_fn);
918        // HACK: subst for all methods coincides with that for their trait because the methods
919        // don't have any generic parameters, so we skip building another subst for the methods.
920        let substs = GenericArgs::new_from_slice(&[base_ty.into(), index_ty.into()]);
921        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
922    }
923
924    pub(crate) fn resolve_bin_expr(
925        &self,
926        db: &'db dyn HirDatabase,
927        binop_expr: &ast::BinExpr,
928    ) -> Option<Function> {
929        let op = binop_expr.op_kind()?;
930        let lhs = self.ty_of_expr(binop_expr.lhs()?)?;
931        let rhs = self.ty_of_expr(binop_expr.rhs()?)?;
932
933        let (op_fn, _op_trait) = lang_items_for_bin_op(self.lang_items(db), op)
934            .and_then(|(method, trait_)| method.zip(trait_))?;
935        // HACK: subst for `index()` coincides with that for `Index` because `index()` itself
936        // doesn't have any generic parameters, so we skip building another subst for `index()`.
937        let substs = GenericArgs::new_from_slice(&[lhs.into(), rhs.into()]);
938
939        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
940    }
941
942    pub(crate) fn resolve_try_expr(
943        &self,
944        db: &'db dyn HirDatabase,
945        try_expr: &ast::TryExpr,
946    ) -> Option<Function> {
947        let ty = self.ty_of_expr(try_expr.expr()?)?;
948
949        let op_fn = self.lang_items(db).TryTraitBranch?;
950        // HACK: subst for `branch()` coincides with that for `Try` because `branch()` itself
951        // doesn't have any generic parameters, so we skip building another subst for `branch()`.
952        let substs = GenericArgs::new_from_slice(&[ty.into()]);
953
954        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))
955    }
956
957    pub(crate) fn resolve_record_field(
958        &self,
959        db: &'db dyn HirDatabase,
960        field: &ast::RecordExprField,
961    ) -> Option<(Field, Option<Local<'db>>, Type<'db>, GenericSubstitution<'db>)> {
962        let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
963        let expr = ast::Expr::from(record_expr);
964        let expr_id = self.store_sm()?.node_expr(InFile::new(self.file_id, &expr))?;
965        let interner = DbInterner::new_no_crate(db);
966
967        let ast_name = field.field_name()?;
968        let local_name = ast_name.as_name();
969        let local = if field.name_ref().is_some() {
970            None
971        } else {
972            // Shorthand syntax, resolve to the local
973            let path = Path::from_known_path_with_no_generic(ModPath::from_segments(
974                PathKind::Plain,
975                once(local_name.clone()),
976            ));
977            match self.resolver.resolve_path_in_value_ns_fully(
978                db,
979                &path,
980                name_hygiene(db, InFile::new(self.file_id, ast_name.syntax())),
981            ) {
982                Some(ValueNs::LocalBinding(binding_id)) => Some(Local {
983                    binding_id,
984                    parent: self.owner()?,
985                    parent_infer: self.infer_body?,
986                }),
987                _ => None,
988            }
989        };
990        let (adt, subst) = self.infer()?.type_of_expr_or_pat(expr_id)?.as_adt()?;
991        let variant = self.infer()?.variant_resolution_for_expr_or_pat(expr_id)?;
992        let variant_data = variant.fields(db);
993        let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };
994        let field_ty = (*db.field_types(variant).get(field.local_id)?)
995            .ty()
996            .instantiate(interner, subst)
997            .skip_norm_wip();
998        Some((
999            field.into(),
1000            local,
1001            self.ty(field_ty),
1002            GenericSubstitution::new(adt.into(), subst, self.type_owner),
1003        ))
1004    }
1005
1006    pub(crate) fn resolve_record_pat_field(
1007        &self,
1008        db: &'db dyn HirDatabase,
1009        field: &ast::RecordPatField,
1010    ) -> Option<(Field, Type<'db>, GenericSubstitution<'db>)> {
1011        let interner = DbInterner::new_no_crate(db);
1012        let field_name = field.field_name()?.as_name();
1013        let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;
1014        let pat_id = self.pat_id(&record_pat.into())?;
1015        let variant = self.infer()?.variant_resolution_for_pat(pat_id.as_pat()?)?;
1016        let variant_data = variant.fields(db);
1017        let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };
1018        let (adt, subst) = self.infer()?.pat_ty(pat_id.as_pat()?).as_adt()?;
1019        let field_ty = (*db.field_types(variant).get(field.local_id)?)
1020            .ty()
1021            .instantiate(interner, subst)
1022            .skip_norm_wip();
1023        Some((
1024            field.into(),
1025            self.ty(field_ty),
1026            GenericSubstitution::new(adt.into(), subst, self.type_owner),
1027        ))
1028    }
1029
1030    pub(crate) fn resolve_tuple_struct_pat_fields(
1031        &self,
1032        db: &'db dyn HirDatabase,
1033        tuple_struct_pat: &ast::TupleStructPat,
1034    ) -> Option<Vec<(Field, Type<'db>)>> {
1035        let interner = DbInterner::new_no_crate(db);
1036        let pat_id = self.pat_id(&tuple_struct_pat.clone().into())?;
1037        let variant_id = self.infer()?.variant_resolution_for_pat(pat_id.as_pat()?)?;
1038        let (_adt, substs) = self.infer()?.pat_ty(pat_id.as_pat()?).as_adt()?;
1039
1040        Some(
1041            db.field_types(variant_id)
1042                .iter()
1043                .map(|(local_id, field)| {
1044                    let def = Field { parent: variant_id.into(), id: local_id };
1045                    let ty = field.ty().instantiate(interner, substs).skip_norm_wip();
1046                    (def, self.ty(ty))
1047                })
1048                .collect(),
1049        )
1050    }
1051
1052    pub(crate) fn resolve_bind_pat_to_const(
1053        &self,
1054        db: &'db dyn HirDatabase,
1055        pat: &ast::IdentPat,
1056    ) -> Option<ModuleDef> {
1057        let expr_or_pat_id = self.pat_id(&pat.clone().into())?;
1058        let store = self.store()?;
1059
1060        let path = match expr_or_pat_id {
1061            ExprOrPatId::ExprId(idx) => match &store[idx] {
1062                Expr::Path(path) => path,
1063                _ => return None,
1064            },
1065            ExprOrPatId::PatId(idx) => match &store[idx] {
1066                Pat::Path(path) => path,
1067                _ => return None,
1068            },
1069        };
1070
1071        let store_owner = self.resolver.expression_store_owner();
1072        let (res, _) = resolve_hir_value_path(
1073            db,
1074            &self.resolver,
1075            store_owner,
1076            self.infer_body,
1077            path,
1078            HygieneId::ROOT,
1079        )?;
1080        match res {
1081            PathResolution::Def(def) => Some(def),
1082            _ => None,
1083        }
1084    }
1085
1086    pub(crate) fn resolve_use_type_arg(&self, name: &ast::NameRef) -> Option<crate::TypeParam> {
1087        let name = name.as_name();
1088        self.resolver
1089            .all_generic_params()
1090            .find_map(|(params, parent)| params.find_type_by_name(&name, parent))
1091            .map(crate::TypeParam::from)
1092    }
1093
1094    pub(crate) fn resolve_offset_of_field(
1095        &self,
1096        db: &'db dyn HirDatabase,
1097        name_ref: &ast::NameRef,
1098    ) -> Option<(Either<crate::EnumVariant, crate::Field>, GenericSubstitution<'db>)> {
1099        let offset_of_expr = ast::OffsetOfExpr::cast(name_ref.syntax().parent()?)?;
1100        let container = offset_of_expr.ty()?;
1101        let container = self.type_of_type(db, &container)?;
1102
1103        let env = self.trait_environment(db);
1104
1105        let interner = DbInterner::new_with(db, env.krate);
1106        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
1107
1108        let mut container = Either::Right(container.ty.skip_binder());
1109        for field_name in offset_of_expr.fields() {
1110            if let Either::Right(container) = &mut container {
1111                *container = structurally_normalize_ty(&infcx, *container, env.param_env);
1112            }
1113            let handle_variants =
1114                |variant: VariantId, subst: GenericArgs<'db>, container: &mut _| {
1115                    let fields = variant.fields(db);
1116                    let field = fields.field(&field_name.as_name())?;
1117                    let field_types = db.field_types(variant);
1118                    *container = Either::Right(
1119                        field_types[field].ty().instantiate(interner, subst).skip_norm_wip(),
1120                    );
1121                    let generic_def = match variant {
1122                        VariantId::EnumVariantId(it) => it.loc(db).parent.into(),
1123                        VariantId::StructId(it) => it.into(),
1124                        VariantId::UnionId(it) => it.into(),
1125                    };
1126                    Some((
1127                        Either::Right(Field { parent: variant.into(), id: field }),
1128                        generic_def,
1129                        subst,
1130                    ))
1131                };
1132            let temp_ty = Ty::new_error(interner, ErrorGuaranteed);
1133            let (field_def, generic_def, subst) =
1134                match std::mem::replace(&mut container, Either::Right(temp_ty)) {
1135                    Either::Left((variant_id, subst)) => {
1136                        handle_variants(VariantId::from(variant_id), subst, &mut container)?
1137                    }
1138                    Either::Right(container_ty) => match container_ty.kind() {
1139                        TyKind::Adt(adt_def, subst) => match adt_def.def_id() {
1140                            AdtId::StructId(id) => {
1141                                handle_variants(id.into(), subst, &mut container)?
1142                            }
1143                            AdtId::UnionId(id) => {
1144                                handle_variants(id.into(), subst, &mut container)?
1145                            }
1146                            AdtId::EnumId(id) => {
1147                                let variants = id.enum_variants(db);
1148                                let variant = variants.variant(&field_name.as_name())?;
1149                                container = Either::Left((variant, subst));
1150                                (Either::Left(EnumVariant { id: variant }), id.into(), subst)
1151                            }
1152                        },
1153                        _ => return None,
1154                    },
1155                };
1156
1157            if field_name.syntax().text_range() == name_ref.syntax().text_range() {
1158                return Some((
1159                    field_def,
1160                    GenericSubstitution::new(generic_def, subst, self.type_owner),
1161                ));
1162            }
1163        }
1164        never!("the `NameRef` is a child of the `OffsetOfExpr`, we should've visited it");
1165        None
1166    }
1167
1168    pub(crate) fn resolve_path(
1169        &self,
1170        db: &'db dyn HirDatabase,
1171        path: &ast::Path,
1172    ) -> Option<(PathResolution<'db>, Option<GenericSubstitution<'db>>)> {
1173        let parent = path.syntax().parent();
1174        let parent = || parent.clone();
1175
1176        let mut prefer_value_ns = parent().and_then(ast::PathExpr::cast).is_some();
1177        let resolved = (|| {
1178            let infer = self.infer()?;
1179            if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {
1180                let expr_id = self.expr_id(path_expr.into())?;
1181                if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr_or_pat(expr_id) {
1182                    let (assoc, subst) = match assoc {
1183                        CandidateId::FunctionId(f_in_trait) => {
1184                            match infer.type_of_expr_or_pat(expr_id) {
1185                                None => {
1186                                    let subst = GenericSubstitution::new(
1187                                        f_in_trait.into(),
1188                                        subs,
1189                                        self.type_owner,
1190                                    );
1191                                    (AssocItem::Function(f_in_trait.into()), Some(subst))
1192                                }
1193                                Some(func_ty) => {
1194                                    if let TyKind::FnDef(_fn_def, subs) = func_ty.kind() {
1195                                        let (fn_, subst) = self
1196                                            .resolve_impl_method_or_trait_def_with_subst(
1197                                                db, f_in_trait, subs,
1198                                            );
1199                                        let subst = GenericSubstitution::new_from_fn(
1200                                            fn_,
1201                                            subst,
1202                                            self.type_owner,
1203                                        );
1204                                        (AssocItem::Function(fn_), subst)
1205                                    } else {
1206                                        let subst = GenericSubstitution::new(
1207                                            f_in_trait.into(),
1208                                            subs,
1209                                            self.type_owner,
1210                                        );
1211                                        (AssocItem::Function(f_in_trait.into()), Some(subst))
1212                                    }
1213                                }
1214                            }
1215                        }
1216                        CandidateId::ConstId(const_id) => {
1217                            let (konst, subst) =
1218                                self.resolve_impl_const_or_trait_def_with_subst(db, const_id, subs);
1219                            let subst =
1220                                GenericSubstitution::new(konst.into(), subst, self.type_owner);
1221                            (AssocItem::Const(konst.into()), Some(subst))
1222                        }
1223                    };
1224
1225                    return Some((PathResolution::Def(assoc.into()), subst));
1226                }
1227                if let Some(VariantId::EnumVariantId(variant)) =
1228                    infer.variant_resolution_for_expr_or_pat(expr_id)
1229                {
1230                    return Some((
1231                        PathResolution::Def(ModuleDef::EnumVariant(variant.into())),
1232                        None,
1233                    ));
1234                }
1235                prefer_value_ns = true;
1236            } else if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {
1237                let expr_or_pat_id = self.pat_id(&path_pat.into())?;
1238                if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr_or_pat(expr_or_pat_id)
1239                {
1240                    let (assoc, subst) = match assoc {
1241                        CandidateId::ConstId(const_id) => {
1242                            let (konst, subst) =
1243                                self.resolve_impl_const_or_trait_def_with_subst(db, const_id, subs);
1244                            let subst =
1245                                GenericSubstitution::new(konst.into(), subst, self.type_owner);
1246                            (AssocItemId::from(konst), subst)
1247                        }
1248                        CandidateId::FunctionId(function_id) => (
1249                            function_id.into(),
1250                            GenericSubstitution::new(function_id.into(), subs, self.type_owner),
1251                        ),
1252                    };
1253                    return Some((PathResolution::Def(AssocItem::from(assoc).into()), Some(subst)));
1254                }
1255                if let Some(VariantId::EnumVariantId(variant)) =
1256                    infer.variant_resolution_for_expr_or_pat(expr_or_pat_id)
1257                {
1258                    return Some((
1259                        PathResolution::Def(ModuleDef::EnumVariant(variant.into())),
1260                        None,
1261                    ));
1262                }
1263            } else if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {
1264                let expr_id = self.expr_id(rec_lit.into())?;
1265                if let Some(VariantId::EnumVariantId(variant)) =
1266                    infer.variant_resolution_for_expr_or_pat(expr_id)
1267                {
1268                    return Some((
1269                        PathResolution::Def(ModuleDef::EnumVariant(variant.into())),
1270                        None,
1271                    ));
1272                }
1273            } else {
1274                let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);
1275                let tuple_struct_pat =
1276                    || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);
1277                if let Some(pat) = record_pat.or_else(tuple_struct_pat) {
1278                    let pat_id = self.pat_id(&pat)?;
1279                    let variant_res_for_pat = infer.variant_resolution_for_pat(pat_id.as_pat()?);
1280                    if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {
1281                        return Some((
1282                            PathResolution::Def(ModuleDef::EnumVariant(variant.into())),
1283                            None,
1284                        ));
1285                    }
1286                }
1287            }
1288            None
1289        })();
1290        if resolved.is_some() {
1291            return resolved;
1292        }
1293
1294        // FIXME: collectiong here shouldnt be necessary?
1295        let mut collector =
1296            ExprCollector::new(db, self.resolver.module(), self.file_id, LoweringMode::Ide);
1297        let hir_path =
1298            collector.lower_path(path.clone(), &mut ExprCollector::impl_trait_error_allocator)?;
1299        let parent_hir_path = path
1300            .parent_path()
1301            .and_then(|p| collector.lower_path(p, &mut ExprCollector::impl_trait_error_allocator));
1302        let (store, _) = collector.store.finish();
1303
1304        // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are
1305        // trying to resolve foo::bar.
1306        if let Some(use_tree) = parent().and_then(ast::UseTree::cast)
1307            && use_tree.coloncolon_token().is_some()
1308        {
1309            return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store)
1310                .map(|it| (it, None));
1311        }
1312
1313        let meta_path = path
1314            .syntax()
1315            .ancestors()
1316            .take_while(|it| {
1317                let kind = it.kind();
1318                ast::Path::can_cast(kind) || ast::Meta::can_cast(kind)
1319            })
1320            .last()
1321            .and_then(ast::Meta::cast);
1322
1323        // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are
1324        // trying to resolve foo::bar.
1325        if let Some(parent_hir_path) = parent_hir_path {
1326            return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store) {
1327                None if meta_path.is_some() => path
1328                    .first_segment()
1329                    .and_then(|it| it.name_ref())
1330                    .and_then(|name_ref| {
1331                        ToolModule::by_name(db, self.resolver.krate().into(), name_ref.text())
1332                            .map(PathResolution::ToolModule)
1333                    })
1334                    .map(|it| (it, None)),
1335                // Case the type name conflict with use module,
1336                // e.g.
1337                // ```
1338                // use std::str;
1339                // fn main() {
1340                //     str::from_utf8();  // as module std::str
1341                //     str::len();        // as primitive type str
1342                //     str::no_exist_item(); // as primitive type str
1343                // }
1344                // ```
1345                Some(it) if matches!(it, PathResolution::Def(ModuleDef::BuiltinType(_))) => {
1346                    if let Some(mod_path) = hir_path.mod_path()
1347                        && let Some(ModuleDefId::ModuleId(id)) =
1348                            self.resolver.resolve_module_path_in_items(db, mod_path).take_types()
1349                    {
1350                        let parent_hir_name = parent_hir_path.segments().get(1).map(|it| it.name);
1351                        let module = crate::Module { id };
1352                        if module
1353                            .scope(db, None)
1354                            .into_iter()
1355                            .any(|(name, _)| Some(&name) == parent_hir_name)
1356                        {
1357                            return Some((PathResolution::Def(ModuleDef::Module(module)), None));
1358                        };
1359                    }
1360                    Some((it, None))
1361                }
1362                // FIXME: We do not show substitutions for parts of path, because this is really complex
1363                // due to the interactions with associated items of `impl`s and associated items of associated
1364                // types.
1365                res => res.map(|it| (it, None)),
1366            };
1367        } else if let Some(meta_path) = meta_path {
1368            // Case where we are resolving the final path segment of a path in an attribute
1369            // in this case we have to check for inert/builtin attributes and tools and prioritize
1370            // resolution of attributes over other namespaces
1371            if let Some(name_ref) = path.as_single_name_ref() {
1372                let builtin = BuiltinAttr::builtin(name_ref.text());
1373                if builtin.is_some() {
1374                    return builtin.map(|it| (PathResolution::BuiltinAttr(it), None));
1375                }
1376
1377                if let Some(attr) = meta_path.parent_attr() {
1378                    let adt =
1379                        attr.syntax().ancestors().find_map(ast::Item::cast).and_then(
1380                            |it| match it {
1381                                ast::Item::Struct(it) => Some(ast::Adt::Struct(it)),
1382                                ast::Item::Enum(it) => Some(ast::Adt::Enum(it)),
1383                                ast::Item::Union(it) => Some(ast::Adt::Union(it)),
1384                                _ => None,
1385                            },
1386                        );
1387                    if let Some(adt) = adt {
1388                        let ast_id = self.file_id.ast_id_map(db).ast_id(&adt);
1389                        if let Some(helpers) = self
1390                            .resolver
1391                            .def_map()
1392                            .derive_helpers_in_scope(InFile::new(self.file_id, ast_id))
1393                        {
1394                            // FIXME: Multiple derives can have the same helper
1395                            let name_ref = name_ref.as_name();
1396                            for (macro_id, mut helpers) in
1397                                helpers.iter().chunk_by(|(_, macro_id, ..)| macro_id).into_iter()
1398                            {
1399                                if let Some(idx) = helpers.position(|(name, ..)| *name == name_ref)
1400                                {
1401                                    return Some((
1402                                        PathResolution::DeriveHelper(DeriveHelper {
1403                                            derive: *macro_id,
1404                                            idx: idx as u32,
1405                                        }),
1406                                        None,
1407                                    ));
1408                                }
1409                            }
1410                        }
1411                    }
1412                }
1413            }
1414            return match resolve_hir_path_as_attr_macro(db, &self.resolver, &hir_path) {
1415                Some(m) => Some((PathResolution::Def(ModuleDef::Macro(m)), None)),
1416                // this labels any path that starts with a tool module as the tool itself, this is technically wrong
1417                // but there is no benefit in differentiating these two cases for the time being
1418                None => path
1419                    .first_segment()
1420                    .and_then(|it| it.name_ref())
1421                    .and_then(|name_ref| {
1422                        ToolModule::by_name(db, self.resolver.krate().into(), name_ref.text())
1423                            .map(PathResolution::ToolModule)
1424                    })
1425                    .map(|it| (it, None)),
1426            };
1427        }
1428        if parent().is_some_and(|it| ast::Visibility::can_cast(it.kind())) {
1429            // No substitution because only modules can be inside visibilities, and those have no generics.
1430            resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store).map(|it| (it, None))
1431        } else {
1432            // Probably a type, no need to show substitutions for those.
1433            let res = resolve_hir_path_(
1434                db,
1435                &self.resolver,
1436                self.infer_body,
1437                &hir_path,
1438                prefer_value_ns,
1439                name_hygiene(db, InFile::new(self.file_id, path.syntax())),
1440                Some(&store),
1441                false,
1442            )
1443            .any()?;
1444            let subst = (|| {
1445                let parent = parent()?;
1446                let ty = if let Some(expr) = ast::Expr::cast(parent.clone()) {
1447                    let expr_id = self.expr_id(expr)?;
1448                    self.infer()?.type_of_expr_or_pat(expr_id)?
1449                } else {
1450                    let pat = ast::Pat::cast(parent)?;
1451                    let pat_id = self.pat_id(&pat)?;
1452                    self.infer()?.expr_or_pat_ty(pat_id)
1453                };
1454                let (subst, expected_resolution) = match ty.kind() {
1455                    TyKind::Adt(adt_def, subst) => {
1456                        let adt_id = adt_def.def_id();
1457                        (
1458                            GenericSubstitution::new(adt_id.into(), subst, self.type_owner),
1459                            PathResolution::Def(ModuleDef::Adt(adt_id.into())),
1460                        )
1461                    }
1462                    TyKind::Alias(AliasTy {
1463                        kind: AliasTyKind::Projection { def_id },
1464                        args,
1465                        ..
1466                    }) => {
1467                        let assoc_id = def_id.0;
1468                        (
1469                            GenericSubstitution::new(assoc_id.into(), args, self.type_owner),
1470                            PathResolution::Def(ModuleDef::TypeAlias(assoc_id.into())),
1471                        )
1472                    }
1473                    TyKind::FnDef(fn_id, subst) => {
1474                        let generic_def_id = match fn_id.0 {
1475                            CallableDefId::StructId(id) => id.into(),
1476                            CallableDefId::FunctionId(id) => id.into(),
1477                            CallableDefId::EnumVariantId(_) => return None,
1478                        };
1479                        (
1480                            GenericSubstitution::new(generic_def_id, subst, self.type_owner),
1481                            PathResolution::Def(ModuleDefId::from(fn_id.0).into()),
1482                        )
1483                    }
1484                    _ => return None,
1485                };
1486                if res != expected_resolution {
1487                    // The user will not understand where we're coming from. This can happen (I think) with type aliases.
1488                    return None;
1489                }
1490                Some(subst)
1491            })();
1492            Some((res, subst))
1493        }
1494    }
1495
1496    pub(crate) fn resolve_hir_path_per_ns(
1497        &self,
1498        db: &'db dyn HirDatabase,
1499        path: &ast::Path,
1500    ) -> Option<PathResolutionPerNs<'db>> {
1501        let mut collector =
1502            ExprCollector::new(db, self.resolver.module(), self.file_id, LoweringMode::Ide);
1503        let hir_path =
1504            collector.lower_path(path.clone(), &mut ExprCollector::impl_trait_error_allocator)?;
1505        let (store, _) = collector.store.finish();
1506        Some(resolve_hir_path_(
1507            db,
1508            &self.resolver,
1509            self.infer_body,
1510            &hir_path,
1511            false,
1512            name_hygiene(db, InFile::new(self.file_id, path.syntax())),
1513            Some(&store),
1514            true,
1515        ))
1516    }
1517
1518    pub(crate) fn record_literal_missing_fields(
1519        &self,
1520        db: &'db dyn HirDatabase,
1521        literal: &ast::RecordExpr,
1522    ) -> Option<Vec<(Field, Type<'db>)>> {
1523        let body = self.store()?;
1524        let infer = self.infer()?;
1525
1526        let expr_id = self.expr_id(literal.clone().into())?.as_expr()?;
1527        let substs = infer.expr_ty(expr_id).as_adt()?.1;
1528        let (variant, missing_fields) =
1529            record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
1530        let res = self.missing_fields(db, substs, variant, missing_fields);
1531        Some(res)
1532    }
1533
1534    pub(crate) fn record_literal_matched_fields(
1535        &self,
1536        db: &'db dyn HirDatabase,
1537        literal: &ast::RecordExpr,
1538    ) -> Option<Vec<(Field, Type<'db>)>> {
1539        let body = self.store()?;
1540        let infer = self.infer()?;
1541
1542        let expr_id = self.expr_id(literal.clone().into())?.as_expr()?;
1543        let substs = infer.expr_ty(expr_id).as_adt()?.1;
1544        let (variant, matched_fields) =
1545            record_literal_matched_fields(db, infer, expr_id, &body[expr_id])?;
1546
1547        let res = self.missing_fields(db, substs, variant, matched_fields);
1548        Some(res)
1549    }
1550
1551    pub(crate) fn record_pattern_missing_fields(
1552        &self,
1553        db: &'db dyn HirDatabase,
1554        pattern: &ast::RecordPat,
1555    ) -> Option<Vec<(Field, Type<'db>)>> {
1556        let body = self.store()?;
1557        let infer = self.infer()?;
1558
1559        let pat_id = self.pat_id(&pattern.clone().into())?.as_pat()?;
1560        let substs = infer.pat_ty(pat_id).as_adt()?.1;
1561
1562        let (variant, missing_fields) =
1563            record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
1564        let res = self.missing_fields(db, substs, variant, missing_fields);
1565        Some(res)
1566    }
1567
1568    pub(crate) fn record_pattern_matched_fields(
1569        &self,
1570        db: &'db dyn HirDatabase,
1571        pattern: &ast::RecordPat,
1572    ) -> Option<Vec<(Field, Type<'db>)>> {
1573        let body = self.store()?;
1574        let infer = self.infer()?;
1575
1576        let pat_id = self.pat_id(&pattern.clone().into())?.as_pat()?;
1577        let substs = infer.pat_ty(pat_id).as_adt()?.1;
1578
1579        let (variant, matched_fields) =
1580            record_pattern_matched_fields(db, infer, pat_id, &body[pat_id])?;
1581        let res = self.missing_fields(db, substs, variant, matched_fields);
1582        Some(res)
1583    }
1584
1585    fn missing_fields(
1586        &self,
1587        db: &'db dyn HirDatabase,
1588        substs: GenericArgs<'db>,
1589        variant: VariantId,
1590        missing_fields: Vec<LocalFieldId>,
1591    ) -> Vec<(Field, Type<'db>)> {
1592        let interner = DbInterner::new_no_crate(db);
1593        let field_types = db.field_types(variant);
1594
1595        missing_fields
1596            .into_iter()
1597            .map(|local_id| {
1598                let field = FieldId { parent: variant, local_id };
1599                let ty = field_types[local_id].ty().instantiate(interner, substs).skip_norm_wip();
1600                (field.into(), self.ty(ty))
1601            })
1602            .collect()
1603    }
1604
1605    pub(crate) fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {
1606        let infer = self.infer()?;
1607        let expr_id = self.expr_id(record_lit.into())?;
1608        infer.variant_resolution_for_expr_or_pat(expr_id)
1609    }
1610
1611    pub(crate) fn is_unsafe_macro_call_expr(
1612        &self,
1613        db: &'db dyn HirDatabase,
1614        macro_expr: InFile<&ast::MacroExpr>,
1615    ) -> bool {
1616        if let Some((def, body, sm, Some(infer))) = self.def()
1617            && let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr)
1618        {
1619            let mut is_unsafe = false;
1620            let mut walk_expr = |expr_id| {
1621                unsafe_operations(db, infer, def, body, expr_id, &mut |_, inside_unsafe_block| {
1622                    is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No
1623                })
1624            };
1625            match expanded_expr {
1626                ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr),
1627                ExprOrPatId::PatId(expanded_pat) => body.walk_exprs_in_pat(expanded_pat, walk_expr),
1628            }
1629            return is_unsafe;
1630        }
1631        false
1632    }
1633
1634    /// Returns the range of the implicit template argument and its resolution at the given `offset`
1635    pub(crate) fn resolve_offset_in_format_args(
1636        &self,
1637        db: &'db dyn HirDatabase,
1638        format_args: InFile<&ast::FormatArgsExpr>,
1639        offset: TextSize,
1640    ) -> Option<(TextRange, Option<PathResolution<'db>>)> {
1641        let (hygiene, implicits) = self.store_sm()?.implicit_format_args(format_args)?;
1642        implicits.iter().find(|(range, _)| range.contains_inclusive(offset)).map(|(range, name)| {
1643            (
1644                *range,
1645                resolve_hir_value_path(
1646                    db,
1647                    &self.resolver,
1648                    self.resolver.expression_store_owner(),
1649                    self.infer_body,
1650                    &Path::from_known_path_with_no_generic(ModPath::from_segments(
1651                        PathKind::Plain,
1652                        Some(name.clone()),
1653                    )),
1654                    hygiene,
1655                )
1656                .map(|(it, _)| it),
1657            )
1658        })
1659    }
1660
1661    pub(crate) fn resolve_offset_in_asm_template(
1662        &self,
1663        asm: InFile<&ast::AsmExpr>,
1664        line: usize,
1665        offset: TextSize,
1666    ) -> Option<(ExpressionStoreOwnerId, (ExprId, TextRange, usize))> {
1667        let (def, _, sm, _) = self.def()?;
1668        let (expr, args) = sm.asm_template_args(asm)?;
1669        Some(def).zip(
1670            args.get(line)?
1671                .iter()
1672                .find(|(range, _)| range.contains_inclusive(offset))
1673                .map(|(range, idx)| (expr, *range, *idx)),
1674        )
1675    }
1676
1677    pub(crate) fn as_format_args_parts<'a>(
1678        &'a self,
1679        db: &'db dyn HirDatabase,
1680        format_args: InFile<&ast::FormatArgsExpr>,
1681    ) -> Option<impl Iterator<Item = (TextRange, Option<PathResolution<'db>>)> + 'a> {
1682        let (hygiene, names) = self.store_sm()?.implicit_format_args(format_args)?;
1683        Some(names.iter().map(move |(range, name)| {
1684            (
1685                *range,
1686                resolve_hir_value_path(
1687                    db,
1688                    &self.resolver,
1689                    self.resolver.expression_store_owner(),
1690                    self.infer_body,
1691                    &Path::from_known_path_with_no_generic(ModPath::from_segments(
1692                        PathKind::Plain,
1693                        Some(name.clone()),
1694                    )),
1695                    hygiene,
1696                )
1697                .map(|(it, _)| it),
1698            )
1699        }))
1700    }
1701
1702    pub(crate) fn as_asm_parts(
1703        &self,
1704        asm: InFile<&ast::AsmExpr>,
1705    ) -> Option<(ExpressionStoreOwnerId, (ExprId, &[Vec<(TextRange, usize)>]))> {
1706        let (def, _, sm, _) = self.def()?;
1707        Some(def).zip(sm.asm_template_args(asm))
1708    }
1709
1710    fn resolve_impl_method_or_trait_def(
1711        &self,
1712        db: &'db dyn HirDatabase,
1713        func: FunctionId,
1714        substs: GenericArgs<'db>,
1715    ) -> Function {
1716        self.resolve_impl_method_or_trait_def_with_subst(db, func, substs).0
1717    }
1718
1719    fn resolve_impl_method_or_trait_def_with_subst(
1720        &self,
1721        db: &'db dyn HirDatabase,
1722        func: FunctionId,
1723        substs: GenericArgs<'db>,
1724    ) -> (Function, GenericArgs<'db>) {
1725        let owner = match self.resolver.generic_def() {
1726            Some(it) => it,
1727            None => return (func.into(), substs),
1728        };
1729        let env = self.param_and(db.trait_environment(owner));
1730        let (func, args) = db.lookup_impl_method(env, func, substs);
1731        match func {
1732            Either::Left(func) => (func.into(), args),
1733            Either::Right((impl_, method)) => {
1734                (Function { id: AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } }, args)
1735            }
1736        }
1737    }
1738
1739    fn resolve_impl_const_or_trait_def_with_subst(
1740        &self,
1741        db: &'db dyn HirDatabase,
1742        const_id: ConstId,
1743        subs: GenericArgs<'db>,
1744    ) -> (ConstId, GenericArgs<'db>) {
1745        let owner = match self.resolver.generic_def() {
1746            Some(it) => it,
1747            None => return (const_id, subs),
1748        };
1749        let env = self.param_and(db.trait_environment(owner));
1750        let interner = DbInterner::new_with(db, env.krate);
1751        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);
1752        method_resolution::lookup_impl_const(&infcx, env.param_env, const_id, subs)
1753    }
1754
1755    fn lang_items<'a>(&self, db: &'a dyn HirDatabase) -> &'a LangItems {
1756        hir_def::lang_item::lang_items(db, self.resolver.krate())
1757    }
1758
1759    fn ty_of_expr(&self, expr: ast::Expr) -> Option<Ty<'db>> {
1760        self.infer()?.type_of_expr_or_pat(self.expr_id(expr)?)
1761    }
1762}
1763
1764// Note: the `ExprId` here does not need to be accurate, what's important is that it points at the same
1765// inference root.
1766fn scope_for(
1767    db: &dyn HirDatabase,
1768    scopes: &ExprScopes,
1769    source_map: &ExpressionStoreSourceMap,
1770    node: InFile<&SyntaxNode>,
1771) -> Option<(ScopeId, ExprId)> {
1772    node.ancestors_with_macros(db)
1773        .take_while(|it| {
1774            let kind = it.kind();
1775            !ast::Item::can_cast(kind)
1776                || ast::MacroCall::can_cast(kind)
1777                || ast::Use::can_cast(kind)
1778                || ast::AsmExpr::can_cast(kind)
1779        })
1780        .filter_map(|it| it.map(ast::Expr::cast).transpose())
1781        .filter_map(|it| source_map.node_expr(it.as_ref())?.as_expr())
1782        .find_map(|expr| scopes.scope_for(expr).map(|scope| (scope, expr)))
1783}
1784
1785fn scope_for_offset(
1786    db: &dyn HirDatabase,
1787    scopes: &ExprScopes,
1788    source_map: &ExpressionStoreSourceMap,
1789    from_file: HirFileId,
1790    offset: TextSize,
1791) -> Option<(ScopeId, ExprId)> {
1792    scopes
1793        .scope_by_expr()
1794        .iter()
1795        .filter_map(|(id, scope)| {
1796            let InFile { file_id, value } = source_map.expr_syntax(id).ok()?;
1797            if from_file == file_id {
1798                return Some((value.text_range(), scope, id));
1799            }
1800
1801            // FIXME handle attribute expansion
1802            let source = iter::successors(file_id.macro_file().map(|it| it.call_node(db)), |it| {
1803                Some(it.file_id.macro_file()?.call_node(db))
1804            })
1805            .find(|it| it.file_id == from_file)
1806            .filter(|it| it.kind() == SyntaxKind::MACRO_CALL)?;
1807            Some((source.text_range(), scope, id))
1808        })
1809        .filter(|(expr_range, _scope, _expr)| {
1810            expr_range.start() <= offset && offset <= expr_range.end()
1811        })
1812        // find containing scope
1813        .min_by_key(|(expr_range, _scope, _expr)| expr_range.len())
1814        .map(|(expr_range, scope, expr)| {
1815            adjust(db, scopes, source_map, expr_range, from_file, offset).unwrap_or((*scope, expr))
1816        })
1817}
1818
1819// XXX: during completion, cursor might be outside of any particular
1820// expression. Try to figure out the correct scope...
1821fn adjust(
1822    db: &dyn HirDatabase,
1823    scopes: &ExprScopes,
1824    source_map: &ExpressionStoreSourceMap,
1825    expr_range: TextRange,
1826    from_file: HirFileId,
1827    offset: TextSize,
1828) -> Option<(ScopeId, ExprId)> {
1829    let child_scopes = scopes
1830        .scope_by_expr()
1831        .iter()
1832        .filter_map(|(id, scope)| {
1833            let source = source_map.expr_syntax(id).ok()?;
1834            // FIXME: correctly handle macro expansion
1835            if source.file_id != from_file {
1836                return None;
1837            }
1838            let root = source.file_syntax(db);
1839            let node = source.value.to_node(&root);
1840            Some((node.syntax().text_range(), scope, id))
1841        })
1842        .filter(|&(range, _, _)| {
1843            range.start() <= offset && expr_range.contains_range(range) && range != expr_range
1844        });
1845
1846    child_scopes
1847        .max_by(|&(r1, _, _), &(r2, _, _)| {
1848            if r1.contains_range(r2) {
1849                std::cmp::Ordering::Greater
1850            } else if r2.contains_range(r1) {
1851                std::cmp::Ordering::Less
1852            } else {
1853                r1.start().cmp(&r2.start())
1854            }
1855        })
1856        .map(|(_ptr, scope, expr)| (*scope, expr))
1857}
1858
1859#[inline]
1860pub(crate) fn resolve_hir_path<'db>(
1861    db: &'db dyn HirDatabase,
1862    resolver: &Resolver<'db>,
1863    infer_body: Option<InferBodyId<'db>>,
1864    path: &Path,
1865    hygiene: HygieneId,
1866    store: Option<&ExpressionStore>,
1867) -> Option<PathResolution<'db>> {
1868    resolve_hir_path_(db, resolver, infer_body, path, false, hygiene, store, false).any()
1869}
1870
1871#[inline]
1872pub(crate) fn resolve_hir_path_as_attr_macro(
1873    db: &dyn HirDatabase,
1874    resolver: &Resolver<'_>,
1875    path: &Path,
1876) -> Option<Macro> {
1877    resolver
1878        .resolve_path_as_macro(db, path.mod_path()?, Some(MacroSubNs::Attr))
1879        .map(|it| it.def)
1880        .map(Into::into)
1881}
1882
1883fn resolve_hir_path_<'db>(
1884    db: &'db dyn HirDatabase,
1885    resolver: &Resolver<'db>,
1886    infer_body: Option<InferBodyId<'db>>,
1887    path: &Path,
1888    prefer_value_ns: bool,
1889    hygiene: HygieneId,
1890    store: Option<&ExpressionStore>,
1891    resolve_per_ns: bool,
1892) -> PathResolutionPerNs<'db> {
1893    let types = || {
1894        let (ty, unresolved, ty_is_visible) = match path.type_anchor() {
1895            Some(type_ref) => resolver.generic_def().and_then(|def| {
1896                let generics = OnceCell::new();
1897                let (_, res) = TyLoweringContext::new(
1898                    db,
1899                    resolver,
1900                    store?,
1901                    resolver.expression_store_owner().unwrap_or_else(|| def.into()),
1902                    def,
1903                    &generics,
1904                    LifetimeElisionKind::Infer,
1905                    LifetimeLoweringMode::LateParam,
1906                )
1907                .with_interning_mode(LoweringMode::Ide)
1908                .lower_ty_ext(type_ref);
1909                res.map(|ty_ns| (ty_ns, path.segments().first(), Visibility::Public))
1910            }),
1911            None => {
1912                let (ty, remaining_idx, _, _, vis) =
1913                    resolver.resolve_path_in_type_ns_with_prefix_info(db, path)?;
1914                match remaining_idx {
1915                    Some(remaining_idx) => {
1916                        if remaining_idx + 1 == path.segments().len() {
1917                            Some((ty, path.segments().last(), vis))
1918                        } else {
1919                            None
1920                        }
1921                    }
1922                    None => Some((ty, None, vis)),
1923                }
1924            }
1925        }?;
1926
1927        // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
1928        // within the trait's associated types.
1929        if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty)
1930            && let Some(type_alias_id) =
1931                trait_id.trait_items(db).associated_type_by_name(unresolved.name)
1932        {
1933            return Some((
1934                PathResolution::Def(ModuleDefId::from(type_alias_id).into()),
1935                ty_is_visible,
1936            ));
1937        }
1938
1939        let res = match ty {
1940            TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
1941            TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()),
1942            TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
1943                PathResolution::Def(Adt::from(it).into())
1944            }
1945            TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
1946            TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
1947            TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
1948            TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
1949            TypeNs::ModuleId(it) => PathResolution::Def(ModuleDef::Module(it.into())),
1950        };
1951        match unresolved {
1952            Some(unresolved) => resolver
1953                .generic_def()
1954                .and_then(|def| {
1955                    hir_ide::associated_type_shorthand_candidates(
1956                        db,
1957                        def,
1958                        res.in_type_ns()?,
1959                        |name, _| name == unresolved.name,
1960                    )
1961                })
1962                .map(TypeAlias::from)
1963                .map(Into::into)
1964                .map(|def| (PathResolution::Def(def), ty_is_visible)),
1965            None => Some((res, ty_is_visible)),
1966        }
1967    };
1968
1969    let body_owner = resolver.expression_store_owner();
1970    let values = || resolve_hir_value_path(db, resolver, body_owner, infer_body, path, hygiene);
1971
1972    let items = || {
1973        resolver
1974            .resolve_module_path_in_items(db, path.mod_path()?)
1975            .take_types_full()
1976            .map(|it| (PathResolution::Def(it.def.into()), it.vis))
1977    };
1978
1979    let macros = || {
1980        resolver
1981            .resolve_path_as_macro(db, path.mod_path()?, None)
1982            .map(|res| (PathResolution::Def(ModuleDef::Macro(res.def.into())), res.vis))
1983    };
1984
1985    let mut types_ns: Option<Option<_>> = None;
1986    let mut values_ns: Option<Option<_>> = None;
1987
1988    let mut types_is_visible: Option<bool> = None;
1989    let mut values_is_visible: Option<bool> = None;
1990
1991    if !resolve_per_ns {
1992        if prefer_value_ns {
1993            values_ns = Some(values().inspect(|(_, vis)| {
1994                values_is_visible = Some(resolver.is_visible(db, *vis));
1995            }));
1996
1997            if let Some(Some((res, _))) = values_ns
1998                && values_is_visible.unwrap_or_default()
1999            {
2000                return PathResolutionPerNs::new(None, Some(res), None);
2001            }
2002        } else {
2003            types_ns = Some(types().or_else(items).inspect(|(_, vis)| {
2004                types_is_visible = Some(resolver.is_visible(db, *vis));
2005            }));
2006
2007            if let Some(Some((res, _))) = types_ns
2008                && types_is_visible.unwrap_or_default()
2009            {
2010                return PathResolutionPerNs::new(Some(res), None, None);
2011            }
2012        }
2013    }
2014
2015    let mut macros_is_visible = false;
2016
2017    let mut types = types_ns.unwrap_or_else(|| types().or_else(items)).map(|(res, vis)| {
2018        types_is_visible = Some(types_is_visible.unwrap_or_else(|| resolver.is_visible(db, vis)));
2019        res
2020    });
2021    let mut values = values_ns.unwrap_or_else(values).map(|(res, vis)| {
2022        values_is_visible = Some(values_is_visible.unwrap_or_else(|| resolver.is_visible(db, vis)));
2023        res
2024    });
2025    let mut macros = macros().map(|(res, vis)| {
2026        macros_is_visible = resolver.is_visible(db, vis);
2027        res
2028    });
2029
2030    let types_is_visible = types_is_visible.unwrap_or_default();
2031    let values_is_visible = values_is_visible.unwrap_or_default();
2032
2033    // If there is a visible resolution and an invisible one, we only want to include the visible one. But if all are
2034    // invisible, we want to include them all.
2035    if types_is_visible || values_is_visible || macros_is_visible {
2036        if !types_is_visible {
2037            types = None;
2038        }
2039        if !values_is_visible {
2040            values = None;
2041        }
2042        if !macros_is_visible {
2043            macros = None;
2044        }
2045    }
2046
2047    PathResolutionPerNs { type_ns: types, value_ns: values, macro_ns: macros }
2048}
2049
2050fn resolve_hir_value_path<'db>(
2051    db: &'db dyn HirDatabase,
2052    resolver: &Resolver<'db>,
2053    store_owner: Option<ExpressionStoreOwnerId>,
2054    infer_body: Option<InferBodyId<'db>>,
2055    path: &Path,
2056    hygiene: HygieneId,
2057) -> Option<(PathResolution<'db>, Visibility)> {
2058    resolver.resolve_path_in_value_ns_with_prefix_info(db, path, hygiene).and_then(
2059        |(val, _, vis)| {
2060            let ResolveValueResult::ValueNs(val) = val else { return None };
2061            let res = match val {
2062                ValueNs::LocalBinding(binding_id) => {
2063                    let var = Local { parent: store_owner?, parent_infer: infer_body?, binding_id };
2064                    PathResolution::Local(var)
2065                }
2066                ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),
2067                ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),
2068                ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),
2069                ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),
2070                ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
2071                ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),
2072                ValueNs::GenericParam(id) => PathResolution::ConstParam(id.into()),
2073            };
2074            Some((res, vis))
2075        },
2076    )
2077}
2078
2079/// Resolves a path where we know it is a qualifier of another path.
2080///
2081/// For example, if we have:
2082/// ```
2083/// mod my {
2084///     pub mod foo {
2085///         struct Bar;
2086///     }
2087///
2088///     pub fn foo() {}
2089/// }
2090/// ```
2091/// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.
2092fn resolve_hir_path_qualifier<'db>(
2093    db: &'db dyn HirDatabase,
2094    resolver: &Resolver<'db>,
2095    path: &Path,
2096    store: &ExpressionStore,
2097) -> Option<PathResolution<'db>> {
2098    (|| {
2099        let (ty, unresolved) = match path.type_anchor() {
2100            Some(type_ref) => resolver.generic_def().and_then(|def| {
2101                let generics = OnceCell::new();
2102                let (_, res) = TyLoweringContext::new(
2103                    db,
2104                    resolver,
2105                    store,
2106                    resolver.expression_store_owner().unwrap_or_else(|| def.into()),
2107                    def,
2108                    &generics,
2109                    LifetimeElisionKind::Infer,
2110                    LifetimeLoweringMode::LateParam,
2111                )
2112                .with_interning_mode(LoweringMode::Ide)
2113                .lower_ty_ext(type_ref);
2114                res.map(|ty_ns| (ty_ns, path.segments().first()))
2115            }),
2116            None => {
2117                let (ty, remaining_idx, _) = resolver.resolve_path_in_type_ns(db, path)?;
2118                match remaining_idx {
2119                    Some(remaining_idx) => {
2120                        if remaining_idx + 1 == path.segments().len() {
2121                            Some((ty, path.segments().last()))
2122                        } else {
2123                            None
2124                        }
2125                    }
2126                    None => Some((ty, None)),
2127                }
2128            }
2129        }?;
2130
2131        // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type
2132        // within the trait's associated types.
2133        if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty)
2134            && let Some(type_alias_id) =
2135                trait_id.trait_items(db).associated_type_by_name(unresolved.name)
2136        {
2137            return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));
2138        }
2139
2140        let res = match ty {
2141            TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),
2142            TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()),
2143            TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {
2144                PathResolution::Def(Adt::from(it).into())
2145            }
2146            TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),
2147            TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),
2148            TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),
2149            TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),
2150            TypeNs::ModuleId(it) => PathResolution::Def(ModuleDef::Module(it.into())),
2151        };
2152        match unresolved {
2153            Some(unresolved) => resolver
2154                .generic_def()
2155                .and_then(|def| {
2156                    hir_ide::associated_type_shorthand_candidates(
2157                        db,
2158                        def,
2159                        res.in_type_ns()?,
2160                        |name, _| name == unresolved.name,
2161                    )
2162                })
2163                .map(TypeAlias::from)
2164                .map(Into::into)
2165                .map(PathResolution::Def),
2166            None => Some(res),
2167        }
2168    })()
2169    .or_else(|| {
2170        resolver
2171            .resolve_module_path_in_items(db, path.mod_path()?)
2172            .take_types()
2173            .map(|it| PathResolution::Def(it.into()))
2174    })
2175}
2176
2177pub(crate) fn name_hygiene(db: &dyn HirDatabase, name: InFile<&SyntaxNode>) -> HygieneId {
2178    let Some(macro_file) = name.file_id.macro_file() else {
2179        return HygieneId::ROOT;
2180    };
2181    let span_map = macro_file.expansion_span_map(db);
2182    let ctx = span_map.span_at(name.value.text_range().start()).ctx;
2183    HygieneId::new(ctx.opaque_and_semiopaque(db))
2184}
2185
2186fn record_literal_matched_fields(
2187    db: &dyn HirDatabase,
2188    infer: &InferenceResult<'_>,
2189    id: ExprId,
2190    expr: &Expr,
2191) -> Option<(VariantId, Vec<LocalFieldId>)> {
2192    let (fields, _spread) = match expr {
2193        Expr::RecordLit { fields, spread, .. } => (fields, spread),
2194        _ => return None,
2195    };
2196
2197    let variant_def = infer.variant_resolution_for_expr(id)?;
2198    if let VariantId::UnionId(_) = variant_def {
2199        return None;
2200    }
2201
2202    let variant_data = variant_def.fields(db);
2203
2204    let specified_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();
2205    // suggest fields if:
2206    // - not in code
2207    let matched_fields: Vec<LocalFieldId> = variant_data
2208        .fields()
2209        .iter()
2210        .filter_map(|(f, d)| (!specified_fields.contains(&d.name)).then_some(f))
2211        .collect();
2212    if matched_fields.is_empty() {
2213        return None;
2214    }
2215    Some((variant_def, matched_fields))
2216}
2217
2218fn record_pattern_matched_fields(
2219    db: &dyn HirDatabase,
2220    infer: &InferenceResult<'_>,
2221    id: PatId,
2222    pat: &Pat,
2223) -> Option<(VariantId, Vec<LocalFieldId>)> {
2224    let (fields, _ellipsis) = match pat {
2225        Pat::Record { path: _, args, ellipsis } => (args, *ellipsis),
2226        _ => return None,
2227    };
2228
2229    let variant_def = infer.variant_resolution_for_pat(id)?;
2230    if let VariantId::UnionId(_) = variant_def {
2231        return None;
2232    }
2233
2234    let variant_data = variant_def.fields(db);
2235
2236    let specified_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();
2237    // suggest fields if:
2238    // - not in code
2239    let matched_fields: Vec<LocalFieldId> = variant_data
2240        .fields()
2241        .iter()
2242        .filter_map(|(f, d)| if !specified_fields.contains(&d.name) { Some(f) } else { None })
2243        .collect();
2244    if matched_fields.is_empty() {
2245        return None;
2246    }
2247    Some((variant_def, matched_fields))
2248}