src/tools/rust-analyzer/crates/hir/src/source_analyzer.rs RUST 2,018 lines View on github.com → Search inside
File is large — showing lines 1–2,000 of 2,018.
1//! Lookup hir elements using positions in the source code. This is a lossy2//! transformation: in general, a single source might correspond to several3//! modules, functions, etc, due to macros, cfgs and `#[path=]` attributes on4//! modules.5//!6//! So, this modules should not be used during hir construction, it exists7//! purely for "IDE needs".8use std::iter::{self, once};910use either::Either;11use hir_def::{12    AdtId, AssocItemId, CallableDefId, ConstId, DefWithBodyId, ExpressionStoreOwnerId, FieldId,13    FunctionId, GenericDefId, LocalFieldId, ModuleDefId, StructId, TraitId, VariantId,14    expr_store::{15        Body, BodySourceMap, ExpressionStore, ExpressionStoreSourceMap, HygieneId,16        lower::ExprCollector,17        path::Path,18        scope::{ExprScopes, ScopeId},19    },20    hir::{BindingId, Expr, ExprId, ExprOrPatId, Pat, PatId, generics::GenericParams},21    lang_item::LangItems,22    nameres::MacroSubNs,23    resolver::{Resolver, TypeNs, ValueNs, resolver_for_scope},24    type_ref::{Mutability, TypeRef, TypeRefId},25};26use hir_expand::{27    HirFileId, InFile,28    mod_path::{ModPath, PathKind, path},29    name::{AsName, Name},30};31use hir_ty::{32    Adjustment, InferenceResult, LifetimeElisionKind, ParamEnvAndCrate, TyLoweringContext,33    diagnostics::{34        InsideUnsafeBlock, record_literal_missing_fields, record_pattern_missing_fields,35        unsafe_operations,36    },37    lang_items::lang_items_for_bin_op,38    method_resolution::{self, CandidateId},39    next_solver::{40        AliasTy, DbInterner, ErrorGuaranteed, GenericArgs, ParamEnv, Ty, TyKind, TypingMode,41        infer::DbInternerInferExt,42    },43    traits::structurally_normalize_ty,44};45use intern::sym;46use itertools::Itertools;47use rustc_hash::FxHashSet;48use rustc_type_ir::{49    AliasTyKind,50    inherent::{AdtDef, IntoKind, Ty as _},51};52use smallvec::SmallVec;53use stdx::never;54use syntax::{55    SyntaxKind, SyntaxNode, TextRange, TextSize,56    ast::{self, AstNode, RangeItem, RangeOp},57};5859use crate::{60    Adt, AnyFunctionId, AssocItem, BindingMode, BuiltinAttr, BuiltinType, Callable, Const,61    DeriveHelper, EnumVariant, Field, Function, GenericSubstitution, Local, Macro, ModuleDef,62    Static, Struct, ToolModule, Trait, TupleField, Type, TypeAlias,63    db::HirDatabase,64    semantics::{PathResolution, PathResolutionPerNs},65};6667/// `SourceAnalyzer` is a convenience wrapper which exposes HIR API in terms of68/// original source files. It should not be used inside the HIR itself.69#[derive(Debug)]70pub(crate) struct SourceAnalyzer<'db> {71    pub(crate) file_id: HirFileId,72    pub(crate) resolver: Resolver<'db>,73    pub(crate) body_or_sig: Option<BodyOrSig<'db>>,74}7576#[derive(Debug)]77pub(crate) enum BodyOrSig<'db> {78    Body {79        def: DefWithBodyId,80        body: &'db Body,81        source_map: &'db BodySourceMap,82        infer: Option<&'db InferenceResult>,83    },84    VariantFields {85        def: VariantId,86        store: &'db ExpressionStore,87        source_map: &'db ExpressionStoreSourceMap,88        infer: Option<&'db InferenceResult>,89    },90    Sig {91        def: GenericDefId,92        store: &'db ExpressionStore,93        source_map: &'db ExpressionStoreSourceMap,94        infer: Option<&'db InferenceResult>,95        #[expect(dead_code)]96        generics: &'db GenericParams,97    },98}99100impl<'db> SourceAnalyzer<'db> {101    pub(crate) fn new_for_body(102        db: &'db dyn HirDatabase,103        def: DefWithBodyId,104        node: InFile<&SyntaxNode>,105        offset: Option<TextSize>,106    ) -> SourceAnalyzer<'db> {107        Self::new_for_body_(db, def, node, offset, Some(InferenceResult::of(db, def)))108    }109110    pub(crate) fn new_for_body_no_infer(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, None)117    }118119    pub(crate) fn new_for_body_(120        db: &'db dyn HirDatabase,121        def: DefWithBodyId,122        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,123        offset: Option<TextSize>,124        infer: Option<&'db InferenceResult>,125    ) -> SourceAnalyzer<'db> {126        let (body, source_map) = Body::with_source_map(db, def);127        let scopes = ExprScopes::of(db, def);128        let scope = match offset {129            None => scope_for(db, scopes, source_map, node),130            Some(offset) => {131                debug_assert!(132                    node.text_range().contains_inclusive(offset),133                    "{:?} not in {:?}",134                    offset,135                    node.text_range()136                );137                scope_for_offset(db, scopes, source_map, node.file_id, offset)138            }139        };140        let resolver = resolver_for_scope(db, def, scope);141        SourceAnalyzer {142            resolver,143            body_or_sig: Some(BodyOrSig::Body { def, body, source_map, infer }),144            file_id,145        }146    }147148    pub(crate) fn new_generic_def(149        db: &'db dyn HirDatabase,150        def: GenericDefId,151        node: InFile<&SyntaxNode>,152        offset: Option<TextSize>,153    ) -> SourceAnalyzer<'db> {154        Self::new_generic_def_(db, def, node, offset, true)155    }156157    pub(crate) fn new_generic_def_no_infer(158        db: &'db dyn HirDatabase,159        def: GenericDefId,160        node: InFile<&SyntaxNode>,161        offset: Option<TextSize>,162    ) -> SourceAnalyzer<'db> {163        Self::new_generic_def_(db, def, node, offset, false)164    }165166    pub(crate) fn new_generic_def_(167        db: &'db dyn HirDatabase,168        def: GenericDefId,169        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,170        offset: Option<TextSize>,171        infer: bool,172    ) -> SourceAnalyzer<'db> {173        let (generics, store, source_map) = GenericParams::with_source_map(db, def);174        let scopes = ExprScopes::of(db, def);175        let scope = match offset {176            None => scope_for(db, scopes, source_map, node),177            Some(offset) => {178                debug_assert!(179                    node.text_range().contains_inclusive(offset),180                    "{:?} not in {:?}",181                    offset,182                    node.text_range()183                );184                scope_for_offset(db, scopes, source_map, node.file_id, offset)185            }186        };187        let resolver = resolver_for_scope(db, def, scope);188        let infer = if infer { Some(InferenceResult::of(db, def)) } else { None };189        SourceAnalyzer {190            resolver,191            body_or_sig: Some(BodyOrSig::Sig { def, store, source_map, generics, infer }),192            file_id,193        }194    }195196    pub(crate) fn new_variant_body(197        db: &'db dyn HirDatabase,198        def: VariantId,199        node @ InFile { file_id, .. }: InFile<&SyntaxNode>,200        offset: Option<TextSize>,201        infer: bool,202    ) -> SourceAnalyzer<'db> {203        let (fields, source_map) = def.fields_with_source_map(db);204        let scopes = ExprScopes::of(db, def);205        let scope = match offset {206            None => scope_for(db, scopes, source_map, node),207            Some(offset) => {208                debug_assert!(209                    node.text_range().contains_inclusive(offset),210                    "{:?} not in {:?}",211                    offset,212                    node.text_range()213                );214                scope_for_offset(db, scopes, source_map, node.file_id, offset)215            }216        };217        let resolver = resolver_for_scope(db, def, scope);218        let infer = if infer { Some(InferenceResult::of(db, def)) } else { None };219        SourceAnalyzer {220            resolver,221            body_or_sig: Some(BodyOrSig::VariantFields {222                def,223                store: &fields.store,224                source_map,225                infer,226            }),227            file_id,228        }229    }230231    pub(crate) fn new_for_resolver(232        resolver: Resolver<'db>,233        node: InFile<&SyntaxNode>,234    ) -> SourceAnalyzer<'db> {235        SourceAnalyzer { resolver, body_or_sig: None, file_id: node.file_id }236    }237238    fn owner(&self) -> Option<ExpressionStoreOwnerId> {239        self.body_or_sig.as_ref().map(|it| match *it {240            BodyOrSig::VariantFields { def, .. } => def.into(),241            BodyOrSig::Sig { def, .. } => def.into(),242            BodyOrSig::Body { def, .. } => def.into(),243        })244    }245246    fn infer(&self) -> Option<&InferenceResult> {247        self.body_or_sig.as_ref().and_then(|it| match it {248            BodyOrSig::VariantFields { infer, .. }249            | BodyOrSig::Sig { infer, .. }250            | BodyOrSig::Body { infer, .. } => infer.as_deref(),251        })252    }253254    pub(crate) fn def(255        &self,256    ) -> Option<(257        ExpressionStoreOwnerId,258        &ExpressionStore,259        &ExpressionStoreSourceMap,260        Option<&InferenceResult>,261    )> {262        self.body_or_sig.as_ref().map(|it| match *it {263            BodyOrSig::VariantFields { def, store, source_map, infer, .. } => {264                (def.into(), store, source_map, infer)265            }266            BodyOrSig::Sig { def, store, source_map, infer, .. } => {267                (def.into(), store, source_map, infer)268            }269            BodyOrSig::Body { def, body, source_map, infer, .. } => {270                (def.into(), &body.store, &source_map.store, infer)271            }272        })273    }274275    pub(crate) fn store(&self) -> Option<&ExpressionStore> {276        self.body_or_sig.as_ref().map(|it| match it {277            BodyOrSig::Sig { store, .. } => &**store,278            BodyOrSig::VariantFields { store, .. } => &**store,279            BodyOrSig::Body { body, .. } => &body.store,280        })281    }282283    pub(crate) fn store_sm(&self) -> Option<&ExpressionStoreSourceMap> {284        self.body_or_sig.as_ref().map(|it| match it {285            BodyOrSig::Sig { source_map, .. } => &**source_map,286            BodyOrSig::VariantFields { source_map, .. } => &**source_map,287            BodyOrSig::Body { source_map, .. } => &source_map.store,288        })289    }290291    fn param_and<'a>(&self, param_env: ParamEnv<'a>) -> ParamEnvAndCrate<'a> {292        ParamEnvAndCrate { param_env, krate: self.resolver.krate() }293    }294295    fn trait_environment(&self, db: &'db dyn HirDatabase) -> ParamEnvAndCrate<'db> {296        self.param_and(self.body_or_sig.as_ref().map_or_else(ParamEnv::empty, |body_or_sig| {297            match *body_or_sig {298                BodyOrSig::Body { def, .. } => db.trait_environment(def.into()),299                BodyOrSig::VariantFields { def, .. } => db.trait_environment(def.into()),300                BodyOrSig::Sig { def, .. } => db.trait_environment(def.into()),301            }302        }))303    }304305    pub(crate) fn expr_id(&self, expr: ast::Expr) -> Option<ExprOrPatId> {306        let src = InFile { file_id: self.file_id, value: expr };307        self.store_sm()?.node_expr(src.as_ref())308    }309310    fn pat_id(&self, pat: &ast::Pat) -> Option<ExprOrPatId> {311        let src = InFile { file_id: self.file_id, value: pat };312        self.store_sm()?.node_pat(src)313    }314315    fn type_id(&self, pat: &ast::Type) -> Option<TypeRefId> {316        let src = InFile { file_id: self.file_id, value: pat };317        self.store_sm()?.node_type(src)318    }319320    fn binding_id_of_pat(&self, pat: &ast::IdentPat) -> Option<BindingId> {321        let pat_id = self.pat_id(&pat.clone().into())?;322        if let Pat::Bind { id, .. } = self.store()?[pat_id.as_pat()?] { Some(id) } else { None }323    }324325    pub(crate) fn expr_adjustments(&self, expr: &ast::Expr) -> Option<&[Adjustment]> {326        // It is safe to omit destructuring assignments here because they have no adjustments (neither327        // expressions nor patterns).328        let expr_id = self.expr_id(expr.clone())?.as_expr()?;329        let infer = self.infer()?;330        infer.expr_adjustment(expr_id)331    }332333    pub(crate) fn type_of_type(334        &self,335        db: &'db dyn HirDatabase,336        ty: &ast::Type,337    ) -> Option<Type<'db>> {338        let interner = DbInterner::new_no_crate(db);339340        let type_ref = self.type_id(ty)?;341342        let mut ty = TyLoweringContext::new(343            db,344            &self.resolver,345            self.store()?,346            self.resolver.generic_def()?,347            // FIXME: Is this correct here? Anyway that should impact mostly diagnostics, which we don't emit here348            // (this can impact the lifetimes generated, e.g. in `const` they won't be `'static`, but this seems like a349            // small problem).350            LifetimeElisionKind::Infer,351        )352        .lower_ty(type_ref);353354        // Try and substitute unknown types using InferenceResult355        if let Some(infer) = self.infer()356            && let Some(store) = self.store()357        {358            let mut inferred_types = vec![];359            TypeRef::walk(type_ref, store, &mut |type_ref_id, type_ref| {360                if matches!(type_ref, TypeRef::Placeholder) {361                    inferred_types.push(infer.type_of_type_placeholder(type_ref_id));362                }363            });364            let mut inferred_types = inferred_types.into_iter();365366            let substituted_ty = hir_ty::next_solver::fold::fold_tys(interner, ty, |ty| {367                if ty.is_ty_error() { inferred_types.next().flatten().unwrap_or(ty) } else { ty }368            });369370            // Only used the result if the placeholder and unknown type counts matched371            let success =372                inferred_types.next().is_none() && !substituted_ty.references_non_lt_error();373            if success {374                ty = substituted_ty;375            }376        }377378        Some(Type::new_with_resolver(db, &self.resolver, ty))379    }380381    pub(crate) fn type_of_expr(382        &self,383        db: &'db dyn HirDatabase,384        expr: &ast::Expr,385    ) -> Option<(Type<'db>, Option<Type<'db>>)> {386        let expr_id = self.expr_id(expr.clone())?;387        let infer = self.infer()?;388        let coerced = expr_id389            .as_expr()390            .and_then(|expr_id| infer.expr_adjustment(expr_id))391            .and_then(|adjusts| adjusts.last().map(|adjust| adjust.target.as_ref()));392        let ty = infer.expr_or_pat_ty(expr_id);393        let mk_ty = |ty: Ty<'db>| Type::new_with_resolver(db, &self.resolver, ty);394        Some((mk_ty(ty), coerced.map(mk_ty)))395    }396397    pub(crate) fn type_of_pat(398        &self,399        db: &'db dyn HirDatabase,400        pat: &ast::Pat,401    ) -> Option<(Type<'db>, Option<Type<'db>>)> {402        let expr_or_pat_id = self.pat_id(pat)?;403        let infer = self.infer()?;404        let coerced = match expr_or_pat_id {405            ExprOrPatId::ExprId(idx) => infer406                .expr_adjustment(idx)407                .and_then(|adjusts| adjusts.last())408                .map(|adjust| adjust.target.as_ref()),409            ExprOrPatId::PatId(idx) => infer410                .pat_adjustment(idx)411                .and_then(|adjusts| adjusts.last())412                .map(|adjust| adjust.as_ref()),413        };414415        let ty = infer.expr_or_pat_ty(expr_or_pat_id);416        let mk_ty = |ty: Ty<'db>| Type::new_with_resolver(db, &self.resolver, ty);417        Some((mk_ty(ty), coerced.map(mk_ty)))418    }419420    pub(crate) fn type_of_binding_in_pat(421        &self,422        db: &'db dyn HirDatabase,423        pat: &ast::IdentPat,424    ) -> Option<Type<'db>> {425        let binding_id = self.binding_id_of_pat(pat)?;426        let infer = self.infer()?;427        let ty = infer.binding_ty(binding_id);428        let mk_ty = |ty: Ty<'db>| Type::new_with_resolver(db, &self.resolver, ty);429        Some(mk_ty(ty))430    }431432    pub(crate) fn type_of_self(433        &self,434        db: &'db dyn HirDatabase,435        _param: &ast::SelfParam,436    ) -> Option<Type<'db>> {437        let binding = match self.body_or_sig.as_ref()? {438            BodyOrSig::Sig { .. } | BodyOrSig::VariantFields { .. } => return None,439            BodyOrSig::Body { body, .. } => body.self_param?,440        };441        let ty = self.infer()?.binding_ty(binding);442        Some(Type::new_with_resolver(db, &self.resolver, ty))443    }444445    pub(crate) fn binding_mode_of_pat(446        &self,447        _db: &'db dyn HirDatabase,448        pat: &ast::IdentPat,449    ) -> Option<BindingMode> {450        let id = self.pat_id(&pat.clone().into())?;451        let infer = self.infer()?;452        infer.binding_mode(id.as_pat()?).map(|bm| match bm {453            hir_ty::BindingMode::Move => BindingMode::Move,454            hir_ty::BindingMode::Ref(hir_ty::next_solver::Mutability::Mut) => {455                BindingMode::Ref(Mutability::Mut)456            }457            hir_ty::BindingMode::Ref(hir_ty::next_solver::Mutability::Not) => {458                BindingMode::Ref(Mutability::Shared)459            }460        })461    }462    pub(crate) fn pattern_adjustments(463        &self,464        db: &'db dyn HirDatabase,465        pat: &ast::Pat,466    ) -> Option<SmallVec<[Type<'db>; 1]>> {467        let pat_id = self.pat_id(pat)?;468        let infer = self.infer()?;469        Some(470            infer471                .pat_adjustment(pat_id.as_pat()?)?472                .iter()473                .map(|ty| Type::new_with_resolver(db, &self.resolver, ty.as_ref()))474                .collect(),475        )476    }477478    pub(crate) fn resolve_method_call_as_callable(479        &self,480        db: &'db dyn HirDatabase,481        call: &ast::MethodCallExpr,482    ) -> Option<Callable<'db>> {483        let expr_id = self.expr_id(call.clone().into())?.as_expr()?;484        let (func, args) = self.infer()?.method_resolution(expr_id)?;485        let interner = DbInterner::new_no_crate(db);486        let ty = db.value_ty(func.into())?.instantiate(interner, args);487        let ty = Type::new_with_resolver(db, &self.resolver, ty);488        let mut res = ty.as_callable(db)?;489        res.is_bound_method = true;490        Some(res)491    }492493    pub(crate) fn resolve_method_call(494        &self,495        db: &'db dyn HirDatabase,496        call: &ast::MethodCallExpr,497    ) -> Option<Function> {498        let expr_id = self.expr_id(call.clone().into())?.as_expr()?;499        let (f_in_trait, substs) = self.infer()?.method_resolution(expr_id)?;500501        Some(self.resolve_impl_method_or_trait_def(db, f_in_trait, substs))502    }503504    pub(crate) fn resolve_method_call_fallback(505        &self,506        db: &'db dyn HirDatabase,507        call: &ast::MethodCallExpr,508    ) -> Option<(Either<Function, Field>, Option<GenericSubstitution<'db>>)> {509        let expr_id = self.expr_id(call.clone().into())?.as_expr()?;510        let inference_result = self.infer()?;511        match inference_result.method_resolution(expr_id) {512            Some((f_in_trait, substs)) => {513                let (fn_, subst) =514                    self.resolve_impl_method_or_trait_def_with_subst(db, f_in_trait, substs);515                Some((516                    Either::Left(fn_),517                    GenericSubstitution::new_from_fn(fn_, subst, self.trait_environment(db)),518                ))519            }520            None => {521                inference_result.field_resolution(expr_id).and_then(Either::left).map(|field| {522                    (Either::Right(field.into()), self.field_subst(expr_id, inference_result, db))523                })524            }525        }526    }527528    pub(crate) fn resolve_expr_as_callable(529        &self,530        db: &'db dyn HirDatabase,531        call: &ast::Expr,532    ) -> Option<Callable<'db>> {533        let (orig, adjusted) = self.type_of_expr(db, &call.clone())?;534        adjusted.unwrap_or(orig).as_callable(db)535    }536537    pub(crate) fn resolve_field(538        &self,539        field: &ast::FieldExpr,540    ) -> Option<Either<Field, TupleField>> {541        let def = self.owner()?;542        let expr_id = self.expr_id(field.clone().into())?.as_expr()?;543        self.infer()?.field_resolution(expr_id).map(|it| {544            it.map_either(Into::into, |f| TupleField { owner: def, tuple: f.tuple, index: f.index })545        })546    }547548    fn field_subst(549        &self,550        field_expr: ExprId,551        infer: &InferenceResult,552        db: &'db dyn HirDatabase,553    ) -> Option<GenericSubstitution<'db>> {554        let body = self.store()?;555        if let Expr::Field { expr: object_expr, name: _ } = body[field_expr] {556            let (adt, subst) = infer.type_of_expr_with_adjust(object_expr)?.as_adt()?;557            return Some(GenericSubstitution::new(adt.into(), subst, self.trait_environment(db)));558        }559        None560    }561562    pub(crate) fn resolve_field_fallback(563        &self,564        db: &'db dyn HirDatabase,565        field: &ast::FieldExpr,566    ) -> Option<(Either<Either<Field, TupleField>, Function>, Option<GenericSubstitution<'db>>)>567    {568        let def = self.owner()?;569        let expr_id = self.expr_id(field.clone().into())?.as_expr()?;570        let inference_result = self.infer()?;571        match inference_result.field_resolution(expr_id) {572            Some(field) => match field {573                Either::Left(field) => Some((574                    Either::Left(Either::Left(field.into())),575                    self.field_subst(expr_id, inference_result, db),576                )),577                Either::Right(field) => Some((578                    Either::Left(Either::Right(TupleField {579                        owner: def,580                        tuple: field.tuple,581                        index: field.index,582                    })),583                    None,584                )),585            },586            None => inference_result.method_resolution(expr_id).map(|(f, substs)| {587                let (f, subst) = self.resolve_impl_method_or_trait_def_with_subst(db, f, substs);588                (589                    Either::Right(f),590                    GenericSubstitution::new_from_fn(f, subst, self.trait_environment(db)),591                )592            }),593        }594    }595596    pub(crate) fn resolve_range_pat(597        &self,598        db: &'db dyn HirDatabase,599        range_pat: &ast::RangePat,600    ) -> Option<StructId> {601        self.resolve_range_struct(602            db,603            range_pat.op_kind()?,604            range_pat.start().is_some(),605            range_pat.end().is_some(),606        )607    }608609    pub(crate) fn resolve_range_expr(610        &self,611        db: &'db dyn HirDatabase,612        range_expr: &ast::RangeExpr,613    ) -> Option<StructId> {614        self.resolve_range_struct(615            db,616            range_expr.op_kind()?,617            range_expr.start().is_some(),618            range_expr.end().is_some(),619        )620    }621622    fn resolve_range_struct(623        &self,624        db: &'db dyn HirDatabase,625        op_kind: RangeOp,626        has_start: bool,627        has_end: bool,628    ) -> Option<StructId> {629        let has_new_range =630            self.resolver.top_level_def_map().is_unstable_feature_enabled(&sym::new_range);631        let lang_items = self.lang_items(db);632        match (op_kind, has_start, has_end) {633            (RangeOp::Exclusive, false, false) => lang_items.RangeFull,634            (RangeOp::Exclusive, false, true) => lang_items.RangeTo,635            (RangeOp::Exclusive, true, false) => {636                if has_new_range {637                    lang_items.RangeFromCopy638                } else {639                    lang_items.RangeFrom640                }641            }642            (RangeOp::Exclusive, true, true) => {643                if has_new_range {644                    lang_items.RangeCopy645                } else {646                    lang_items.Range647                }648            }649            (RangeOp::Inclusive, false, true) => {650                if has_new_range {651                    lang_items.RangeToInclusiveCopy652                } else {653                    lang_items.RangeToInclusive654                }655            }656            (RangeOp::Inclusive, true, true) => {657                if has_new_range {658                    lang_items.RangeInclusiveCopy659                } else {660                    lang_items.RangeInclusiveStruct661                }662            }663            // [E0586] inclusive ranges must be bounded at the end664            (RangeOp::Inclusive, false, false) => None,665            (RangeOp::Inclusive, true, false) => None,666        }667    }668669    pub(crate) fn resolve_await_to_poll(670        &self,671        db: &'db dyn HirDatabase,672        await_expr: &ast::AwaitExpr,673    ) -> Option<Function> {674        let mut ty = self.ty_of_expr(await_expr.expr()?)?;675676        let into_future_trait = self677            .resolver678            .resolve_known_trait(db, &path![core::future::IntoFuture])679            .map(Trait::from);680681        if let Some(into_future_trait) = into_future_trait {682            let type_ = Type::new_with_resolver(db, &self.resolver, ty);683            if type_.impls_trait(db, into_future_trait, &[]) {684                let items = into_future_trait.items(db);685                let into_future_type = items.into_iter().find_map(|item| match item {686                    AssocItem::TypeAlias(alias)687                        if alias.name(db) == Name::new_symbol_root(sym::IntoFuture) =>688                    {689                        Some(alias)690                    }691                    _ => None,692                })?;693                let future_trait = type_.normalize_trait_assoc_type(db, &[], into_future_type)?;694                ty = future_trait.ty;695            }696        }697698        let poll_fn = self.lang_items(db).FuturePoll?;699        // HACK: subst for `poll()` coincides with that for `Future` because `poll()` itself700        // doesn't have any generic parameters, so we skip building another subst for `poll()`.701        let substs = GenericArgs::new_from_slice(&[ty.into()]);702        Some(self.resolve_impl_method_or_trait_def(db, poll_fn, substs))703    }704705    pub(crate) fn resolve_prefix_expr(706        &self,707        db: &'db dyn HirDatabase,708        prefix_expr: &ast::PrefixExpr,709    ) -> Option<Function> {710        let (_op_trait, op_fn) = match prefix_expr.op_kind()? {711            ast::UnaryOp::Deref => {712                // This can be either `Deref::deref` or `DerefMut::deref_mut`.713                // Since deref kind is inferenced and stored in `InferenceResult.method_resolution`,714                // use that result to find out which one it is.715                let (deref_trait, deref) = self.lang_trait_fn(716                    db,717                    self.lang_items(db).Deref,718                    &Name::new_symbol_root(sym::deref),719                )?;720                self.infer()721                    .and_then(|infer| {722                        let expr = self.expr_id(prefix_expr.clone().into())?.as_expr()?;723                        let (func, _) = infer.method_resolution(expr)?;724                        let (deref_mut_trait, deref_mut) = self.lang_trait_fn(725                            db,726                            self.lang_items(db).DerefMut,727                            &Name::new_symbol_root(sym::deref_mut),728                        )?;729                        if func == deref_mut { Some((deref_mut_trait, deref_mut)) } else { None }730                    })731                    .unwrap_or((deref_trait, deref))732            }733            ast::UnaryOp::Not => {734                self.lang_trait_fn(db, self.lang_items(db).Not, &Name::new_symbol_root(sym::not))?735            }736            ast::UnaryOp::Neg => {737                self.lang_trait_fn(db, self.lang_items(db).Neg, &Name::new_symbol_root(sym::neg))?738            }739        };740741        let ty = self.ty_of_expr(prefix_expr.expr()?)?;742743        // HACK: subst for all methods coincides with that for their trait because the methods744        // don't have any generic parameters, so we skip building another subst for the methods.745        let substs = GenericArgs::new_from_slice(&[ty.into()]);746747        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))748    }749750    pub(crate) fn resolve_index_expr(751        &self,752        db: &'db dyn HirDatabase,753        index_expr: &ast::IndexExpr,754    ) -> Option<Function> {755        let base_ty = self.ty_of_expr(index_expr.base()?)?;756        let index_ty = self.ty_of_expr(index_expr.index()?)?;757758        let (_index_trait, index_fn) =759            self.lang_trait_fn(db, self.lang_items(db).Index, &Name::new_symbol_root(sym::index))?;760        let op_fn = self761            .infer()762            .and_then(|infer| {763                let expr = self.expr_id(index_expr.clone().into())?.as_expr()?;764                let (func, _) = infer.method_resolution(expr)?;765                let (_index_mut_trait, index_mut_fn) = self.lang_trait_fn(766                    db,767                    self.lang_items(db).IndexMut,768                    &Name::new_symbol_root(sym::index_mut),769                )?;770                if func == index_mut_fn { Some(index_mut_fn) } else { None }771            })772            .unwrap_or(index_fn);773        // HACK: subst for all methods coincides with that for their trait because the methods774        // don't have any generic parameters, so we skip building another subst for the methods.775        let substs = GenericArgs::new_from_slice(&[base_ty.into(), index_ty.into()]);776        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))777    }778779    pub(crate) fn resolve_bin_expr(780        &self,781        db: &'db dyn HirDatabase,782        binop_expr: &ast::BinExpr,783    ) -> Option<Function> {784        let op = binop_expr.op_kind()?;785        let lhs = self.ty_of_expr(binop_expr.lhs()?)?;786        let rhs = self.ty_of_expr(binop_expr.rhs()?)?;787788        let (_op_trait, op_fn) =789            lang_items_for_bin_op(self.lang_items(db), op).and_then(|(name, lang_item)| {790                self.lang_trait_fn(db, lang_item, &Name::new_symbol_root(name))791            })?;792        // HACK: subst for `index()` coincides with that for `Index` because `index()` itself793        // doesn't have any generic parameters, so we skip building another subst for `index()`.794        let substs = GenericArgs::new_from_slice(&[lhs.into(), rhs.into()]);795796        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))797    }798799    pub(crate) fn resolve_try_expr(800        &self,801        db: &'db dyn HirDatabase,802        try_expr: &ast::TryExpr,803    ) -> Option<Function> {804        let ty = self.ty_of_expr(try_expr.expr()?)?;805806        let op_fn = self.lang_items(db).TryTraitBranch?;807        // HACK: subst for `branch()` coincides with that for `Try` because `branch()` itself808        // doesn't have any generic parameters, so we skip building another subst for `branch()`.809        let substs = GenericArgs::new_from_slice(&[ty.into()]);810811        Some(self.resolve_impl_method_or_trait_def(db, op_fn, substs))812    }813814    pub(crate) fn resolve_record_field(815        &self,816        db: &'db dyn HirDatabase,817        field: &ast::RecordExprField,818    ) -> Option<(Field, Option<Local>, Type<'db>, GenericSubstitution<'db>)> {819        let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?;820        let expr = ast::Expr::from(record_expr);821        let expr_id = self.store_sm()?.node_expr(InFile::new(self.file_id, &expr))?;822        let interner = DbInterner::new_no_crate(db);823824        let ast_name = field.field_name()?;825        let local_name = ast_name.as_name();826        let local = if field.name_ref().is_some() {827            None828        } else {829            // Shorthand syntax, resolve to the local830            let path = Path::from_known_path_with_no_generic(ModPath::from_segments(831                PathKind::Plain,832                once(local_name.clone()),833            ));834            match self.resolver.resolve_path_in_value_ns_fully(835                db,836                &path,837                name_hygiene(db, InFile::new(self.file_id, ast_name.syntax())),838            ) {839                Some(ValueNs::LocalBinding(binding_id)) => {840                    Some(Local { binding_id, parent: self.resolver.expression_store_owner()? })841                }842                _ => None,843            }844        };845        let (adt, subst) = self.infer()?.type_of_expr_or_pat(expr_id)?.as_adt()?;846        let variant = self.infer()?.variant_resolution_for_expr_or_pat(expr_id)?;847        let variant_data = variant.fields(db);848        let field = FieldId { parent: variant, local_id: variant_data.field(&local_name)? };849        let field_ty =850            (*db.field_types(variant).get(field.local_id)?).get().instantiate(interner, subst);851        Some((852            field.into(),853            local,854            Type::new_with_resolver(db, &self.resolver, field_ty),855            GenericSubstitution::new(adt.into(), subst, self.trait_environment(db)),856        ))857    }858859    pub(crate) fn resolve_record_pat_field(860        &self,861        db: &'db dyn HirDatabase,862        field: &ast::RecordPatField,863    ) -> Option<(Field, Type<'db>, GenericSubstitution<'db>)> {864        let interner = DbInterner::new_no_crate(db);865        let field_name = field.field_name()?.as_name();866        let record_pat = ast::RecordPat::cast(field.syntax().parent().and_then(|p| p.parent())?)?;867        let pat_id = self.pat_id(&record_pat.into())?;868        let variant = self.infer()?.variant_resolution_for_pat(pat_id.as_pat()?)?;869        let variant_data = variant.fields(db);870        let field = FieldId { parent: variant, local_id: variant_data.field(&field_name)? };871        let (adt, subst) = self.infer()?.pat_ty(pat_id.as_pat()?).as_adt()?;872        let field_ty =873            (*db.field_types(variant).get(field.local_id)?).get().instantiate(interner, subst);874        Some((875            field.into(),876            Type::new_with_resolver(db, &self.resolver, field_ty),877            GenericSubstitution::new(adt.into(), subst, self.trait_environment(db)),878        ))879    }880881    pub(crate) fn resolve_bind_pat_to_const(882        &self,883        db: &'db dyn HirDatabase,884        pat: &ast::IdentPat,885    ) -> Option<ModuleDef> {886        let expr_or_pat_id = self.pat_id(&pat.clone().into())?;887        let store = self.store()?;888889        let path = match expr_or_pat_id {890            ExprOrPatId::ExprId(idx) => match &store[idx] {891                Expr::Path(path) => path,892                _ => return None,893            },894            ExprOrPatId::PatId(idx) => match &store[idx] {895                Pat::Path(path) => path,896                _ => return None,897            },898        };899900        let store_owner = self.resolver.expression_store_owner();901        let res = resolve_hir_value_path(db, &self.resolver, store_owner, path, HygieneId::ROOT)?;902        match res {903            PathResolution::Def(def) => Some(def),904            _ => None,905        }906    }907908    pub(crate) fn resolve_use_type_arg(&self, name: &ast::NameRef) -> Option<crate::TypeParam> {909        let name = name.as_name();910        self.resolver911            .all_generic_params()912            .find_map(|(params, parent)| params.find_type_by_name(&name, parent))913            .map(crate::TypeParam::from)914    }915916    pub(crate) fn resolve_offset_of_field(917        &self,918        db: &'db dyn HirDatabase,919        name_ref: &ast::NameRef,920    ) -> Option<(Either<crate::EnumVariant, crate::Field>, GenericSubstitution<'db>)> {921        let offset_of_expr = ast::OffsetOfExpr::cast(name_ref.syntax().parent()?)?;922        let container = offset_of_expr.ty()?;923        let container = self.type_of_type(db, &container)?;924925        let trait_env = container.env;926927        let interner = DbInterner::new_with(db, trait_env.krate);928        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);929930        let mut container = Either::Right(container.ty);931        for field_name in offset_of_expr.fields() {932            if let Either::Right(container) = &mut container {933                *container = structurally_normalize_ty(&infcx, *container, trait_env.param_env);934            }935            let handle_variants = |variant: VariantId,936                                   subst: GenericArgs<'db>,937                                   container: &mut _| {938                let fields = variant.fields(db);939                let field = fields.field(&field_name.as_name())?;940                let field_types = db.field_types(variant);941                *container = Either::Right(field_types[field].get().instantiate(interner, subst));942                let generic_def = match variant {943                    VariantId::EnumVariantId(it) => it.loc(db).parent.into(),944                    VariantId::StructId(it) => it.into(),945                    VariantId::UnionId(it) => it.into(),946                };947                Some((948                    Either::Right(Field { parent: variant.into(), id: field }),949                    generic_def,950                    subst,951                ))952            };953            let temp_ty = Ty::new_error(interner, ErrorGuaranteed);954            let (field_def, generic_def, subst) =955                match std::mem::replace(&mut container, Either::Right(temp_ty)) {956                    Either::Left((variant_id, subst)) => {957                        handle_variants(VariantId::from(variant_id), subst, &mut container)?958                    }959                    Either::Right(container_ty) => match container_ty.kind() {960                        TyKind::Adt(adt_def, subst) => match adt_def.def_id().0 {961                            AdtId::StructId(id) => {962                                handle_variants(id.into(), subst, &mut container)?963                            }964                            AdtId::UnionId(id) => {965                                handle_variants(id.into(), subst, &mut container)?966                            }967                            AdtId::EnumId(id) => {968                                let variants = id.enum_variants(db);969                                let variant = variants.variant(&field_name.as_name())?;970                                container = Either::Left((variant, subst));971                                (Either::Left(EnumVariant { id: variant }), id.into(), subst)972                            }973                        },974                        _ => return None,975                    },976                };977978            if field_name.syntax().text_range() == name_ref.syntax().text_range() {979                return Some((field_def, GenericSubstitution::new(generic_def, subst, trait_env)));980            }981        }982        never!("the `NameRef` is a child of the `OffsetOfExpr`, we should've visited it");983        None984    }985986    pub(crate) fn resolve_path(987        &self,988        db: &'db dyn HirDatabase,989        path: &ast::Path,990    ) -> Option<(PathResolution, Option<GenericSubstitution<'db>>)> {991        let parent = path.syntax().parent();992        let parent = || parent.clone();993994        let mut prefer_value_ns = false;995        let resolved = (|| {996            let infer = self.infer()?;997            if let Some(path_expr) = parent().and_then(ast::PathExpr::cast) {998                let expr_id = self.expr_id(path_expr.into())?;999                if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr_or_pat(expr_id) {1000                    let (assoc, subst) = match assoc {1001                        CandidateId::FunctionId(f_in_trait) => {1002                            match infer.type_of_expr_or_pat(expr_id) {1003                                None => {1004                                    let subst = GenericSubstitution::new(1005                                        f_in_trait.into(),1006                                        subs,1007                                        self.trait_environment(db),1008                                    );1009                                    (AssocItem::Function(f_in_trait.into()), Some(subst))1010                                }1011                                Some(func_ty) => {1012                                    if let TyKind::FnDef(_fn_def, subs) = func_ty.kind() {1013                                        let (fn_, subst) = self1014                                            .resolve_impl_method_or_trait_def_with_subst(1015                                                db, f_in_trait, subs,1016                                            );1017                                        let subst = GenericSubstitution::new_from_fn(1018                                            fn_,1019                                            subst,1020                                            self.trait_environment(db),1021                                        );1022                                        (AssocItem::Function(fn_), subst)1023                                    } else {1024                                        let subst = GenericSubstitution::new(1025                                            f_in_trait.into(),1026                                            subs,1027                                            self.trait_environment(db),1028                                        );1029                                        (AssocItem::Function(f_in_trait.into()), Some(subst))1030                                    }1031                                }1032                            }1033                        }1034                        CandidateId::ConstId(const_id) => {1035                            let (konst, subst) =1036                                self.resolve_impl_const_or_trait_def_with_subst(db, const_id, subs);1037                            let subst = GenericSubstitution::new(1038                                konst.into(),1039                                subst,1040                                self.trait_environment(db),1041                            );1042                            (AssocItem::Const(konst.into()), Some(subst))1043                        }1044                    };10451046                    return Some((PathResolution::Def(assoc.into()), subst));1047                }1048                if let Some(VariantId::EnumVariantId(variant)) =1049                    infer.variant_resolution_for_expr_or_pat(expr_id)1050                {1051                    return Some((1052                        PathResolution::Def(ModuleDef::EnumVariant(variant.into())),1053                        None,1054                    ));1055                }1056                prefer_value_ns = true;1057            } else if let Some(path_pat) = parent().and_then(ast::PathPat::cast) {1058                let expr_or_pat_id = self.pat_id(&path_pat.into())?;1059                if let Some((assoc, subs)) = infer.assoc_resolutions_for_expr_or_pat(expr_or_pat_id)1060                {1061                    let (assoc, subst) = match assoc {1062                        CandidateId::ConstId(const_id) => {1063                            let (konst, subst) =1064                                self.resolve_impl_const_or_trait_def_with_subst(db, const_id, subs);1065                            let subst = GenericSubstitution::new(1066                                konst.into(),1067                                subst,1068                                self.trait_environment(db),1069                            );1070                            (AssocItemId::from(konst), subst)1071                        }1072                        CandidateId::FunctionId(function_id) => (1073                            function_id.into(),1074                            GenericSubstitution::new(1075                                function_id.into(),1076                                subs,1077                                self.trait_environment(db),1078                            ),1079                        ),1080                    };1081                    return Some((PathResolution::Def(AssocItem::from(assoc).into()), Some(subst)));1082                }1083                if let Some(VariantId::EnumVariantId(variant)) =1084                    infer.variant_resolution_for_expr_or_pat(expr_or_pat_id)1085                {1086                    return Some((1087                        PathResolution::Def(ModuleDef::EnumVariant(variant.into())),1088                        None,1089                    ));1090                }1091            } else if let Some(rec_lit) = parent().and_then(ast::RecordExpr::cast) {1092                let expr_id = self.expr_id(rec_lit.into())?;1093                if let Some(VariantId::EnumVariantId(variant)) =1094                    infer.variant_resolution_for_expr_or_pat(expr_id)1095                {1096                    return Some((1097                        PathResolution::Def(ModuleDef::EnumVariant(variant.into())),1098                        None,1099                    ));1100                }1101            } else {1102                let record_pat = parent().and_then(ast::RecordPat::cast).map(ast::Pat::from);1103                let tuple_struct_pat =1104                    || parent().and_then(ast::TupleStructPat::cast).map(ast::Pat::from);1105                if let Some(pat) = record_pat.or_else(tuple_struct_pat) {1106                    let pat_id = self.pat_id(&pat)?;1107                    let variant_res_for_pat = infer.variant_resolution_for_pat(pat_id.as_pat()?);1108                    if let Some(VariantId::EnumVariantId(variant)) = variant_res_for_pat {1109                        return Some((1110                            PathResolution::Def(ModuleDef::EnumVariant(variant.into())),1111                            None,1112                        ));1113                    }1114                }1115            }1116            None1117        })();1118        if resolved.is_some() {1119            return resolved;1120        }11211122        // FIXME: collectiong here shouldnt be necessary?1123        let mut collector = ExprCollector::body(db, self.resolver.module(), self.file_id);1124        let hir_path =1125            collector.lower_path(path.clone(), &mut ExprCollector::impl_trait_error_allocator)?;1126        let parent_hir_path = path1127            .parent_path()1128            .and_then(|p| collector.lower_path(p, &mut ExprCollector::impl_trait_error_allocator));1129        let (store, _) = collector.store.finish();11301131        // Case where path is a qualifier of a use tree, e.g. foo::bar::{Baz, Qux} where we are1132        // trying to resolve foo::bar.1133        if let Some(use_tree) = parent().and_then(ast::UseTree::cast)1134            && use_tree.coloncolon_token().is_some()1135        {1136            return resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store)1137                .map(|it| (it, None));1138        }11391140        let meta_path = path1141            .syntax()1142            .ancestors()1143            .take_while(|it| {1144                let kind = it.kind();1145                ast::Path::can_cast(kind) || ast::Meta::can_cast(kind)1146            })1147            .last()1148            .and_then(ast::Meta::cast);11491150        // Case where path is a qualifier of another path, e.g. foo::bar::Baz where we are1151        // trying to resolve foo::bar.1152        if let Some(parent_hir_path) = parent_hir_path {1153            return match resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store) {1154                None if meta_path.is_some() => path1155                    .first_segment()1156                    .and_then(|it| it.name_ref())1157                    .and_then(|name_ref| {1158                        ToolModule::by_name(db, self.resolver.krate().into(), &name_ref.text())1159                            .map(PathResolution::ToolModule)1160                    })1161                    .map(|it| (it, None)),1162                // Case the type name conflict with use module,1163                // e.g.1164                // ```1165                // use std::str;1166                // fn main() {1167                //     str::from_utf8();  // as module std::str1168                //     str::len();        // as primitive type str1169                //     str::no_exist_item(); // as primitive type str1170                // }1171                // ```1172                Some(it) if matches!(it, PathResolution::Def(ModuleDef::BuiltinType(_))) => {1173                    if let Some(mod_path) = hir_path.mod_path()1174                        && let Some(ModuleDefId::ModuleId(id)) =1175                            self.resolver.resolve_module_path_in_items(db, mod_path).take_types()1176                    {1177                        let parent_hir_name = parent_hir_path.segments().get(1).map(|it| it.name);1178                        let module = crate::Module { id };1179                        if module1180                            .scope(db, None)1181                            .into_iter()1182                            .any(|(name, _)| Some(&name) == parent_hir_name)1183                        {1184                            return Some((PathResolution::Def(ModuleDef::Module(module)), None));1185                        };1186                    }1187                    Some((it, None))1188                }1189                // FIXME: We do not show substitutions for parts of path, because this is really complex1190                // due to the interactions with associated items of `impl`s and associated items of associated1191                // types.1192                res => res.map(|it| (it, None)),1193            };1194        } else if let Some(meta_path) = meta_path {1195            // Case where we are resolving the final path segment of a path in an attribute1196            // in this case we have to check for inert/builtin attributes and tools and prioritize1197            // resolution of attributes over other namespaces1198            if let Some(name_ref) = path.as_single_name_ref() {1199                let builtin = BuiltinAttr::builtin(&name_ref.text());1200                if builtin.is_some() {1201                    return builtin.map(|it| (PathResolution::BuiltinAttr(it), None));1202                }12031204                if let Some(attr) = meta_path.parent_attr() {1205                    let adt = if let Some(field) =1206                        attr.syntax().parent().and_then(ast::RecordField::cast)1207                    {1208                        field.syntax().ancestors().take(4).find_map(ast::Adt::cast)1209                    } else if let Some(field) =1210                        attr.syntax().parent().and_then(ast::TupleField::cast)1211                    {1212                        field.syntax().ancestors().take(4).find_map(ast::Adt::cast)1213                    } else if let Some(variant) =1214                        attr.syntax().parent().and_then(ast::Variant::cast)1215                    {1216                        variant.syntax().ancestors().nth(2).and_then(ast::Adt::cast)1217                    } else {1218                        None1219                    };1220                    if let Some(adt) = adt {1221                        let ast_id = db.ast_id_map(self.file_id).ast_id(&adt);1222                        if let Some(helpers) = self1223                            .resolver1224                            .def_map()1225                            .derive_helpers_in_scope(InFile::new(self.file_id, ast_id))1226                        {1227                            // FIXME: Multiple derives can have the same helper1228                            let name_ref = name_ref.as_name();1229                            for (macro_id, mut helpers) in1230                                helpers.iter().chunk_by(|(_, macro_id, ..)| macro_id).into_iter()1231                            {1232                                if let Some(idx) = helpers.position(|(name, ..)| *name == name_ref)1233                                {1234                                    return Some((1235                                        PathResolution::DeriveHelper(DeriveHelper {1236                                            derive: *macro_id,1237                                            idx: idx as u32,1238                                        }),1239                                        None,1240                                    ));1241                                }1242                            }1243                        }1244                    }1245                }1246            }1247            return match resolve_hir_path_as_attr_macro(db, &self.resolver, &hir_path) {1248                Some(m) => Some((PathResolution::Def(ModuleDef::Macro(m)), None)),1249                // this labels any path that starts with a tool module as the tool itself, this is technically wrong1250                // but there is no benefit in differentiating these two cases for the time being1251                None => path1252                    .first_segment()1253                    .and_then(|it| it.name_ref())1254                    .and_then(|name_ref| {1255                        ToolModule::by_name(db, self.resolver.krate().into(), &name_ref.text())1256                            .map(PathResolution::ToolModule)1257                    })1258                    .map(|it| (it, None)),1259            };1260        }1261        if parent().is_some_and(|it| ast::Visibility::can_cast(it.kind())) {1262            // No substitution because only modules can be inside visibilities, and those have no generics.1263            resolve_hir_path_qualifier(db, &self.resolver, &hir_path, &store).map(|it| (it, None))1264        } else {1265            // Probably a type, no need to show substitutions for those.1266            let res = resolve_hir_path_(1267                db,1268                &self.resolver,1269                &hir_path,1270                prefer_value_ns,1271                name_hygiene(db, InFile::new(self.file_id, path.syntax())),1272                Some(&store),1273                false,1274            )1275            .any()?;1276            let subst = (|| {1277                let parent = parent()?;1278                let ty = if let Some(expr) = ast::Expr::cast(parent.clone()) {1279                    let expr_id = self.expr_id(expr)?;1280                    self.infer()?.type_of_expr_or_pat(expr_id)?1281                } else if let Some(pat) = ast::Pat::cast(parent) {1282                    let pat_id = self.pat_id(&pat)?;1283                    self.infer()?.expr_or_pat_ty(pat_id)1284                } else {1285                    return None;1286                };1287                let env = self.trait_environment(db);1288                let (subst, expected_resolution) = match ty.kind() {1289                    TyKind::Adt(adt_def, subst) => {1290                        let adt_id = adt_def.def_id().0;1291                        (1292                            GenericSubstitution::new(adt_id.into(), subst, env),1293                            PathResolution::Def(ModuleDef::Adt(adt_id.into())),1294                        )1295                    }1296                    TyKind::Alias(AliasTy {1297                        kind: AliasTyKind::Projection { def_id },1298                        args,1299                        ..1300                    }) => {1301                        let assoc_id = def_id.expect_type_alias();1302                        (1303                            GenericSubstitution::new(assoc_id.into(), args, env),1304                            PathResolution::Def(ModuleDef::TypeAlias(assoc_id.into())),1305                        )1306                    }1307                    TyKind::FnDef(fn_id, subst) => {1308                        let generic_def_id = match fn_id.0 {1309                            CallableDefId::StructId(id) => id.into(),1310                            CallableDefId::FunctionId(id) => id.into(),1311                            CallableDefId::EnumVariantId(_) => return None,1312                        };1313                        (1314                            GenericSubstitution::new(generic_def_id, subst, env),1315                            PathResolution::Def(ModuleDefId::from(fn_id.0).into()),1316                        )1317                    }1318                    _ => return None,1319                };1320                if res != expected_resolution {1321                    // The user will not understand where we're coming from. This can happen (I think) with type aliases.1322                    return None;1323                }1324                Some(subst)1325            })();1326            Some((res, subst))1327        }1328    }13291330    pub(crate) fn resolve_hir_path_per_ns(1331        &self,1332        db: &dyn HirDatabase,1333        path: &ast::Path,1334    ) -> Option<PathResolutionPerNs> {1335        let mut collector = ExprCollector::body(db, self.resolver.module(), self.file_id);1336        let hir_path =1337            collector.lower_path(path.clone(), &mut ExprCollector::impl_trait_error_allocator)?;1338        let (store, _) = collector.store.finish();1339        Some(resolve_hir_path_(1340            db,1341            &self.resolver,1342            &hir_path,1343            false,1344            name_hygiene(db, InFile::new(self.file_id, path.syntax())),1345            Some(&store),1346            true,1347        ))1348    }13491350    pub(crate) fn record_literal_missing_fields(1351        &self,1352        db: &'db dyn HirDatabase,1353        literal: &ast::RecordExpr,1354    ) -> Option<Vec<(Field, Type<'db>)>> {1355        let body = self.store()?;1356        let infer = self.infer()?;13571358        let expr_id = self.expr_id(literal.clone().into())?.as_expr()?;1359        let substs = infer.expr_ty(expr_id).as_adt()?.1;1360        let (variant, missing_fields) =1361            record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;1362        let res = self.missing_fields(db, substs, variant, missing_fields);1363        Some(res)1364    }13651366    pub(crate) fn record_literal_matched_fields(1367        &self,1368        db: &'db dyn HirDatabase,1369        literal: &ast::RecordExpr,1370    ) -> Option<Vec<(Field, Type<'db>)>> {1371        let body = self.store()?;1372        let infer = self.infer()?;13731374        let expr_id = self.expr_id(literal.clone().into())?.as_expr()?;1375        let substs = infer.expr_ty(expr_id).as_adt()?.1;1376        let (variant, matched_fields) =1377            record_literal_matched_fields(db, infer, expr_id, &body[expr_id])?;13781379        let res = self.missing_fields(db, substs, variant, matched_fields);1380        Some(res)1381    }13821383    pub(crate) fn record_pattern_missing_fields(1384        &self,1385        db: &'db dyn HirDatabase,1386        pattern: &ast::RecordPat,1387    ) -> Option<Vec<(Field, Type<'db>)>> {1388        let body = self.store()?;1389        let infer = self.infer()?;13901391        let pat_id = self.pat_id(&pattern.clone().into())?.as_pat()?;1392        let substs = infer.pat_ty(pat_id).as_adt()?.1;13931394        let (variant, missing_fields) =1395            record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;1396        let res = self.missing_fields(db, substs, variant, missing_fields);1397        Some(res)1398    }13991400    pub(crate) fn record_pattern_matched_fields(1401        &self,1402        db: &'db dyn HirDatabase,1403        pattern: &ast::RecordPat,1404    ) -> Option<Vec<(Field, Type<'db>)>> {1405        let body = self.store()?;1406        let infer = self.infer()?;14071408        let pat_id = self.pat_id(&pattern.clone().into())?.as_pat()?;1409        let substs = infer.pat_ty(pat_id).as_adt()?.1;14101411        let (variant, matched_fields) =1412            record_pattern_matched_fields(db, infer, pat_id, &body[pat_id])?;1413        let res = self.missing_fields(db, substs, variant, matched_fields);1414        Some(res)1415    }14161417    fn missing_fields(1418        &self,1419        db: &'db dyn HirDatabase,1420        substs: GenericArgs<'db>,1421        variant: VariantId,1422        missing_fields: Vec<LocalFieldId>,1423    ) -> Vec<(Field, Type<'db>)> {1424        let interner = DbInterner::new_no_crate(db);1425        let field_types = db.field_types(variant);14261427        missing_fields1428            .into_iter()1429            .map(|local_id| {1430                let field = FieldId { parent: variant, local_id };1431                let ty = field_types[local_id].get().instantiate(interner, substs);1432                (field.into(), Type::new_with_resolver_inner(db, &self.resolver, ty))1433            })1434            .collect()1435    }14361437    pub(crate) fn resolve_variant(&self, record_lit: ast::RecordExpr) -> Option<VariantId> {1438        let infer = self.infer()?;1439        let expr_id = self.expr_id(record_lit.into())?;1440        infer.variant_resolution_for_expr_or_pat(expr_id)1441    }14421443    pub(crate) fn is_unsafe_macro_call_expr(1444        &self,1445        db: &'db dyn HirDatabase,1446        macro_expr: InFile<&ast::MacroExpr>,1447    ) -> bool {1448        if let Some((def, body, sm, Some(infer))) = self.def()1449            && let Some(expanded_expr) = sm.macro_expansion_expr(macro_expr)1450        {1451            let mut is_unsafe = false;1452            let mut walk_expr = |expr_id| {1453                unsafe_operations(db, infer, def, body, expr_id, &mut |_, inside_unsafe_block| {1454                    is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No1455                })1456            };1457            match expanded_expr {1458                ExprOrPatId::ExprId(expanded_expr) => walk_expr(expanded_expr),1459                ExprOrPatId::PatId(expanded_pat) => {1460                    body.walk_exprs_in_pat(expanded_pat, &mut walk_expr)1461                }1462            }1463            return is_unsafe;1464        }1465        false1466    }14671468    /// Returns the range of the implicit template argument and its resolution at the given `offset`1469    pub(crate) fn resolve_offset_in_format_args(1470        &self,1471        db: &'db dyn HirDatabase,1472        format_args: InFile<&ast::FormatArgsExpr>,1473        offset: TextSize,1474    ) -> Option<(TextRange, Option<PathResolution>)> {1475        let (hygiene, implicits) = self.store_sm()?.implicit_format_args(format_args)?;1476        implicits.iter().find(|(range, _)| range.contains_inclusive(offset)).map(|(range, name)| {1477            (1478                *range,1479                resolve_hir_value_path(1480                    db,1481                    &self.resolver,1482                    self.resolver.expression_store_owner(),1483                    &Path::from_known_path_with_no_generic(ModPath::from_segments(1484                        PathKind::Plain,1485                        Some(name.clone()),1486                    )),1487                    hygiene,1488                ),1489            )1490        })1491    }14921493    pub(crate) fn resolve_offset_in_asm_template(1494        &self,1495        asm: InFile<&ast::AsmExpr>,1496        line: usize,1497        offset: TextSize,1498    ) -> Option<(ExpressionStoreOwnerId, (ExprId, TextRange, usize))> {1499        let (def, _, sm, _) = self.def()?;1500        let (expr, args) = sm.asm_template_args(asm)?;1501        Some(def).zip(1502            args.get(line)?1503                .iter()1504                .find(|(range, _)| range.contains_inclusive(offset))1505                .map(|(range, idx)| (expr, *range, *idx)),1506        )1507    }15081509    pub(crate) fn as_format_args_parts<'a>(1510        &'a self,1511        db: &'a dyn HirDatabase,1512        format_args: InFile<&ast::FormatArgsExpr>,1513    ) -> Option<impl Iterator<Item = (TextRange, Option<PathResolution>)> + 'a> {1514        let (hygiene, names) = self.store_sm()?.implicit_format_args(format_args)?;1515        Some(names.iter().map(move |(range, name)| {1516            (1517                *range,1518                resolve_hir_value_path(1519                    db,1520                    &self.resolver,1521                    self.resolver.expression_store_owner(),1522                    &Path::from_known_path_with_no_generic(ModPath::from_segments(1523                        PathKind::Plain,1524                        Some(name.clone()),1525                    )),1526                    hygiene,1527                ),1528            )1529        }))1530    }15311532    pub(crate) fn as_asm_parts(1533        &self,1534        asm: InFile<&ast::AsmExpr>,1535    ) -> Option<(ExpressionStoreOwnerId, (ExprId, &[Vec<(TextRange, usize)>]))> {1536        let (def, _, sm, _) = self.def()?;1537        Some(def).zip(sm.asm_template_args(asm))1538    }15391540    fn resolve_impl_method_or_trait_def(1541        &self,1542        db: &'db dyn HirDatabase,1543        func: FunctionId,1544        substs: GenericArgs<'db>,1545    ) -> Function {1546        self.resolve_impl_method_or_trait_def_with_subst(db, func, substs).01547    }15481549    fn resolve_impl_method_or_trait_def_with_subst(1550        &self,1551        db: &'db dyn HirDatabase,1552        func: FunctionId,1553        substs: GenericArgs<'db>,1554    ) -> (Function, GenericArgs<'db>) {1555        let owner = match self.resolver.expression_store_owner() {1556            Some(it) => it,1557            None => return (func.into(), substs),1558        };1559        let env = self.param_and(db.trait_environment(owner));1560        let (func, args) = db.lookup_impl_method(env, func, substs);1561        match func {1562            Either::Left(func) => (func.into(), args),1563            Either::Right((impl_, method)) => {1564                (Function { id: AnyFunctionId::BuiltinDeriveImplMethod { method, impl_ } }, args)1565            }1566        }1567    }15681569    fn resolve_impl_const_or_trait_def_with_subst(1570        &self,1571        db: &'db dyn HirDatabase,1572        const_id: ConstId,1573        subs: GenericArgs<'db>,1574    ) -> (ConstId, GenericArgs<'db>) {1575        let owner = match self.resolver.expression_store_owner() {1576            Some(it) => it,1577            None => return (const_id, subs),1578        };1579        let env = self.param_and(db.trait_environment(owner));1580        let interner = DbInterner::new_with(db, env.krate);1581        let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis);1582        method_resolution::lookup_impl_const(&infcx, env.param_env, const_id, subs)1583    }15841585    fn lang_items<'a>(&self, db: &'a dyn HirDatabase) -> &'a LangItems {1586        hir_def::lang_item::lang_items(db, self.resolver.krate())1587    }15881589    fn lang_trait_fn(1590        &self,1591        db: &'db dyn HirDatabase,1592        lang_trait: Option<TraitId>,1593        method_name: &Name,1594    ) -> Option<(TraitId, FunctionId)> {1595        let trait_id = lang_trait?;1596        let fn_id = trait_id.trait_items(db).method_by_name(method_name)?;1597        Some((trait_id, fn_id))1598    }15991600    fn ty_of_expr(&self, expr: ast::Expr) -> Option<Ty<'db>> {1601        self.infer()?.type_of_expr_or_pat(self.expr_id(expr)?)1602    }1603}16041605fn scope_for(1606    db: &dyn HirDatabase,1607    scopes: &ExprScopes,1608    source_map: &ExpressionStoreSourceMap,1609    node: InFile<&SyntaxNode>,1610) -> Option<ScopeId> {1611    node.ancestors_with_macros(db)1612        .take_while(|it| {1613            let kind = it.kind();1614            !ast::Item::can_cast(kind)1615                || ast::MacroCall::can_cast(kind)1616                || ast::Use::can_cast(kind)1617                || ast::AsmExpr::can_cast(kind)1618        })1619        .filter_map(|it| it.map(ast::Expr::cast).transpose())1620        .filter_map(|it| source_map.node_expr(it.as_ref())?.as_expr())1621        .find_map(|it| scopes.scope_for(it))1622}16231624fn scope_for_offset(1625    db: &dyn HirDatabase,1626    scopes: &ExprScopes,1627    source_map: &ExpressionStoreSourceMap,1628    from_file: HirFileId,1629    offset: TextSize,1630) -> Option<ScopeId> {1631    scopes1632        .scope_by_expr()1633        .iter()1634        .filter_map(|(id, scope)| {1635            let InFile { file_id, value } = source_map.expr_syntax(id).ok()?;1636            if from_file == file_id {1637                return Some((value.text_range(), scope));1638            }16391640            // FIXME handle attribute expansion1641            let source = iter::successors(file_id.macro_file().map(|it| it.call_node(db)), |it| {1642                Some(it.file_id.macro_file()?.call_node(db))1643            })1644            .find(|it| it.file_id == from_file)1645            .filter(|it| it.kind() == SyntaxKind::MACRO_CALL)?;1646            Some((source.text_range(), scope))1647        })1648        .filter(|(expr_range, _scope)| expr_range.start() <= offset && offset <= expr_range.end())1649        // find containing scope1650        .min_by_key(|(expr_range, _scope)| expr_range.len())1651        .map(|(expr_range, scope)| {1652            adjust(db, scopes, source_map, expr_range, from_file, offset).unwrap_or(*scope)1653        })1654}16551656// XXX: during completion, cursor might be outside of any particular1657// expression. Try to figure out the correct scope...1658fn adjust(1659    db: &dyn HirDatabase,1660    scopes: &ExprScopes,1661    source_map: &ExpressionStoreSourceMap,1662    expr_range: TextRange,1663    from_file: HirFileId,1664    offset: TextSize,1665) -> Option<ScopeId> {1666    let child_scopes = scopes1667        .scope_by_expr()1668        .iter()1669        .filter_map(|(id, scope)| {1670            let source = source_map.expr_syntax(id).ok()?;1671            // FIXME: correctly handle macro expansion1672            if source.file_id != from_file {1673                return None;1674            }1675            let root = source.file_syntax(db);1676            let node = source.value.to_node(&root);1677            Some((node.syntax().text_range(), scope))1678        })1679        .filter(|&(range, _)| {1680            range.start() <= offset && expr_range.contains_range(range) && range != expr_range1681        });16821683    child_scopes1684        .max_by(|&(r1, _), &(r2, _)| {1685            if r1.contains_range(r2) {1686                std::cmp::Ordering::Greater1687            } else if r2.contains_range(r1) {1688                std::cmp::Ordering::Less1689            } else {1690                r1.start().cmp(&r2.start())1691            }1692        })1693        .map(|(_ptr, scope)| *scope)1694}16951696#[inline]1697pub(crate) fn resolve_hir_path(1698    db: &dyn HirDatabase,1699    resolver: &Resolver<'_>,1700    path: &Path,1701    hygiene: HygieneId,1702    store: Option<&ExpressionStore>,1703) -> Option<PathResolution> {1704    resolve_hir_path_(db, resolver, path, false, hygiene, store, false).any()1705}17061707#[inline]1708pub(crate) fn resolve_hir_path_as_attr_macro(1709    db: &dyn HirDatabase,1710    resolver: &Resolver<'_>,1711    path: &Path,1712) -> Option<Macro> {1713    resolver1714        .resolve_path_as_macro(db, path.mod_path()?, Some(MacroSubNs::Attr))1715        .map(|(it, _)| it)1716        .map(Into::into)1717}17181719fn resolve_hir_path_(1720    db: &dyn HirDatabase,1721    resolver: &Resolver<'_>,1722    path: &Path,1723    prefer_value_ns: bool,1724    hygiene: HygieneId,1725    store: Option<&ExpressionStore>,1726    resolve_per_ns: bool,1727) -> PathResolutionPerNs {1728    let types = || {1729        let (ty, unresolved) = match path.type_anchor() {1730            Some(type_ref) => resolver.generic_def().and_then(|def| {1731                let (_, res) =1732                    TyLoweringContext::new(db, resolver, store?, def, LifetimeElisionKind::Infer)1733                        .lower_ty_ext(type_ref);1734                res.map(|ty_ns| (ty_ns, path.segments().first()))1735            }),1736            None => {1737                let (ty, remaining_idx, _) = resolver.resolve_path_in_type_ns(db, path)?;1738                match remaining_idx {1739                    Some(remaining_idx) => {1740                        if remaining_idx + 1 == path.segments().len() {1741                            Some((ty, path.segments().last()))1742                        } else {1743                            None1744                        }1745                    }1746                    None => Some((ty, None)),1747                }1748            }1749        }?;17501751        // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type1752        // within the trait's associated types.1753        if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty)1754            && let Some(type_alias_id) =1755                trait_id.trait_items(db).associated_type_by_name(unresolved.name)1756        {1757            return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));1758        }17591760        let res = match ty {1761            TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),1762            TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()),1763            TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {1764                PathResolution::Def(Adt::from(it).into())1765            }1766            TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),1767            TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),1768            TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),1769            TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),1770            TypeNs::ModuleId(it) => PathResolution::Def(ModuleDef::Module(it.into())),1771        };1772        match unresolved {1773            Some(unresolved) => resolver1774                .generic_def()1775                .and_then(|def| {1776                    hir_ty::associated_type_shorthand_candidates(1777                        db,1778                        def,1779                        res.in_type_ns()?,1780                        |name, _| name == unresolved.name,1781                    )1782                })1783                .map(TypeAlias::from)1784                .map(Into::into)1785                .map(PathResolution::Def),1786            None => Some(res),1787        }1788    };17891790    let body_owner = resolver.expression_store_owner();1791    let values = || resolve_hir_value_path(db, resolver, body_owner, path, hygiene);17921793    let items = || {1794        resolver1795            .resolve_module_path_in_items(db, path.mod_path()?)1796            .take_types()1797            .map(|it| PathResolution::Def(it.into()))1798    };17991800    let macros = || {1801        resolver1802            .resolve_path_as_macro(db, path.mod_path()?, None)1803            .map(|(def, _)| PathResolution::Def(ModuleDef::Macro(def.into())))1804    };18051806    if resolve_per_ns {1807        PathResolutionPerNs {1808            type_ns: types().or_else(items),1809            value_ns: values(),1810            macro_ns: macros(),1811        }1812    } else {1813        let res = if prefer_value_ns {1814            values()1815                .map(|value_ns| PathResolutionPerNs::new(None, Some(value_ns), None))1816                .unwrap_or_else(|| PathResolutionPerNs::new(types(), None, None))1817        } else {1818            types()1819                .map(|type_ns| PathResolutionPerNs::new(Some(type_ns), None, None))1820                .unwrap_or_else(|| PathResolutionPerNs::new(None, values(), None))1821        };18221823        if res.any().is_some() {1824            res1825        } else if let Some(type_ns) = items() {1826            PathResolutionPerNs::new(Some(type_ns), None, None)1827        } else {1828            PathResolutionPerNs::new(None, None, macros())1829        }1830    }1831}18321833fn resolve_hir_value_path(1834    db: &dyn HirDatabase,1835    resolver: &Resolver<'_>,1836    store_owner: Option<ExpressionStoreOwnerId>,1837    path: &Path,1838    hygiene: HygieneId,1839) -> Option<PathResolution> {1840    resolver.resolve_path_in_value_ns_fully(db, path, hygiene).and_then(|val| {1841        let res = match val {1842            ValueNs::LocalBinding(binding_id) => {1843                let var = Local { parent: store_owner?, binding_id };1844                PathResolution::Local(var)1845            }1846            ValueNs::FunctionId(it) => PathResolution::Def(Function::from(it).into()),1847            ValueNs::ConstId(it) => PathResolution::Def(Const::from(it).into()),1848            ValueNs::StaticId(it) => PathResolution::Def(Static::from(it).into()),1849            ValueNs::StructId(it) => PathResolution::Def(Struct::from(it).into()),1850            ValueNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),1851            ValueNs::ImplSelf(impl_id) => PathResolution::SelfType(impl_id.into()),1852            ValueNs::GenericParam(id) => PathResolution::ConstParam(id.into()),1853        };1854        Some(res)1855    })1856}18571858/// Resolves a path where we know it is a qualifier of another path.1859///1860/// For example, if we have:1861/// ```1862/// mod my {1863///     pub mod foo {1864///         struct Bar;1865///     }1866///1867///     pub fn foo() {}1868/// }1869/// ```1870/// then we know that `foo` in `my::foo::Bar` refers to the module, not the function.1871fn resolve_hir_path_qualifier(1872    db: &dyn HirDatabase,1873    resolver: &Resolver<'_>,1874    path: &Path,1875    store: &ExpressionStore,1876) -> Option<PathResolution> {1877    (|| {1878        let (ty, unresolved) = match path.type_anchor() {1879            Some(type_ref) => resolver.generic_def().and_then(|def| {1880                let (_, res) =1881                    TyLoweringContext::new(db, resolver, store, def, LifetimeElisionKind::Infer)1882                        .lower_ty_ext(type_ref);1883                res.map(|ty_ns| (ty_ns, path.segments().first()))1884            }),1885            None => {1886                let (ty, remaining_idx, _) = resolver.resolve_path_in_type_ns(db, path)?;1887                match remaining_idx {1888                    Some(remaining_idx) => {1889                        if remaining_idx + 1 == path.segments().len() {1890                            Some((ty, path.segments().last()))1891                        } else {1892                            None1893                        }1894                    }1895                    None => Some((ty, None)),1896                }1897            }1898        }?;18991900        // If we are in a TypeNs for a Trait, and we have an unresolved name, try to resolve it as a type1901        // within the trait's associated types.1902        if let (Some(unresolved), &TypeNs::TraitId(trait_id)) = (&unresolved, &ty)1903            && let Some(type_alias_id) =1904                trait_id.trait_items(db).associated_type_by_name(unresolved.name)1905        {1906            return Some(PathResolution::Def(ModuleDefId::from(type_alias_id).into()));1907        }19081909        let res = match ty {1910            TypeNs::SelfType(it) => PathResolution::SelfType(it.into()),1911            TypeNs::GenericParam(id) => PathResolution::TypeParam(id.into()),1912            TypeNs::AdtSelfType(it) | TypeNs::AdtId(it) => {1913                PathResolution::Def(Adt::from(it).into())1914            }1915            TypeNs::EnumVariantId(it) => PathResolution::Def(EnumVariant::from(it).into()),1916            TypeNs::TypeAliasId(it) => PathResolution::Def(TypeAlias::from(it).into()),1917            TypeNs::BuiltinType(it) => PathResolution::Def(BuiltinType::from(it).into()),1918            TypeNs::TraitId(it) => PathResolution::Def(Trait::from(it).into()),1919            TypeNs::ModuleId(it) => PathResolution::Def(ModuleDef::Module(it.into())),1920        };1921        match unresolved {1922            Some(unresolved) => resolver1923                .generic_def()1924                .and_then(|def| {1925                    hir_ty::associated_type_shorthand_candidates(1926                        db,1927                        def,1928                        res.in_type_ns()?,1929                        |name, _| name == unresolved.name,1930                    )1931                })1932                .map(TypeAlias::from)1933                .map(Into::into)1934                .map(PathResolution::Def),1935            None => Some(res),1936        }1937    })()1938    .or_else(|| {1939        resolver1940            .resolve_module_path_in_items(db, path.mod_path()?)1941            .take_types()1942            .map(|it| PathResolution::Def(it.into()))1943    })1944}19451946pub(crate) fn name_hygiene(db: &dyn HirDatabase, name: InFile<&SyntaxNode>) -> HygieneId {1947    let Some(macro_file) = name.file_id.macro_file() else {1948        return HygieneId::ROOT;1949    };1950    let span_map = db.expansion_span_map(macro_file);1951    let ctx = span_map.span_at(name.value.text_range().start()).ctx;1952    HygieneId::new(ctx.opaque_and_semiopaque(db))1953}19541955fn record_literal_matched_fields(1956    db: &dyn HirDatabase,1957    infer: &InferenceResult,1958    id: ExprId,1959    expr: &Expr,1960) -> Option<(VariantId, Vec<LocalFieldId>)> {1961    let (fields, _spread) = match expr {1962        Expr::RecordLit { fields, spread, .. } => (fields, spread),1963        _ => return None,1964    };19651966    let variant_def = infer.variant_resolution_for_expr(id)?;1967    if let VariantId::UnionId(_) = variant_def {1968        return None;1969    }19701971    let variant_data = variant_def.fields(db);19721973    let specified_fields: FxHashSet<_> = fields.iter().map(|f| &f.name).collect();1974    // suggest fields if:1975    // - not in code1976    let matched_fields: Vec<LocalFieldId> = variant_data1977        .fields()1978        .iter()1979        .filter_map(|(f, d)| (!specified_fields.contains(&d.name)).then_some(f))1980        .collect();1981    if matched_fields.is_empty() {1982        return None;1983    }1984    Some((variant_def, matched_fields))1985}19861987fn record_pattern_matched_fields(1988    db: &dyn HirDatabase,1989    infer: &InferenceResult,1990    id: PatId,1991    pat: &Pat,1992) -> Option<(VariantId, Vec<LocalFieldId>)> {1993    let (fields, _ellipsis) = match pat {1994        Pat::Record { path: _, args, ellipsis } => (args, *ellipsis),1995        _ => return None,1996    };19971998    let variant_def = infer.variant_resolution_for_pat(id)?;1999    if let VariantId::UnionId(_) = variant_def {2000        return None;

Code quality findings 19

Critical: Use of 'unsafe' keyword bypasses Rust's safety guarantees. Requires careful auditing, clear justification (FFI, specific optimizations), and minimal scope.
error safety unsafe-block
let mut is_unsafe = false;
Critical: Use of 'unsafe' keyword bypasses Rust's safety guarantees. Requires careful auditing, clear justification (FFI, specific optimizations), and minimal scope.
error safety unsafe-block
is_unsafe |= inside_unsafe_block == InsideUnsafeBlock::No
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
if let Expr::Field { expr: object_expr, name: _ } = body[field_expr] {
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
ExprOrPatId::ExprId(idx) => match &store[idx] {
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
ExprOrPatId::PatId(idx) => match &store[idx] {
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
*container = Either::Right(field_types[field].get().instantiate(interner, subst));
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
record_literal_missing_fields(db, infer, expr_id, &body[expr_id])?;
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
record_literal_matched_fields(db, infer, expr_id, &body[expr_id])?;
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
record_pattern_missing_fields(db, infer, pat_id, &body[pat_id])?;
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
record_pattern_matched_fields(db, infer, pat_id, &body[pat_id])?;
Warning: Direct indexing (e.g., `vec[i]`, `slice[i]`) panics on out-of-bounds access. Prefer using `.get(index)` or `.get_mut(index)` which return Option<&T>/Option<&mut T>.
warning correctness unchecked-indexing
let ty = field_types[local_id].get().instantiate(interner, substs);
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
let into_future_type = items.into_iter().find_map(|item| match item {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match self.resolver.resolve_path_in_value_ns_fully(
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
let path = match expr_or_pat_id {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
ExprOrPatId::ExprId(idx) => match &store[idx] {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
ExprOrPatId::PatId(idx) => match &store[idx] {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
match res {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
let (fields, _spread) = match expr {
Info: Ensure 'match' statements are exhaustive. If matching on enums, consider adding a wildcard arm `_ => {}` only if necessary and intentional, as it suppresses warnings about unhandled variants.
info correctness match-wildcard
let (fields, _ellipsis) = match pat {

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.