diff --git a/Cargo.lock b/Cargo.lock index 5e39dfe87004..bef549f05140 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -801,15 +801,6 @@ dependencies = [ "foldhash 0.1.5", ] -[[package]] -name = "hashbrown" -version = "0.16.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" -dependencies = [ - "foldhash 0.2.0", -] - [[package]] name = "hashbrown" version = "0.17.1" @@ -823,11 +814,11 @@ dependencies = [ [[package]] name = "hashlink" -version = "0.11.0" +version = "0.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea0b22561a9c04a7cb1a302c013e0259cd3b4bb619f145b32f72b8b4bcbed230" +checksum = "a5081f264ed7adee96ea4b4778b6bb9da0a7228b084587aa3bd3ff05da7c5a3b" dependencies = [ - "hashbrown 0.16.1", + "hashbrown 0.17.1", ] [[package]] @@ -2578,8 +2569,6 @@ dependencies = [ [[package]] name = "salsa" version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adfc1e32b8d1a486e3a45a5480fb5dca7912f49262a8916a67378064da4fe1ab" dependencies = [ "boxcar", "crossbeam-queue", @@ -2604,14 +2593,10 @@ dependencies = [ [[package]] name = "salsa-macro-rules" version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "67dad477a3e3a484a7c2311c1d25160fb270214981be24022de7de8a206a3300" [[package]] name = "salsa-macros" version = "0.27.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "943f70e101fb3bd599960e79e719e70d85142730e5b45f3269246086ed218562" dependencies = [ "proc-macro2", "quote", diff --git a/Cargo.toml b/Cargo.toml index 37e5dbb44422..2e0cc9892c09 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,9 +44,9 @@ debug = 2 # ungrammar = { path = "lib/ungrammar" } -# salsa = { path = "../salsa" } -# salsa-macros = { path = "../salsa/components/salsa-macros" } -# salsa-macro-rules = { path = "../salsa/components/salsa-macro-rules" } +salsa = { path = "../salsa" } +salsa-macros = { path = "../salsa/components/salsa-macros" } +salsa-macro-rules = { path = "../salsa/components/salsa-macro-rules" } [workspace.dependencies] # local crates diff --git a/crates/hir-ty/src/autoderef.rs b/crates/hir-ty/src/autoderef.rs index a8ed4126abea..ac5dcbcbbc10 100644 --- a/crates/hir-ty/src/autoderef.rs +++ b/crates/hir-ty/src/autoderef.rs @@ -128,8 +128,8 @@ impl<'db> AutoderefCtx<'db> for DefaultAutoderefCtx<'_, 'db> { } } -pub(crate) struct InferenceContextAutoderefCtx<'a, 'b, 'db>(&'a mut InferenceContext<'b, 'db>); -impl<'db> AutoderefCtx<'db> for InferenceContextAutoderefCtx<'_, '_, 'db> { +pub(crate) struct InferenceContextAutoderefCtx<'a, 'db>(&'a mut InferenceContext<'db>); +impl<'db> AutoderefCtx<'db> for InferenceContextAutoderefCtx<'_, 'db> { #[inline] fn infcx(&self) -> &InferCtxt<'db> { &self.0.table.infer_ctxt @@ -160,8 +160,8 @@ pub(crate) struct GeneralAutoderef<'db, Ctx, Steps = Vec<(Ty<'db>, AutoderefKind pub(crate) type Autoderef<'a, 'db, Steps = Vec<(Ty<'db>, AutoderefKind)>> = GeneralAutoderef<'db, DefaultAutoderefCtx<'a, 'db>, Steps>; -pub(crate) type InferenceContextAutoderef<'a, 'b, 'db, Steps = Vec<(Ty<'db>, AutoderefKind)>> = - GeneralAutoderef<'db, InferenceContextAutoderefCtx<'a, 'b, 'db>, Steps>; +pub(crate) type InferenceContextAutoderef<'a, 'db, Steps = Vec<(Ty<'db>, AutoderefKind)>> = + GeneralAutoderef<'db, InferenceContextAutoderefCtx<'a, 'db>, Steps>; impl<'db, Ctx, Steps> Iterator for GeneralAutoderef<'db, Ctx, Steps> where @@ -239,10 +239,10 @@ impl<'a, 'db> Autoderef<'a, 'db> { } } -impl<'a, 'b, 'db> InferenceContextAutoderef<'a, 'b, 'db> { +impl<'a, 'db> InferenceContextAutoderef<'a, 'db> { #[inline] pub(crate) fn new_from_inference_context( - ctx: &'a mut InferenceContext<'b, 'db>, + ctx: &'a mut InferenceContext<'db>, base_ty: Ty<'db>, span: Span, ) -> Self { @@ -250,7 +250,7 @@ impl<'a, 'b, 'db> InferenceContextAutoderef<'a, 'b, 'db> { } #[inline] - pub(crate) fn ctx(&mut self) -> &mut InferenceContext<'b, 'db> { + pub(crate) fn ctx(&mut self) -> &mut InferenceContext<'db> { self.ctx.0 } } diff --git a/crates/hir-ty/src/consteval.rs b/crates/hir-ty/src/consteval.rs index d6580d3752f6..2413902de246 100644 --- a/crates/hir-ty/src/consteval.rs +++ b/crates/hir-ty/src/consteval.rs @@ -16,6 +16,7 @@ use rustc_abi::Size; use rustc_apfloat::Float; use rustc_ast_ir::Mutability; use rustc_type_ir::inherent::{Const as _, GenericArgs as _, IntoKind, Ty as _}; +use salsa::Update; use stdx::never; use crate::{ @@ -35,13 +36,13 @@ use crate::{ use super::mir::interpret_mir; -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum ConstEvalError { - MirLowerError(MirLowerError), - MirEvalError(MirEvalError), +#[derive(Debug, Clone, PartialEq, Eq, Update)] +pub enum ConstEvalError<'db> { + MirLowerError(MirLowerError<'db>), + MirEvalError(MirEvalError<'db>), } -impl ConstEvalError { +impl ConstEvalError<'_> { pub fn pretty_print( &self, f: &mut String, @@ -60,8 +61,8 @@ impl ConstEvalError { } } -impl From for ConstEvalError { - fn from(value: MirLowerError) -> Self { +impl<'db> From> for ConstEvalError<'db> { + fn from(value: MirLowerError<'db>) -> Self { match value { MirLowerError::ConstEvalError(_, e) => *e, _ => ConstEvalError::MirLowerError(value), @@ -69,8 +70,8 @@ impl From for ConstEvalError { } } -impl From for ConstEvalError { - fn from(value: MirEvalError) -> Self { +impl<'db> From> for ConstEvalError<'db> { + fn from(value: MirEvalError<'db>) -> Self { ConstEvalError::MirEvalError(value) } } @@ -405,10 +406,10 @@ pub(crate) fn create_anon_const<'a, 'db>( } } -pub(crate) fn const_eval_discriminant_variant( - db: &dyn HirDatabase, +pub(crate) fn const_eval_discriminant_variant<'db>( + db: &'db dyn HirDatabase, variant_id: EnumVariantId, -) -> Result { +) -> Result> { let interner = DbInterner::new_no_crate(db); let def = variant_id.into(); let body = Body::of(db, def); @@ -441,11 +442,11 @@ pub(crate) fn const_eval_discriminant_variant( Ok(c) } -pub(crate) fn const_eval_discriminant_cycle_result( - _: &dyn HirDatabase, +pub(crate) fn const_eval_discriminant_cycle_result<'db>( + _: &'db dyn HirDatabase, _: salsa::Id, _: EnumVariantId, -) -> Result { +) -> Result> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } @@ -454,58 +455,58 @@ pub(crate) fn const_eval<'db>( def: ConstId, subst: GenericArgs<'db>, trait_env: Option>, -) -> Result, ConstEvalError> { +) -> Result, ConstEvalError<'db>> { return match const_eval_query(db, def, subst.store(), trait_env.map(|env| env.store())) { Ok(konst) => Ok(konst.as_ref()), Err(err) => Err(err.clone()), }; #[salsa::tracked(returns(ref), cycle_result = const_eval_cycle_result)] - pub(crate) fn const_eval_query( - db: &dyn HirDatabase, + pub(crate) fn const_eval_query<'db>( + db: &'db dyn HirDatabase, def: ConstId, subst: StoredGenericArgs, trait_env: Option, - ) -> Result { + ) -> Result> { let body = db.monomorphized_mir_body( def.into(), subst, ParamEnvAndCrate { param_env: db.trait_environment(def.into()), krate: def.krate(db) } .store(), )?; - let c = interpret_mir(db, body, false, trait_env.as_ref().map(|env| env.as_ref()))?.0?; + let c = interpret_mir(db, body, false, trait_env.as_ref().map(|env| env.as_ref(db)))?.0?; Ok(c.store()) } - pub(crate) fn const_eval_cycle_result( - _: &dyn HirDatabase, + pub(crate) fn const_eval_cycle_result<'db>( + _: &'db dyn HirDatabase, _: salsa::Id, _: ConstId, _: StoredGenericArgs, _: Option, - ) -> Result { + ) -> Result> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } } pub(crate) fn anon_const_eval<'db>( db: &'db dyn HirDatabase, - def: AnonConstId, + def: AnonConstId<'db>, subst: GenericArgs<'db>, trait_env: Option>, -) -> Result, ConstEvalError> { +) -> Result, ConstEvalError<'db>> { return match anon_const_eval_query(db, def, subst.store(), trait_env.map(|env| env.store())) { Ok(konst) => Ok(konst.as_ref()), Err(err) => Err(err.clone()), }; #[salsa::tracked(returns(ref), cycle_result = anon_const_eval_cycle_result)] - pub(crate) fn anon_const_eval_query( - db: &dyn HirDatabase, - def: AnonConstId, + pub(crate) fn anon_const_eval_query<'db>( + db: &'db dyn HirDatabase, + def: AnonConstId<'db>, subst: StoredGenericArgs, trait_env: Option, - ) -> Result { + ) -> Result> { let body = db.monomorphized_mir_body( def.into(), subst, @@ -515,17 +516,17 @@ pub(crate) fn anon_const_eval<'db>( } .store(), )?; - let c = interpret_mir(db, body, false, trait_env.as_ref().map(|env| env.as_ref()))?.0?; + let c = interpret_mir(db, body, false, trait_env.as_ref().map(|env| env.as_ref(db)))?.0?; Ok(c.store()) } - pub(crate) fn anon_const_eval_cycle_result( - _: &dyn HirDatabase, + pub(crate) fn anon_const_eval_cycle_result<'db>( + _: &'db dyn HirDatabase, _: salsa::Id, - _: AnonConstId, + _: AnonConstId<'db>, _: StoredGenericArgs, _: Option, - ) -> Result { + ) -> Result> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } } @@ -533,17 +534,17 @@ pub(crate) fn anon_const_eval<'db>( pub(crate) fn const_eval_static<'db>( db: &'db dyn HirDatabase, def: StaticId, -) -> Result, ConstEvalError> { +) -> Result, ConstEvalError<'db>> { return match const_eval_static_query(db, def) { Ok(konst) => Ok(konst.as_ref()), Err(err) => Err(err.clone()), }; #[salsa::tracked(returns(ref), cycle_result = const_eval_static_cycle_result)] - pub(crate) fn const_eval_static_query( - db: &dyn HirDatabase, + pub(crate) fn const_eval_static_query<'db>( + db: &'db dyn HirDatabase, def: StaticId, - ) -> Result { + ) -> Result> { let interner = DbInterner::new_no_crate(db); let body = db.monomorphized_mir_body( def.into(), @@ -555,11 +556,11 @@ pub(crate) fn const_eval_static<'db>( Ok(c.store()) } - pub(crate) fn const_eval_static_cycle_result( - _: &dyn HirDatabase, + pub(crate) fn const_eval_static_cycle_result<'db>( + _: &'db dyn HirDatabase, _: salsa::Id, _: StaticId, - ) -> Result { + ) -> Result> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } } diff --git a/crates/hir-ty/src/consteval/tests.rs b/crates/hir-ty/src/consteval/tests.rs index 5421b97db238..fdb50389e2e2 100644 --- a/crates/hir-ty/src/consteval/tests.rs +++ b/crates/hir-ty/src/consteval/tests.rs @@ -26,7 +26,7 @@ use super::{ mod intrinsics; -fn simplify(e: ConstEvalError) -> ConstEvalError { +fn simplify(e: ConstEvalError<'_>) -> ConstEvalError<'_> { match e { ConstEvalError::MirEvalError(MirEvalError::InFunction(e, _)) => { simplify(ConstEvalError::MirEvalError(*e)) @@ -38,7 +38,7 @@ fn simplify(e: ConstEvalError) -> ConstEvalError { #[track_caller] fn check_fail( #[rust_analyzer::rust_fixture] ra_fixture: &str, - error: impl FnOnce(ConstEvalError) -> bool, + error: impl FnOnce(ConstEvalError<'_>) -> bool, ) { let (db, file_id) = TestDB::with_single_file(ra_fixture); crate::attach_db(&db, || match eval_goal(&db, file_id) { @@ -101,7 +101,7 @@ fn check_answer( }); } -fn pretty_print_err(e: ConstEvalError, db: &TestDB) -> String { +fn pretty_print_err(e: ConstEvalError<'_>, db: &TestDB) -> String { let mut err = String::new(); let span_formatter = |file, range| format!("{file:?} {range:?}"); let display_target = @@ -118,7 +118,7 @@ fn pretty_print_err(e: ConstEvalError, db: &TestDB) -> String { err } -fn eval_goal(db: &TestDB, file_id: EditionedFileId) -> Result, ConstEvalError> { +fn eval_goal(db: &TestDB, file_id: EditionedFileId) -> Result, ConstEvalError<'_>> { let _tracing = setup_tracing(); let interner = DbInterner::new_no_crate(db); let module_id = db.module_for_file(file_id.file_id(db)); diff --git a/crates/hir-ty/src/db.rs b/crates/hir-ty/src/db.rs index baf8bbd56fb1..bf92d88bb1ed 100644 --- a/crates/hir-ty/src/db.rs +++ b/crates/hir-ty/src/db.rs @@ -17,8 +17,8 @@ use hir_def::{ signatures::{ConstSignature, StaticSignature}, }; use la_arena::ArenaMap; +use salsa::Update; use span::Edition; -use stdx::impl_from; use triomphe::Arc; use crate::{ @@ -44,41 +44,50 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { // FXME: Collapse `mir_body_for_closure` into `mir_body` // and `monomorphized_mir_body_for_closure` into `monomorphized_mir_body` #[salsa::transparent] - fn mir_body(&self, def: InferBodyId) -> Result<&MirBody, MirLowerError> { + fn mir_body<'db>( + &'db self, + def: InferBodyId<'db>, + ) -> Result<&'db MirBody<'db>, MirLowerError<'db>> { crate::mir::mir_body_query(self, def).as_ref().map_err(|err| err.clone()) } #[salsa::transparent] - fn mir_body_for_closure(&self, def: InternedClosureId) -> Result<&MirBody, MirLowerError> { + fn mir_body_for_closure<'db>( + &'db self, + def: InternedClosureId<'db>, + ) -> Result<&'db MirBody<'db>, MirLowerError<'db>> { crate::mir::mir_body_for_closure_query(self, def).as_ref().map_err(|err| err.clone()) } #[salsa::transparent] - fn monomorphized_mir_body( - &self, - def: InferBodyId, + fn monomorphized_mir_body<'db>( + &'db self, + def: InferBodyId<'db>, subst: StoredGenericArgs, env: StoredParamEnvAndCrate, - ) -> Result<&MirBody, MirLowerError> { + ) -> Result<&'db MirBody<'db>, MirLowerError<'db>> { crate::mir::monomorphized_mir_body_query(self, def, subst, env) .as_ref() .map_err(|err| err.clone()) } #[salsa::transparent] - fn monomorphized_mir_body_for_closure( - &self, - def: InternedClosureId, + fn monomorphized_mir_body_for_closure<'db>( + &'db self, + def: InternedClosureId<'db>, subst: StoredGenericArgs, env: StoredParamEnvAndCrate, - ) -> Result<&MirBody, MirLowerError> { + ) -> Result<&'db MirBody<'db>, MirLowerError<'db>> { crate::mir::monomorphized_mir_body_for_closure_query(self, def, subst, env) .as_ref() .map_err(|err| err.clone()) } #[salsa::transparent] - fn borrowck(&self, def: InferBodyId) -> Result<&[BorrowckResult], MirLowerError> { + fn borrowck<'db>( + &'db self, + def: InferBodyId<'db>, + ) -> Result<&'db [BorrowckResult<'db>], MirLowerError<'db>> { crate::mir::borrowck_query(self, def).as_ref().map(|it| &**it).map_err(|err| err.clone()) } @@ -89,24 +98,30 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { def: ConstId, subst: GenericArgs<'db>, trait_env: Option>, - ) -> Result, ConstEvalError>; + ) -> Result, ConstEvalError<'db>>; #[salsa::invoke(crate::consteval::anon_const_eval)] #[salsa::transparent] fn anon_const_eval<'db>( &'db self, - def: AnonConstId, + def: AnonConstId<'db>, subst: GenericArgs<'db>, trait_env: Option>, - ) -> Result, ConstEvalError>; + ) -> Result, ConstEvalError<'db>>; #[salsa::invoke(crate::consteval::const_eval_static)] #[salsa::transparent] - fn const_eval_static<'db>(&'db self, def: StaticId) -> Result, ConstEvalError>; + fn const_eval_static<'db>( + &'db self, + def: StaticId, + ) -> Result, ConstEvalError<'db>>; #[salsa::invoke(crate::consteval::const_eval_discriminant_variant)] #[salsa::cycle(cycle_result = crate::consteval::const_eval_discriminant_cycle_result)] - fn const_eval_discriminant(&self, def: EnumVariantId) -> Result; + fn const_eval_discriminant<'db>( + &'db self, + def: EnumVariantId, + ) -> Result>; #[salsa::invoke(crate::method_resolution::lookup_impl_method_query)] #[salsa::transparent] @@ -150,10 +165,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::type_for_type_alias_with_diagnostics)] #[salsa::transparent] - fn type_for_type_alias_with_diagnostics( - &self, + fn type_for_type_alias_with_diagnostics<'db>( + &'db self, def: TypeAliasId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder>; /// Returns the type of the value of the given constant, or `None` if the `ValueTyDefId` is /// a `StructId` or `EnumVariantId` with a record constructor. @@ -167,10 +182,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::type_for_const_with_diagnostics)] #[salsa::transparent] - fn type_for_const_with_diagnostics( - &self, + fn type_for_const_with_diagnostics<'db>( + &'db self, def: ConstId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder>; #[salsa::invoke(crate::lower::type_for_static)] #[salsa::transparent] @@ -178,17 +193,17 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::type_for_static_with_diagnostics)] #[salsa::transparent] - fn type_for_static_with_diagnostics( - &self, + fn type_for_static_with_diagnostics<'db>( + &'db self, def: StaticId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder>; #[salsa::invoke(crate::lower::impl_self_ty_with_diagnostics)] #[salsa::transparent] - fn impl_self_ty_with_diagnostics( - &self, + fn impl_self_ty_with_diagnostics<'db>( + &'db self, def: ImplId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder>; #[salsa::invoke(crate::lower::impl_self_ty_query)] #[salsa::transparent] @@ -196,10 +211,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::const_param_types_with_diagnostics)] #[salsa::transparent] - fn const_param_types_with_diagnostics( - &self, + fn const_param_types_with_diagnostics<'db>( + &'db self, def: GenericDefId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, ArenaMap>; #[salsa::invoke(crate::lower::const_param_types)] #[salsa::transparent] @@ -211,10 +226,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::impl_trait_with_diagnostics)] #[salsa::transparent] - fn impl_trait_with_diagnostics( - &self, + fn impl_trait_with_diagnostics<'db>( + &'db self, def: ImplId, - ) -> &Option>>; + ) -> &'db Option>>; #[salsa::invoke(crate::lower::impl_trait_query)] #[salsa::transparent] @@ -222,10 +237,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::field_types_with_diagnostics)] #[salsa::transparent] - fn field_types_with_diagnostics( - &self, + fn field_types_with_diagnostics<'db>( + &'db self, var: VariantId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, ArenaMap>; #[salsa::invoke(crate::lower::field_types_query)] #[salsa::transparent] @@ -240,10 +255,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::callable_item_signature_with_diagnostics)] #[salsa::transparent] - fn callable_item_signature_with_diagnostics( - &self, + fn callable_item_signature_with_diagnostics<'db>( + &'db self, def: CallableDefId, - ) -> &TyLoweringResult>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder>; #[salsa::invoke(crate::lower::trait_environment)] #[salsa::transparent] @@ -251,10 +266,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::generic_defaults_with_diagnostics)] #[salsa::transparent] - fn generic_defaults_with_diagnostics( - &self, + fn generic_defaults_with_diagnostics<'db>( + &'db self, def: GenericDefId, - ) -> &TyLoweringResult; + ) -> &'db TyLoweringResult<'db, GenericDefaults>; /// This returns an empty list if no parameter has default. /// @@ -265,10 +280,10 @@ pub trait HirDatabase: DefDatabase + std::fmt::Debug { #[salsa::invoke(crate::lower::type_alias_bounds_with_diagnostics)] #[salsa::transparent] - fn type_alias_bounds_with_diagnostics( - &self, + fn type_alias_bounds_with_diagnostics<'db>( + &'db self, type_alias: TypeAliasId, - ) -> &TyLoweringResult>>; + ) -> &'db TyLoweringResult<'db, TypeAliasBounds>>; #[salsa::invoke(crate::lower::type_alias_bounds)] #[salsa::transparent] @@ -313,22 +328,22 @@ pub struct InternedOpaqueTyId { pub loc: ImplTraitId, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct InternedClosure { - pub owner: InferBodyId, +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Update)] +pub struct InternedClosure<'db> { + pub owner: InferBodyId<'db>, pub expr: ExprId, pub kind: ClosureKind, } -#[salsa_macros::interned(constructor = new_impl, no_lifetime, debug, revisions = usize::MAX)] +#[salsa_macros::interned(constructor = new_impl, debug, revisions = usize::MAX)] #[derive(PartialOrd, Ord)] -pub struct InternedClosureId { - pub loc: InternedClosure, +pub struct InternedClosureId<'db> { + pub loc: InternedClosure<'db>, } -impl InternedClosureId { +impl<'db> InternedClosureId<'db> { #[inline] - pub fn new(db: &dyn HirDatabase, loc: InternedClosure) -> Self { + pub fn new(db: &'db dyn HirDatabase, loc: InternedClosure<'db>) -> Self { if cfg!(debug_assertions) { let store = ExpressionStore::of(db, loc.owner.expression_store_owner(db)); let expr = &store[loc.expr]; @@ -348,15 +363,15 @@ impl InternedClosureId { } } -#[salsa_macros::interned(constructor = new_impl, no_lifetime, debug, revisions = usize::MAX)] +#[salsa_macros::interned(constructor = new_impl, debug, revisions = usize::MAX)] #[derive(PartialOrd, Ord)] -pub struct InternedCoroutineId { - pub loc: InternedClosure, +pub struct InternedCoroutineId<'db> { + pub loc: InternedClosure<'db>, } -impl InternedCoroutineId { +impl<'db> InternedCoroutineId<'db> { #[inline] - pub fn new(db: &dyn HirDatabase, loc: InternedClosure) -> Self { + pub fn new(db: &'db dyn HirDatabase, loc: InternedClosure<'db>) -> Self { if cfg!(debug_assertions) { let store = ExpressionStore::of(db, loc.owner.expression_store_owner(db)); let expr = &store[loc.expr]; @@ -377,15 +392,15 @@ impl InternedCoroutineId { } } -#[salsa_macros::interned(constructor = new_impl, no_lifetime, debug, revisions = usize::MAX)] +#[salsa_macros::interned(constructor = new_impl, debug, revisions = usize::MAX)] #[derive(PartialOrd, Ord)] -pub struct InternedCoroutineClosureId { - pub loc: InternedClosure, +pub struct InternedCoroutineClosureId<'db> { + pub loc: InternedClosure<'db>, } -impl InternedCoroutineClosureId { +impl<'db> InternedCoroutineClosureId<'db> { #[inline] - pub fn new(db: &dyn HirDatabase, loc: InternedClosure) -> Self { + pub fn new(db: &'db dyn HirDatabase, loc: InternedClosure<'db>) -> Self { if cfg!(debug_assertions) { let store = ExpressionStore::of(db, loc.owner.expression_store_owner(db)); let expr = &store[loc.expr]; @@ -421,37 +436,41 @@ pub struct AnonConstLoc { pub(crate) allow_using_generic_params: bool, } -#[salsa_macros::interned(debug, no_lifetime, revisions = usize::MAX, constructor = new_)] +#[salsa_macros::interned(debug, revisions = usize::MAX, constructor = new_)] #[derive(PartialOrd, Ord)] pub struct AnonConstId { #[returns(ref)] pub loc: AnonConstLoc, } -impl AnonConstId { - pub(crate) fn new(db: &dyn DefDatabase, loc: AnonConstLoc, token: TrackedStructToken) -> Self { +impl<'db> AnonConstId<'db> { + pub(crate) fn new( + db: &'db dyn DefDatabase, + loc: AnonConstLoc, + token: TrackedStructToken, + ) -> Self { _ = token; AnonConstId::new_(db, loc) } } -impl HasModule for AnonConstId { +impl HasModule for AnonConstId<'_> { fn module(&self, db: &dyn DefDatabase) -> ModuleId { self.loc(db).owner.module(db) } } -impl HasResolver for AnonConstId { +impl HasResolver for AnonConstId<'_> { fn resolver(self, db: &dyn DefDatabase) -> Resolver<'_> { self.loc(db).owner.resolver(db) } } -impl AnonConstId { +impl<'db> AnonConstId<'db> { pub fn all_from_signature( - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, def: GenericDefId, - ) -> ArrayVec<&[AnonConstId], 5> { + ) -> ArrayVec<&'db [Self], 5> { let mut result = ArrayVec::new(); // Queries common to all generic defs: @@ -488,16 +507,30 @@ impl AnonConstId { /// A constant, which might appears as a const item, an anonymous const block in expressions /// or patterns, or as a constant in types with const generics. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa_macros::Supertype)] -pub enum GeneralConstId { +pub enum GeneralConstId<'db> { ConstId(ConstId), StaticId(StaticId), - AnonConstId(AnonConstId), + AnonConstId(AnonConstId<'db>), } -impl_from!(ConstId, StaticId, AnonConstId for GeneralConstId); +impl<'db> From for GeneralConstId<'db> { + fn from(it: ConstId) -> GeneralConstId<'db> { + GeneralConstId::ConstId(it) + } +} +impl<'db> From for GeneralConstId<'db> { + fn from(it: StaticId) -> GeneralConstId<'db> { + GeneralConstId::StaticId(it) + } +} +impl<'db> From> for GeneralConstId<'db> { + fn from(it: AnonConstId<'db>) -> GeneralConstId<'db> { + GeneralConstId::AnonConstId(it) + } +} -impl GeneralConstId { - pub fn generic_def(self, db: &dyn HirDatabase) -> Option { +impl<'db> GeneralConstId<'db> { + pub fn generic_def(self, db: &'db dyn HirDatabase) -> Option { match self { GeneralConstId::ConstId(it) => Some(it.into()), GeneralConstId::StaticId(it) => Some(it.into()), @@ -505,7 +538,7 @@ impl GeneralConstId { } } - pub fn name(self, db: &dyn DefDatabase) -> String { + pub fn name(self, db: &'db dyn DefDatabase) -> String { match self { GeneralConstId::StaticId(it) => { StaticSignature::of(db, it).name.display(db, Edition::CURRENT).to_string() diff --git a/crates/hir-ty/src/diagnostics/expr.rs b/crates/hir-ty/src/diagnostics/expr.rs index be4de11ceb36..ea8d5e959a68 100644 --- a/crates/hir-ty/src/diagnostics/expr.rs +++ b/crates/hir-ty/src/diagnostics/expr.rs @@ -104,7 +104,7 @@ impl<'db> BodyValidationDiagnostic<'db> { struct ExprValidator<'db> { owner: DefWithBodyId, body: &'db Body, - infer: &'db InferenceResult, + infer: &'db InferenceResult<'db>, env: ParamEnv<'db>, diagnostics: Vec>, validate_lints: bool, @@ -598,9 +598,9 @@ impl<'db> FilterMapNextChecker<'db> { } } -pub fn record_literal_missing_fields( - db: &dyn HirDatabase, - infer: &InferenceResult, +pub fn record_literal_missing_fields<'db>( + db: &'db dyn HirDatabase, + infer: &InferenceResult<'db>, id: ExprId, expr: &Expr, ) -> Option<(VariantId, Vec)> { @@ -641,9 +641,9 @@ pub fn record_literal_missing_fields( Some((variant_def, missed_fields)) } -pub fn record_pattern_missing_fields( - db: &dyn HirDatabase, - infer: &InferenceResult, +pub fn record_pattern_missing_fields<'db>( + db: &'db dyn HirDatabase, + infer: &InferenceResult<'db>, id: PatId, pat: &Pat, ) -> Option<(VariantId, Vec)> { @@ -678,8 +678,8 @@ pub fn record_pattern_missing_fields( Some((variant_def, missed_fields)) } -fn types_of_subpatterns_do_match(pat: PatId, body: &Body, infer: &InferenceResult) -> bool { - fn walk(pat: PatId, body: &Body, infer: &InferenceResult, has_type_mismatches: &mut bool) { +fn types_of_subpatterns_do_match(pat: PatId, body: &Body, infer: &InferenceResult<'_>) -> bool { + fn walk(pat: PatId, body: &Body, infer: &InferenceResult<'_>, has_type_mismatches: &mut bool) { match infer.pat_has_type_mismatch(pat) { true => *has_type_mismatches = true, false if *has_type_mismatches => (), diff --git a/crates/hir-ty/src/diagnostics/match_check.rs b/crates/hir-ty/src/diagnostics/match_check.rs index 14bff6522070..613912e0901b 100644 --- a/crates/hir-ty/src/diagnostics/match_check.rs +++ b/crates/hir-ty/src/diagnostics/match_check.rs @@ -97,7 +97,7 @@ pub(crate) enum PatKind<'db> { pub(crate) struct PatCtxt<'a, 'db> { db: &'db dyn HirDatabase, - infer: &'db InferenceResult, + infer: &'db InferenceResult<'db>, body: &'a Body, pub(crate) errors: Vec, } @@ -105,7 +105,7 @@ pub(crate) struct PatCtxt<'a, 'db> { impl<'a, 'db> PatCtxt<'a, 'db> { pub(crate) fn new( db: &'db dyn HirDatabase, - infer: &'db InferenceResult, + infer: &'db InferenceResult<'db>, body: &'a Body, ) -> Self { Self { db, infer, body, errors: Vec::new() } diff --git a/crates/hir-ty/src/diagnostics/unsafe_check.rs b/crates/hir-ty/src/diagnostics/unsafe_check.rs index 3c69c6a44b12..d9e5f9ad0816 100644 --- a/crates/hir-ty/src/diagnostics/unsafe_check.rs +++ b/crates/hir-ty/src/diagnostics/unsafe_check.rs @@ -100,7 +100,7 @@ enum UnsafeDiagnostic { pub fn unsafe_operations_for_body( db: &dyn HirDatabase, - infer: &InferenceResult, + infer: &InferenceResult<'_>, def: DefWithBodyId, body: &Body, callback: &mut dyn FnMut(ExprOrPatId), @@ -119,7 +119,7 @@ pub fn unsafe_operations_for_body( pub fn unsafe_operations( db: &dyn HirDatabase, - infer: &InferenceResult, + infer: &InferenceResult<'_>, def: ExpressionStoreOwnerId, body: &ExpressionStore, current: ExprId, @@ -137,7 +137,7 @@ pub fn unsafe_operations( struct UnsafeVisitor<'db> { db: &'db dyn HirDatabase, - infer: &'db InferenceResult, + infer: &'db InferenceResult<'db>, body: &'db ExpressionStore, resolver: Resolver<'db>, def: ExpressionStoreOwnerId, @@ -156,7 +156,7 @@ struct UnsafeVisitor<'db> { impl<'db> UnsafeVisitor<'db> { fn new( db: &'db dyn HirDatabase, - infer: &'db InferenceResult, + infer: &'db InferenceResult<'db>, body: &'db ExpressionStore, def: ExpressionStoreOwnerId, unsafe_expr_cb: &'db mut dyn FnMut(UnsafeDiagnostic), diff --git a/crates/hir-ty/src/infer.rs b/crates/hir-ty/src/infer.rs index 616701f80c43..e84b408fc1ee 100644 --- a/crates/hir-ty/src/infer.rs +++ b/crates/hir-ty/src/infer.rs @@ -63,6 +63,7 @@ use rustc_type_ir::{ AliasTyKind, TypeFoldable, TypeVisitableExt, inherent::{GenericArgs as _, IntoKind, Ty as _}, }; +use salsa::Update; use smallvec::SmallVec; use span::Edition; use stdx::never; @@ -116,7 +117,7 @@ pub use unify::{could_unify, could_unify_deeply}; use cast::{CastCheck, CastError}; /// The entry point of type inference. -fn infer_query(db: &dyn HirDatabase, def: DefWithBodyId) -> InferenceResult { +fn infer_query<'db>(db: &'db dyn HirDatabase, def: DefWithBodyId) -> InferenceResult<'db> { infer_query_with_inspect(db, def, None, LoweringMode::Analysis) } @@ -125,7 +126,7 @@ pub fn infer_query_with_inspect<'db>( def: DefWithBodyId, inspect: Option>, lowering_mode: LoweringMode, -) -> InferenceResult { +) -> InferenceResult<'db> { let _p = tracing::info_span!("infer_query").entered(); let resolver = def.resolver(db); let body = Body::of(db, def); @@ -181,7 +182,11 @@ pub fn infer_query_with_inspect<'db>( infer_finalize(ctx) } -fn infer_cycle_result(db: &dyn HirDatabase, _: salsa::Id, _: DefWithBodyId) -> InferenceResult { +fn infer_cycle_result<'db>( + db: &'db dyn HirDatabase, + _: salsa::Id, + _: DefWithBodyId, +) -> InferenceResult<'db> { InferenceResult { has_errors: true, ..InferenceResult::new(Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed)) @@ -189,7 +194,10 @@ fn infer_cycle_result(db: &dyn HirDatabase, _: salsa::Id, _: DefWithBodyId) -> I } /// Infer types for an anonymous const expression. -fn infer_anon_const_query(db: &dyn HirDatabase, def: AnonConstId) -> InferenceResult { +fn infer_anon_const_query<'db>( + db: &'db dyn HirDatabase, + def: AnonConstId<'db>, +) -> InferenceResult<'db> { let _p = tracing::info_span!("infer_anon_const_query").entered(); let loc = def.loc(db); let store_owner = loc.owner; @@ -217,18 +225,18 @@ fn infer_anon_const_query(db: &dyn HirDatabase, def: AnonConstId) -> InferenceRe infer_finalize(ctx) } -fn infer_anon_const_cycle_result( - db: &dyn HirDatabase, +fn infer_anon_const_cycle_result<'db>( + db: &'db dyn HirDatabase, _: salsa::Id, - _: AnonConstId, -) -> InferenceResult { + _: AnonConstId<'db>, +) -> InferenceResult<'db> { InferenceResult { has_errors: true, ..InferenceResult::new(Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed)) } } -fn infer_finalize(mut ctx: InferenceContext<'_, '_>) -> InferenceResult { +fn infer_finalize<'db>(mut ctx: InferenceContext<'db>) -> InferenceResult<'db> { ctx.handle_opaque_type_uses(); ctx.type_inference_fallback(); @@ -704,8 +712,8 @@ pub enum PatAdjust { /// When you add a field that stores types (including `Substitution` and the like), don't forget /// `resolve_completely()`'ing them in `InferenceContext::resolve_all()`. Inference variables must /// not appear in the final inference result. -#[derive(Clone, PartialEq, Eq, Debug)] -pub struct InferenceResult { +#[derive(Clone, PartialEq, Eq, Debug, Update)] +pub struct InferenceResult<'db> { /// For each method call expr, records the function it resolves to. method_resolutions: FxHashMap, /// For each field access expr, records the field it resolves to. @@ -769,7 +777,7 @@ pub struct InferenceResult { pub closures_data: FxHashMap, - defined_anon_consts: ThinVec, + defined_anon_consts: ThinVec>, } #[derive(Clone, PartialEq, Eq, Debug, Default)] @@ -990,24 +998,32 @@ pub enum UpvarCapture { } #[salsa::tracked] -impl InferenceResult { +impl<'db> InferenceResult<'db> { #[salsa::tracked(returns(ref), cycle_result = infer_cycle_result)] - fn for_body(db: &dyn HirDatabase, def: DefWithBodyId) -> InferenceResult { + fn for_body(db: &dyn HirDatabase, def: DefWithBodyId) -> InferenceResult<'_> { infer_query(db, def) } +} +#[salsa::tracked] +impl<'db> InferenceResult<'db> { /// Infer types for all const expressions in an item's signature. /// /// Returns an `InferenceResult` containing type information for array lengths, /// const generic arguments, and other const expressions appearing in type /// positions within the item's signature. #[salsa::tracked(returns(ref), cycle_result = infer_anon_const_cycle_result)] - fn for_anon_const(db: &dyn HirDatabase, def: AnonConstId) -> InferenceResult { + fn for_anon_const(db: &'db dyn HirDatabase, def: AnonConstId<'db>) -> InferenceResult<'db> { infer_anon_const_query(db, def) } +} +impl<'db> InferenceResult<'db> { #[inline] - pub fn of(db: &dyn HirDatabase, def: impl Into) -> &InferenceResult { + pub fn of( + db: &'db dyn HirDatabase, + def: impl Into>, + ) -> &'db InferenceResult<'db> { match def.into() { InferBodyId::DefWithBodyId(it) => InferenceResult::for_body(db, it), InferBodyId::AnonConstId(it) => InferenceResult::for_anon_const(db, it), @@ -1015,7 +1031,7 @@ impl InferenceResult { } } -impl InferenceResult { +impl<'db> InferenceResult<'db> { fn new(error_ty: Ty<'_>) -> Self { Self { method_resolutions: Default::default(), @@ -1042,7 +1058,7 @@ impl InferenceResult { } } - pub fn method_resolution<'db>(&self, expr: ExprId) -> Option<(FunctionId, GenericArgs<'db>)> { + pub fn method_resolution(&self, expr: ExprId) -> Option<(FunctionId, GenericArgs<'db>)> { self.method_resolutions.get(&expr).map(|(func, args)| (*func, args.as_ref())) } pub fn field_resolution(&self, expr: ExprId) -> Option> { @@ -1060,22 +1076,22 @@ impl InferenceResult { ExprOrPatId::PatId(id) => self.variant_resolution_for_pat(id), } } - pub fn assoc_resolutions_for_expr<'db>( + pub fn assoc_resolutions_for_expr<'a>( &self, id: ExprId, - ) -> Option<(CandidateId, GenericArgs<'db>)> { + ) -> Option<(CandidateId, GenericArgs<'a>)> { self.assoc_resolutions.get(&id.into()).map(|(assoc, args)| (*assoc, args.as_ref())) } - pub fn assoc_resolutions_for_pat<'db>( + pub fn assoc_resolutions_for_pat<'a>( &self, id: PatId, - ) -> Option<(CandidateId, GenericArgs<'db>)> { + ) -> Option<(CandidateId, GenericArgs<'a>)> { self.assoc_resolutions.get(&id.into()).map(|(assoc, args)| (*assoc, args.as_ref())) } - pub fn assoc_resolutions_for_expr_or_pat<'db>( + pub fn assoc_resolutions_for_expr_or_pat<'a>( &self, id: ExprOrPatId, - ) -> Option<(CandidateId, GenericArgs<'db>)> { + ) -> Option<(CandidateId, GenericArgs<'a>)> { match id { ExprOrPatId::ExprId(id) => self.assoc_resolutions_for_expr(id), ExprOrPatId::PatId(id) => self.assoc_resolutions_for_pat(id), @@ -1098,19 +1114,19 @@ impl InferenceResult { pub fn has_type_mismatches(&self) -> bool { self.nodes_with_type_mismatches.is_some() } - pub fn placeholder_types<'db>(&self) -> impl Iterator)> { + pub fn placeholder_types<'a>(&self) -> impl Iterator)> { self.type_of_type_placeholder.iter().map(|(&type_ref, ty)| (type_ref, ty.as_ref())) } - pub fn type_of_type_placeholder<'db>(&self, type_ref: TypeRefId) -> Option> { + pub fn type_of_type_placeholder<'a>(&self, type_ref: TypeRefId) -> Option> { self.type_of_type_placeholder.get(&type_ref).map(|ty| ty.as_ref()) } - pub fn type_of_expr_or_pat<'db>(&self, id: ExprOrPatId) -> Option> { + pub fn type_of_expr_or_pat<'a>(&self, id: ExprOrPatId) -> Option> { match id { ExprOrPatId::ExprId(id) => self.type_of_expr.get(id).map(|it| it.as_ref()), ExprOrPatId::PatId(id) => self.type_of_pat.get(id).map(|it| it.as_ref()), } } - pub fn type_of_expr_with_adjust<'db>(&self, id: ExprId) -> Option> { + pub fn type_of_expr_with_adjust<'a>(&self, id: ExprId) -> Option> { match self.expr_adjustments.get(&id).and_then(|adjustments| { adjustments.iter().rfind(|adj| { // https://github.com/rust-lang/rust/blob/67819923ac8ea353aaa775303f4c3aacbf41d010/compiler/rustc_mir_build/src/thir/cx/expr.rs#L140 @@ -1127,7 +1143,7 @@ impl InferenceResult { None => self.type_of_expr.get(id).map(|it| it.as_ref()), } } - pub fn type_of_pat_with_adjust<'db>(&self, id: PatId) -> Ty<'db> { + pub fn type_of_pat_with_adjust<'a>(&self, id: PatId) -> Ty<'a> { match self.pat_adjustments.get(&id).and_then(|adjustments| adjustments.last()) { Some(adjusted) => adjusted.source.as_ref(), None => self.pat_ty(id), @@ -1141,7 +1157,7 @@ impl InferenceResult { &self.diagnostics } - pub fn tuple_field_access_type<'db>(&self, id: TupleId) -> Tys<'db> { + pub fn tuple_field_access_type<'a>(&self, id: TupleId) -> Tys<'a> { self.tuple_field_access_types[id.0 as usize].as_ref() } @@ -1158,25 +1174,25 @@ impl InferenceResult { } // This method is consumed by external tools to run rust-analyzer as a library. Don't remove, please. - pub fn expression_types<'db>(&self) -> impl Iterator)> { + pub fn expression_types<'a>(&self) -> impl Iterator)> { self.type_of_expr.iter().map(|(k, v)| (k, v.as_ref())) } // This method is consumed by external tools to run rust-analyzer as a library. Don't remove, please. - pub fn pattern_types<'db>(&self) -> impl Iterator)> { + pub fn pattern_types<'a>(&self) -> impl Iterator)> { self.type_of_pat.iter().map(|(k, v)| (k, v.as_ref())) } // This method is consumed by external tools to run rust-analyzer as a library. Don't remove, please. - pub fn binding_types<'db>(&self) -> impl Iterator)> { + pub fn binding_types<'a>(&self) -> impl Iterator)> { self.type_of_binding.iter().map(|(k, v)| (k, v.as_ref())) } // This method is consumed by external tools to run rust-analyzer as a library. Don't remove, please. - pub fn return_position_impl_trait_types<'db>( - &'db self, - db: &'db dyn HirDatabase, - ) -> impl Iterator)> { + pub fn return_position_impl_trait_types<'a>( + &'a self, + db: &'a dyn HirDatabase, + ) -> impl Iterator)> { self.type_of_opaque.iter().filter_map(move |(&id, ty)| { let ImplTraitId::ReturnTypeImplTrait(_, rpit_idx) = id.loc(db) else { return None; @@ -1185,24 +1201,24 @@ impl InferenceResult { }) } - pub fn expr_ty<'db>(&self, id: ExprId) -> Ty<'db> { + pub fn expr_ty<'a>(&self, id: ExprId) -> Ty<'a> { self.type_of_expr.get(id).map_or(self.error_ty.as_ref(), |it| it.as_ref()) } - pub fn pat_ty<'db>(&self, id: PatId) -> Ty<'db> { + pub fn pat_ty<'a>(&self, id: PatId) -> Ty<'a> { self.type_of_pat.get(id).map_or(self.error_ty.as_ref(), |it| it.as_ref()) } - pub fn expr_or_pat_ty<'db>(&self, id: ExprOrPatId) -> Ty<'db> { + pub fn expr_or_pat_ty<'a>(&self, id: ExprOrPatId) -> Ty<'a> { self.type_of_expr_or_pat(id).unwrap_or(self.error_ty.as_ref()) } - pub fn binding_ty<'db>(&self, id: BindingId) -> Ty<'db> { + pub fn binding_ty<'a>(&self, id: BindingId) -> Ty<'a> { self.type_of_binding.get(id).map_or(self.error_ty.as_ref(), |it| it.as_ref()) } /// This does not deduplicate, which means you'll get the types once per capture. - pub fn closure_captures_tys<'db>(&self, closure: ExprId) -> impl Iterator> { + pub fn closure_captures_tys<'a>(&self, closure: ExprId) -> impl Iterator> { self.closures_data[&closure] .min_captures .values() @@ -1210,11 +1226,11 @@ impl InferenceResult { } /// Like [`Self::closure_captures_tys()`], but using [`CapturedPlace::captured_ty()`]. - pub fn closure_captures_captured_tys<'db>( + pub fn closure_captures_captured_tys<'a>( &self, - db: &'db dyn HirDatabase, + db: &'a dyn HirDatabase, closure: ExprId, - ) -> impl Iterator> { + ) -> impl Iterator> { self.closures_data[&closure] .min_captures .values() @@ -1234,12 +1250,12 @@ enum DerefPatBorrowMode { /// The inference context contains all information needed during type inference. #[derive(Debug)] -pub(crate) struct InferenceContext<'body, 'db> { +pub(crate) struct InferenceContext<'db> { pub(crate) db: &'db dyn HirDatabase, - pub(crate) owner: InferBodyId, + pub(crate) owner: InferBodyId<'db>, pub(crate) store_owner: ExpressionStoreOwnerId, pub(crate) generic_def: GenericDefId, - pub(crate) store: &'body ExpressionStore, + pub(crate) store: &'db ExpressionStore, pub(crate) lowering_mode: LoweringMode, /// Generally you should not resolve things via this resolver. Instead create a TyLoweringContext /// and resolve the path via its methods. This will ensure proper error reporting. @@ -1254,7 +1270,7 @@ pub(crate) struct InferenceContext<'body, 'db> { pub(crate) features: &'db UnstableFeatures, /// The traits in scope, disregarding block modules. This is used for caching purposes. traits_in_scope: FxHashSet, - pub(crate) result: InferenceResult, + pub(crate) result: InferenceResult<'db>, tuple_field_accesses_rev: IndexSet, std::hash::BuildHasherDefault>, /// The return type of the function being inferred, the closure or async block if we're @@ -1284,7 +1300,7 @@ pub(crate) struct InferenceContext<'body, 'db> { diagnostics: Diagnostics, vars_emitted_type_must_be_known_for: FxHashSet>, - defined_anon_consts: RefCell>, + defined_anon_consts: RefCell>>, } #[derive(Clone, Debug)] @@ -1331,13 +1347,13 @@ fn find_continuable<'a, 'db>( } } -impl<'body, 'db> InferenceContext<'body, 'db> { +impl<'db> InferenceContext<'db> { fn new( db: &'db dyn HirDatabase, - owner: InferBodyId, + owner: InferBodyId<'db>, store_owner: ExpressionStoreOwnerId, generic_def: GenericDefId, - store: &'body ExpressionStore, + store: &'db ExpressionStore, resolver: Resolver<'db>, allow_using_generic_params: bool, lowering_mode: LoweringMode, @@ -1379,7 +1395,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { } } - fn merge(&mut self, other: &InferenceResult) { + fn merge(&mut self, other: &InferenceResult<'db>) { let InferenceResult { method_resolutions, field_resolutions, @@ -1534,7 +1550,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { // `InferenceResult` in the middle of inference. See the fixme comment in `consteval::eval_to_const`. If you // used this function for another workaround, mention it here. If you really need this function and believe that // there is no problem in it being `pub(crate)`, remove this comment. - fn resolve_all(self) -> InferenceResult { + fn resolve_all(self) -> InferenceResult<'db> { let InferenceContext { table, mut result, @@ -1667,7 +1683,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { result } - fn collect_const(&mut self, id: ConstId, data: &ConstSignature) { + fn collect_const(&mut self, id: ConstId, data: &'db ConstSignature) { let return_ty = self.make_ty( data.type_ref, &data.store, @@ -1679,7 +1695,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { self.return_ty = return_ty; } - fn collect_static(&mut self, id: StaticId, data: &StaticSignature) { + fn collect_static(&mut self, id: StaticId, data: &'db StaticSignature) { let return_ty = self.make_ty( data.type_ref, &data.store, @@ -1883,7 +1899,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { fn with_ty_lowering( &mut self, - store: &ExpressionStore, + store: &'db ExpressionStore, types_source: InferenceTyDiagnosticSource, store_owner: ExpressionStoreOwnerId, lifetime_elision: LifetimeElisionKind<'db>, @@ -1929,7 +1945,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { fn make_ty( &mut self, type_ref: TypeRefId, - store: &ExpressionStore, + store: &'db ExpressionStore, type_source: InferenceTyDiagnosticSource, store_owner: ExpressionStoreOwnerId, lifetime_elision: LifetimeElisionKind<'db>, @@ -2515,7 +2531,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { }; fn forbid_unresolved_segments<'db>( - ctx: &InferenceContext<'_, 'db>, + ctx: &InferenceContext<'db>, result: (Ty<'db>, Option), unresolved: Option, ) -> (Ty<'db>, Option) { @@ -2685,7 +2701,7 @@ impl<'db> Expectation<'db> { /// which still is useful, because it informs integer literals and the like. /// See the test case `test/ui/coerce-expect-unsized.rs` and #20169 /// for examples of where this comes up,. - fn rvalue_hint(ctx: &mut InferenceContext<'_, 'db>, ty: Ty<'db>) -> Self { + fn rvalue_hint(ctx: &mut InferenceContext<'db>, ty: Ty<'db>) -> Self { match ctx.struct_tail_without_normalization(ty).kind() { TyKind::Slice(_) | TyKind::Str | TyKind::Dynamic(..) => { Expectation::RValueLikeUnsized(ty) diff --git a/crates/hir-ty/src/infer/callee.rs b/crates/hir-ty/src/infer/callee.rs index 057ba7fa868f..05bd3518149d 100644 --- a/crates/hir-ty/src/infer/callee.rs +++ b/crates/hir-ty/src/infer/callee.rs @@ -33,7 +33,7 @@ enum CallStep<'db> { Overloaded(MethodCallee<'db>), } -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { pub(crate) fn infer_call( &mut self, call_expr: ExprId, @@ -106,7 +106,7 @@ impl<'db> InferenceContext<'_, 'db> { call_expr: ExprId, callee_expr: ExprId, arg_exprs: &[ExprId], - autoderef: &mut InferenceContextAutoderef<'_, '_, 'db>, + autoderef: &mut InferenceContextAutoderef<'_, 'db>, error_reported: &mut bool, ) -> Option> { let final_ty = autoderef.final_ty(); @@ -538,8 +538,8 @@ pub(crate) struct DeferredCallResolution<'db> { fn_sig: FnSig<'db>, } -impl<'a, 'db> DeferredCallResolution<'db> { - pub(crate) fn resolve(self, ctx: &mut InferenceContext<'a, 'db>) { +impl<'db> DeferredCallResolution<'db> { + pub(crate) fn resolve(self, ctx: &mut InferenceContext<'db>) { debug!("DeferredCallResolution::resolve() {:?}", self); // we should not be invoked until the closure kind has been diff --git a/crates/hir-ty/src/infer/cast.rs b/crates/hir-ty/src/infer/cast.rs index da996ccbea86..dc0813908194 100644 --- a/crates/hir-ty/src/infer/cast.rs +++ b/crates/hir-ty/src/infer/cast.rs @@ -123,7 +123,7 @@ impl<'db> CastCheck<'db> { pub(super) fn check( &mut self, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ) -> Result<(), InferenceDiagnostic> { self.expr_ty = ctx.table.try_structurally_resolve_type(self.source_expr.into(), self.expr_ty); @@ -159,7 +159,7 @@ impl<'db> CastCheck<'db> { self.do_check(ctx).map_err(|e| e.into_diagnostic(self.expr, self.expr_ty, self.cast_ty)) } - fn do_check(&self, ctx: &mut InferenceContext<'_, 'db>) -> Result<(), CastError> { + fn do_check(&self, ctx: &mut InferenceContext<'db>) -> Result<(), CastError> { let (t_from, t_cast) = match (CastTy::from_ty(ctx.db, self.expr_ty), CastTy::from_ty(ctx.db, self.cast_ty)) { (Some(t_from), Some(t_cast)) => (t_from, t_cast), @@ -258,7 +258,7 @@ impl<'db> CastCheck<'db> { fn check_ref_cast( &self, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, t_expr: Ty<'db>, m_expr: Mutability, t_cast: Ty<'db>, @@ -304,7 +304,7 @@ impl<'db> CastCheck<'db> { fn check_ptr_ptr_cast( &self, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, src: Ty<'db>, dst: Ty<'db>, ) -> Result<(), CastError> { @@ -456,7 +456,7 @@ impl<'db> CastCheck<'db> { fn check_ptr_addr_cast( &self, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, expr_ty: Ty<'db>, ) -> Result<(), CastError> { match pointer_kind(self.expr, expr_ty, ctx).map_err(|_| CastError::Unknown)? { @@ -470,7 +470,7 @@ impl<'db> CastCheck<'db> { fn check_addr_ptr_cast( &self, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, cast_ty: Ty<'db>, ) -> Result<(), CastError> { match pointer_kind(self.expr, cast_ty, ctx).map_err(|_| CastError::Unknown)? { @@ -486,7 +486,7 @@ impl<'db> CastCheck<'db> { fn check_fptr_ptr_cast( &self, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, cast_ty: Ty<'db>, ) -> Result<(), CastError> { match pointer_kind(self.expr, cast_ty, ctx).map_err(|_| CastError::Unknown)? { @@ -520,7 +520,7 @@ enum PointerKind<'db> { fn pointer_kind<'db>( expr: ExprId, ty: Ty<'db>, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ) -> Result>, ()> { let ty = ctx.table.try_structurally_resolve_type(expr.into(), ty); diff --git a/crates/hir-ty/src/infer/closure.rs b/crates/hir-ty/src/infer/closure.rs index ab111736d56a..502b64a70f1b 100644 --- a/crates/hir-ty/src/infer/closure.rs +++ b/crates/hir-ty/src/infer/closure.rs @@ -47,7 +47,7 @@ struct ClosureSignatures<'db> { liberated_sig: FnSig<'db>, } -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { fn poll_option_ty(&mut self, item_ty: Ty<'db>) -> Ty<'db> { let interner = self.interner(); diff --git a/crates/hir-ty/src/infer/closure/analysis.rs b/crates/hir-ty/src/infer/closure/analysis.rs index 5ea43bc03ca8..e6c449cfe315 100644 --- a/crates/hir-ty/src/infer/closure/analysis.rs +++ b/crates/hir-ty/src/infer/closure/analysis.rs @@ -194,7 +194,7 @@ enum PlaceAncestryRelation { /// analysis pass. type InferredCaptureInformation = Vec<(Place, CaptureInfo)>; -impl<'a, 'db> InferenceContext<'a, 'db> { +impl<'db> InferenceContext<'db> { pub(crate) fn closure_analyze(&mut self) { let upvars = crate::upvars::upvars_mentioned(self.db, self.store_owner) .unwrap_or(const { &FxHashMap::with_hasher(FxBuildHasher) }); @@ -1202,7 +1202,7 @@ impl<'db> euv::Delegate<'db> for InferBorrowKind { &mut self, place_with_id: PlaceWithOrigin, cause: FakeReadCause, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ) { let PlaceBase::Upvar { .. } = place_with_id.place.base else { return }; @@ -1222,7 +1222,7 @@ impl<'db> euv::Delegate<'db> for InferBorrowKind { } #[instrument(skip(self), level = "debug")] - fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else { return; }; @@ -1237,7 +1237,7 @@ impl<'db> euv::Delegate<'db> for InferBorrowKind { } #[instrument(skip(self), level = "debug")] - fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else { return; }; @@ -1256,7 +1256,7 @@ impl<'db> euv::Delegate<'db> for InferBorrowKind { &mut self, place_with_id: PlaceWithOrigin, bk: BorrowKind, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ) { let PlaceBase::Upvar { closure: upvar_closure, .. } = place_with_id.place.base else { return; @@ -1284,15 +1284,15 @@ impl<'db> euv::Delegate<'db> for InferBorrowKind { } #[instrument(skip(self), level = "debug")] - fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { self.borrow(assignee_place, BorrowKind::Mutable, ctx); } } /// Rust doesn't permit moving fields out of a type that implements drop #[instrument(skip(fcx), ret, level = "debug")] -fn restrict_precision_for_drop_types<'a, 'db>( - fcx: &mut InferenceContext<'a, 'db>, +fn restrict_precision_for_drop_types<'db>( + fcx: &mut InferenceContext<'db>, mut place: Place, capture_info: &mut CaptureInfo, ) -> Place { diff --git a/crates/hir-ty/src/infer/closure/analysis/expr_use_visitor.rs b/crates/hir-ty/src/infer/closure/analysis/expr_use_visitor.rs index d8a8cceee658..7f4b112b688c 100644 --- a/crates/hir-ty/src/infer/closure/analysis/expr_use_visitor.rs +++ b/crates/hir-ty/src/infer/closure/analysis/expr_use_visitor.rs @@ -301,7 +301,7 @@ pub(crate) trait Delegate<'db> { /// diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic /// id will be the id of the expression `expr` but the place itself will have /// the id of the binding in the pattern `pat`. - fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>); + fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>); /// The value found at `place` is used, depending /// on `mode`. Where `diag_expr_id` is the id used for diagnostics for `place`. @@ -316,7 +316,7 @@ pub(crate) trait Delegate<'db> { /// diagnostics. Around pattern matching such as `let pat = expr`, the diagnostic /// id will be the id of the expression `expr` but the place itself will have /// the id of the binding in the pattern `pat`. - fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>); + fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>); /// The value found at `place` is being borrowed with kind `bk`. /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details). @@ -324,7 +324,7 @@ pub(crate) trait Delegate<'db> { &mut self, place_with_id: PlaceWithOrigin, bk: BorrowKind, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ); /// The value found at `place` is being copied. @@ -333,7 +333,7 @@ pub(crate) trait Delegate<'db> { /// If an implementation is not provided, use of a `Copy` type in a ByValue context is instead /// considered a use by `ImmBorrow` and `borrow` is called instead. This is because a shared /// borrow is the "minimum access" that would be needed to perform a copy. - fn copy(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn copy(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { // In most cases, copying data from `x` is equivalent to doing `*&x`, so by default // we treat a copy of `x` as a borrow of `x`. self.borrow(place_with_id, BorrowKind::Immutable, ctx) @@ -341,12 +341,12 @@ pub(crate) trait Delegate<'db> { /// The path at `assignee_place` is being assigned to. /// `diag_expr_id` is the id used for diagnostics (see `consume` for more details). - fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>); + fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>); /// The path at `binding_place` is a binding that is being initialized. /// /// This covers cases such as `let x = 42;` - fn bind(&mut self, binding_place: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn bind(&mut self, binding_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { // Bindings can normally be treated as a regular assignment, so by default we // forward this to the mutate callback. self.mutate(binding_place, ctx) @@ -357,16 +357,16 @@ pub(crate) trait Delegate<'db> { &mut self, place_with_id: PlaceWithOrigin, cause: FakeReadCause, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ); } impl<'db, D: Delegate<'db>> Delegate<'db> for &mut D { - fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn consume(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { (**self).consume(place_with_id, ctx) } - fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn use_cloned(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { (**self).use_cloned(place_with_id, ctx) } @@ -374,20 +374,20 @@ impl<'db, D: Delegate<'db>> Delegate<'db> for &mut D { &mut self, place_with_id: PlaceWithOrigin, bk: BorrowKind, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ) { (**self).borrow(place_with_id, bk, ctx) } - fn copy(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn copy(&mut self, place_with_id: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { (**self).copy(place_with_id, ctx) } - fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn mutate(&mut self, assignee_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { (**self).mutate(assignee_place, ctx) } - fn bind(&mut self, binding_place: PlaceWithOrigin, ctx: &mut InferenceContext<'_, 'db>) { + fn bind(&mut self, binding_place: PlaceWithOrigin, ctx: &mut InferenceContext<'db>) { (**self).bind(binding_place, ctx) } @@ -395,7 +395,7 @@ impl<'db, D: Delegate<'db>> Delegate<'db> for &mut D { &mut self, place_with_id: PlaceWithOrigin, cause: FakeReadCause, - ctx: &mut InferenceContext<'_, 'db>, + ctx: &mut InferenceContext<'db>, ) { (**self).fake_read(place_with_id, cause, ctx) } @@ -404,21 +404,21 @@ impl<'db, D: Delegate<'db>> Delegate<'db> for &mut D { /// A visitor that reports how each expression is being used. /// /// See [module-level docs][self] and [`Delegate`] for details. -pub(crate) struct ExprUseVisitor<'a, 'b, 'db, D: Delegate<'db>> { - cx: &'a mut InferenceContext<'b, 'db>, +pub(crate) struct ExprUseVisitor<'a, 'db, D: Delegate<'db>> { + cx: &'a mut InferenceContext<'db>, delegate: D, closure_expr: ExprId, upvars: UpvarsRef<'db>, } -impl<'a, 'b, 'db, D: Delegate<'db>> ExprUseVisitor<'a, 'b, 'db, D> { +impl<'a, 'db, D: Delegate<'db>> ExprUseVisitor<'a, 'db, D> { /// Creates the ExprUseVisitor, configuring it with the various options provided: /// /// - `delegate` -- who receives the callbacks /// - `param_env` --- parameter environment for trait lookups (esp. pertaining to `Copy`) /// - `typeck_results` --- typeck results for the code being analyzed pub(crate) fn new( - cx: &'a mut InferenceContext<'b, 'db>, + cx: &'a mut InferenceContext<'db>, closure_expr: ExprId, upvars: UpvarsRef<'db>, delegate: D, @@ -1165,7 +1165,7 @@ impl_from!(PatId for CatPatternPat); /// example, auto-derefs are explicit. Also, an index `a[b]` is decomposed into /// two operations: a dereference to reach the array data and then an index to /// jump forward to the relevant item. -impl<'db, D: Delegate<'db>> ExprUseVisitor<'_, '_, 'db, D> { +impl<'db, D: Delegate<'db>> ExprUseVisitor<'_, 'db, D> { fn expect_and_resolve_type(&mut self, ty: Option>) -> Result> { match ty { Some(ty) => { diff --git a/crates/hir-ty/src/infer/coerce.rs b/crates/hir-ty/src/infer/coerce.rs index 343919f5babb..85d8142335dd 100644 --- a/crates/hir-ty/src/infer/coerce.rs +++ b/crates/hir-ty/src/infer/coerce.rs @@ -793,7 +793,7 @@ where fn coerce_closure_to_fn( &mut self, a: Ty<'db>, - closure_def_id_a: InternedClosureId, + closure_def_id_a: InternedClosureId<'db>, args_a: GenericArgs<'db>, b: Ty<'db>, ) -> CoerceResult<'db> { @@ -856,9 +856,9 @@ where } } -struct InferenceCoercionDelegate<'a, 'b, 'db>(&'a mut InferenceContext<'b, 'db>); +struct InferenceCoercionDelegate<'a, 'db>(&'a mut InferenceContext<'db>); -impl<'db> CoerceDelegate<'db> for InferenceCoercionDelegate<'_, '_, 'db> { +impl<'db> CoerceDelegate<'db> for InferenceCoercionDelegate<'_, 'db> { #[inline] fn infcx(&self) -> &InferCtxt<'db> { &self.0.table.infer_ctxt @@ -884,7 +884,7 @@ impl<'db> CoerceDelegate<'db> for InferenceCoercionDelegate<'_, '_, 'db> { } } -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { /// Attempt to coerce an expression to a type, and return the /// adjusted type of the expression, if successful. /// Adjustments are only recorded if the coercion succeeded. @@ -1242,7 +1242,7 @@ impl<'db, 'exprs> CoerceMany<'db, 'exprs> { /// if necessary. pub(crate) fn coerce( &mut self, - icx: &mut InferenceContext<'_, 'db>, + icx: &mut InferenceContext<'db>, cause: &ObligationCause, expression: ExprId, expression_ty: Ty<'db>, @@ -1265,7 +1265,7 @@ impl<'db, 'exprs> CoerceMany<'db, 'exprs> { /// removing a `;`). pub(crate) fn coerce_forced_unit( &mut self, - icx: &mut InferenceContext<'_, 'db>, + icx: &mut InferenceContext<'db>, expr: ExprId, cause: &ObligationCause, label_unit_as_expected: bool, @@ -1287,7 +1287,7 @@ impl<'db, 'exprs> CoerceMany<'db, 'exprs> { /// `Nil`. pub(crate) fn coerce_inner( &mut self, - icx: &mut InferenceContext<'_, 'db>, + icx: &mut InferenceContext<'db>, cause: &ObligationCause, expression: ExprId, mut expression_ty: Ty<'db>, @@ -1403,7 +1403,7 @@ impl<'db, 'exprs> CoerceMany<'db, 'exprs> { self.pushed += 1; } - pub(crate) fn complete(self, icx: &mut InferenceContext<'_, 'db>) -> Ty<'db> { + pub(crate) fn complete(self, icx: &mut InferenceContext<'db>) -> Ty<'db> { if let Some(final_ty) = self.final_ty { final_ty } else { @@ -1597,7 +1597,7 @@ fn coerce<'db>( Ok((adjustments, ty)) } -fn is_capturing_closure(db: &dyn HirDatabase, closure: InternedClosureId) -> bool { +fn is_capturing_closure(db: &dyn HirDatabase, closure: InternedClosureId<'_>) -> bool { let InternedClosure { owner, expr, .. } = closure.loc(db); upvars_mentioned(db, owner.expression_store_owner(db)) .is_some_and(|upvars| upvars.get(&expr).is_some_and(|upvars| !upvars.is_empty())) diff --git a/crates/hir-ty/src/infer/diagnostics.rs b/crates/hir-ty/src/infer/diagnostics.rs index dd0efea4d754..26c0bb676a95 100644 --- a/crates/hir-ty/src/infer/diagnostics.rs +++ b/crates/hir-ty/src/infer/diagnostics.rs @@ -89,7 +89,7 @@ pub(super) struct InferenceTyLoweringContext<'db, 'a> { ctx: TyLoweringContext<'db, 'a>, diagnostics: &'a Diagnostics, source: InferenceTyDiagnosticSource, - defined_anon_consts: &'a RefCell>, + defined_anon_consts: &'a RefCell>>, } impl<'db, 'a> InferenceTyLoweringContext<'db, 'a> { @@ -97,7 +97,7 @@ impl<'db, 'a> InferenceTyLoweringContext<'db, 'a> { pub(super) fn new( db: &'db dyn HirDatabase, resolver: &'a Resolver<'db>, - store: &'a ExpressionStore, + store: &'db ExpressionStore, diagnostics: &'a Diagnostics, source: InferenceTyDiagnosticSource, def: ExpressionStoreOwnerId, @@ -106,7 +106,7 @@ impl<'db, 'a> InferenceTyLoweringContext<'db, 'a> { lifetime_elision: LifetimeElisionKind<'db>, allow_using_generic_params: bool, infer_vars: Option<&'a mut dyn TyLoweringInferVarsCtx<'db>>, - defined_anon_consts: &'a RefCell>, + defined_anon_consts: &'a RefCell>>, ) -> Self { let mut ctx = TyLoweringContext::new( db, diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs index 5f752da3d08d..0c6a5e061618 100644 --- a/crates/hir-ty/src/infer/expr.rs +++ b/crates/hir-ty/src/infer/expr.rs @@ -53,7 +53,7 @@ pub(crate) enum ExprIsRead { No, } -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { pub(crate) fn infer_expr( &mut self, tgt_expr: ExprId, @@ -2094,7 +2094,7 @@ impl<'db> InferenceContext<'_, 'db> { // We introduce a helper function to demand that a given argument satisfy a given input // This is more complicated than just checking type equality, as arguments could be coerced // This version writes those types back so further type checking uses the narrowed types - let demand_compatible = |this: &mut InferenceContext<'_, 'db>, idx| { + let demand_compatible = |this: &mut InferenceContext<'db>, idx| { let formal_input_ty: Ty<'db> = formal_input_tys[idx]; let expected_input_ty: Ty<'db> = expected_input_tys[idx]; let provided_arg = provided_args[idx]; diff --git a/crates/hir-ty/src/infer/fallback.rs b/crates/hir-ty/src/infer/fallback.rs index 3744a434d219..0498ea8fd00a 100644 --- a/crates/hir-ty/src/infer/fallback.rs +++ b/crates/hir-ty/src/infer/fallback.rs @@ -27,7 +27,7 @@ pub(crate) enum DivergingFallbackBehavior { ToNever, } -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { pub(super) fn type_inference_fallback(&mut self) { debug!( "type-inference-fallback start obligations: {:#?}", diff --git a/crates/hir-ty/src/infer/mutability.rs b/crates/hir-ty/src/infer/mutability.rs index 4fa1b71ad4a9..9ec297f5f5e4 100644 --- a/crates/hir-ty/src/infer/mutability.rs +++ b/crates/hir-ty/src/infer/mutability.rs @@ -13,7 +13,7 @@ use crate::{ lower::lower_mutability, }; -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { pub(crate) fn infer_mut_body(&mut self, body_expr: ExprId) { self.infer_mut_expr(body_expr, Mutability::Not); } diff --git a/crates/hir-ty/src/infer/op.rs b/crates/hir-ty/src/infer/op.rs index 9119af9628eb..3ba87202086e 100644 --- a/crates/hir-ty/src/infer/op.rs +++ b/crates/hir-ty/src/infer/op.rs @@ -20,7 +20,7 @@ use crate::{ }, }; -impl<'a, 'db> InferenceContext<'a, 'db> { +impl<'db> InferenceContext<'db> { /// Checks a `a = b` pub(crate) fn infer_assign_op_expr( &mut self, diff --git a/crates/hir-ty/src/infer/opaques.rs b/crates/hir-ty/src/infer/opaques.rs index 63149deb82b7..2d64f9567b37 100644 --- a/crates/hir-ty/src/infer/opaques.rs +++ b/crates/hir-ty/src/infer/opaques.rs @@ -12,7 +12,7 @@ use crate::{ }, }; -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { /// This takes all the opaque type uses during HIR typeck. It first computes /// the concrete hidden type by iterating over all defining uses. /// @@ -63,7 +63,7 @@ impl<'db> UsageKind<'db> { } } -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { fn compute_definition_site_hidden_types( &mut self, mut opaque_types: Vec<(OpaqueTypeKey<'db>, OpaqueHiddenType<'db>)>, diff --git a/crates/hir-ty/src/infer/pat.rs b/crates/hir-ty/src/infer/pat.rs index 915da943ca11..61f8dec40e68 100644 --- a/crates/hir-ty/src/infer/pat.rs +++ b/crates/hir-ty/src/infer/pat.rs @@ -237,7 +237,7 @@ impl<'db> ResolvedPat<'db> { } } -impl<'a, 'db> InferenceContext<'a, 'db> { +impl<'db> InferenceContext<'db> { /// Experimental pattern feature: after matching against a shared reference, do we limit the /// default binding mode in subpatterns to be `ref` when it would otherwise be `ref mut`? /// This corresponds to Rule 3 of RFC 3627. diff --git a/crates/hir-ty/src/infer/path.rs b/crates/hir-ty/src/infer/path.rs index 0ec72edc3d59..6c7dda7a08eb 100644 --- a/crates/hir-ty/src/infer/path.rs +++ b/crates/hir-ty/src/infer/path.rs @@ -25,7 +25,7 @@ use crate::{ use super::{ExprOrPatId, InferenceContext, InferenceTyDiagnosticSource}; -impl<'db> InferenceContext<'_, 'db> { +impl<'db> InferenceContext<'db> { pub(super) fn infer_path( &mut self, path: &Path, diff --git a/crates/hir-ty/src/infer/place_op.rs b/crates/hir-ty/src/infer/place_op.rs index bbf047b8bacf..b226e5ca85de 100644 --- a/crates/hir-ty/src/infer/place_op.rs +++ b/crates/hir-ty/src/infer/place_op.rs @@ -25,7 +25,7 @@ pub(super) enum PlaceOp { Index, } -impl<'a, 'db> InferenceContext<'a, 'db> { +impl<'db> InferenceContext<'db> { pub(super) fn try_overloaded_deref( &self, expr: ExprId, @@ -107,7 +107,7 @@ impl<'a, 'db> InferenceContext<'a, 'db> { expr: ExprId, base_expr: ExprId, index_expr: ExprId, - autoderef: &mut InferenceContextAutoderef<'_, 'a, 'db>, + autoderef: &mut InferenceContextAutoderef<'_, 'db>, index_ty: Ty<'db>, ) -> Option<(/*index type*/ Ty<'db>, /*element type*/ Ty<'db>)> { let ty = autoderef.final_ty(); diff --git a/crates/hir-ty/src/infer/unify.rs b/crates/hir-ty/src/infer/unify.rs index 4c808714d950..6157f51500d9 100644 --- a/crates/hir-ty/src/infer/unify.rs +++ b/crates/hir-ty/src/infer/unify.rs @@ -314,7 +314,11 @@ impl<'db> InferenceTable<'db> { } /// Create a `GenericArgs` full of infer vars for `def`. - pub(crate) fn fresh_args_for_item(&self, span: Span, def: SolverDefId) -> GenericArgs<'db> { + pub(crate) fn fresh_args_for_item( + &self, + span: Span, + def: SolverDefId<'db>, + ) -> GenericArgs<'db> { self.infer_ctxt.fresh_args_for_item(span, def) } diff --git a/crates/hir-ty/src/layout.rs b/crates/hir-ty/src/layout.rs index ed4775539a10..14609004f748 100644 --- a/crates/hir-ty/src/layout.rs +++ b/crates/hir-ty/src/layout.rs @@ -176,7 +176,7 @@ pub fn layout_of_ty_query( let infer_ctxt = interner.infer_ctxt().build(TypingMode::PostAnalysis); let cause = ObligationCause::dummy(); let ty = infer_ctxt - .at(&cause, trait_env.param_env()) + .at(&cause, trait_env.param_env(db)) .deeply_normalize(ty.as_ref()) .unwrap_or(ty.as_ref()); let result = match ty.kind() { @@ -190,7 +190,7 @@ pub fn layout_of_ty_query( s, repr.packed(), &args, - trait_env.as_ref(), + trait_env.as_ref(db), target, ); } @@ -355,11 +355,11 @@ pub fn layout_of_ty_query( PatternKind::Range { start, end } => { if let BackendRepr::Scalar(scalar) = &mut layout.backend_repr { scalar.valid_range_mut().start = extract_const_value(start)? - .try_to_bits(db, trait_env.as_ref()) + .try_to_bits(db, trait_env.as_ref(db)) .ok_or(LayoutError::Unknown)?; scalar.valid_range_mut().end = extract_const_value(end)? - .try_to_bits(db, trait_env.as_ref()) + .try_to_bits(db, trait_env.as_ref(db)) .ok_or(LayoutError::Unknown)?; // FIXME(pattern_types): create implied bounds from pattern types in signatures @@ -419,10 +419,10 @@ pub fn layout_of_ty_query( .map(|pat| match pat.kind() { PatternKind::Range { start, end } => Ok::<_, LayoutError>(( extract_const_value(start)? - .try_to_bits(db, trait_env.as_ref()) + .try_to_bits(db, trait_env.as_ref(db)) .ok_or(LayoutError::Unknown)?, extract_const_value(end)? - .try_to_bits(db, trait_env.as_ref()) + .try_to_bits(db, trait_env.as_ref(db)) .ok_or(LayoutError::Unknown)?, )), PatternKind::NotNull | PatternKind::Or(_) => { diff --git a/crates/hir-ty/src/layout/adt.rs b/crates/hir-ty/src/layout/adt.rs index 22dd53ca2dd0..201ddebc1248 100644 --- a/crates/hir-ty/src/layout/adt.rs +++ b/crates/hir-ty/src/layout/adt.rs @@ -82,7 +82,8 @@ pub fn layout_of_adt_query( |min, max| repr_discr(dl, &repr, min, max).unwrap_or((Integer::I8, false)), variants.iter_enumerated().filter_map(|(id, _)| { let AdtId::EnumId(e) = def else { return None }; - let d = db.const_eval_discriminant(e.enum_variants(db).variants[id.0].0).ok()?; + let d = + db.const_eval_discriminant(e.enum_variants(db).variants[id.0].0).ok()? as i128; Some((id, d)) }), !matches!(def, AdtId::EnumId(..)) diff --git a/crates/hir-ty/src/lib.rs b/crates/hir-ty/src/lib.rs index cc48ba06dbfc..7ce0f67888d0 100644 --- a/crates/hir-ty/src/lib.rs +++ b/crates/hir-ty/src/lib.rs @@ -81,6 +81,7 @@ use rustc_type_ir::{ BoundVarIndexKind, TypeSuperVisitable, TypeVisitableExt, inherent::{IntoKind, Ty as _}, }; +use salsa::Update; use stdx::impl_from; use syntax::ast::{ConstArg, make}; use traits::FnTrait; @@ -165,7 +166,7 @@ impl ComplexMemoryMap<'_> { } impl<'db> MemoryMap<'db> { - pub fn vtable_ty(&self, id: usize) -> Result, MirEvalError> { + pub fn vtable_ty(&self, id: usize) -> Result, MirEvalError<'db>> { match self { MemoryMap::Empty | MemoryMap::Simple(_) => Err(MirEvalError::InvalidVTableId(id)), MemoryMap::Complex(cm) => cm.vtable.ty(id), @@ -181,8 +182,8 @@ impl<'db> MemoryMap<'db> { /// allocator function as `f` and it will return a mapping of old addresses to new addresses. fn transform_addresses( &self, - mut f: impl FnMut(&[u8], usize) -> Result, - ) -> Result, MirEvalError> { + mut f: impl FnMut(&[u8], usize) -> Result>, + ) -> Result, MirEvalError<'db>> { let mut transform = |(addr, val): (&usize, &[u8])| { let addr = *addr; let align = if addr == 0 { 64 } else { (addr - (addr & (addr - 1))).min(64) }; @@ -552,19 +553,43 @@ impl Span { } /// A [`DefWithBodyId`], or an anon const. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, salsa::Supertype)] -pub enum InferBodyId { +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, salsa::Supertype, Update)] +pub enum InferBodyId<'db> { DefWithBodyId(DefWithBodyId), - AnonConstId(AnonConstId), + AnonConstId(AnonConstId<'db>), } -impl_from!(DefWithBodyId(FunctionId, ConstId, StaticId), AnonConstId for InferBodyId); -impl From for InferBodyId { +impl<'db> From for InferBodyId<'db> { + fn from(it: DefWithBodyId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it) + } +} +impl<'db> From for InferBodyId<'db> { + fn from(it: FunctionId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it.into()) + } +} +impl<'db> From for InferBodyId<'db> { + fn from(it: ConstId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it.into()) + } +} +impl<'db> From for InferBodyId<'db> { + fn from(it: StaticId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it.into()) + } +} +impl<'db> From> for InferBodyId<'db> { + fn from(it: AnonConstId<'db>) -> InferBodyId<'db> { + InferBodyId::AnonConstId(it) + } +} +impl<'db> From for InferBodyId<'db> { fn from(id: EnumVariantId) -> Self { InferBodyId::DefWithBodyId(DefWithBodyId::VariantId(id)) } } -impl HasModule for InferBodyId { +impl HasModule for InferBodyId<'_> { fn module(&self, db: &dyn DefDatabase) -> ModuleId { match self { InferBodyId::DefWithBodyId(id) => id.module(db), @@ -573,7 +598,7 @@ impl HasModule for InferBodyId { } } -impl HasResolver for InferBodyId { +impl HasResolver for InferBodyId<'_> { fn resolver(self, db: &dyn DefDatabase) -> Resolver<'_> { match self { InferBodyId::DefWithBodyId(id) => id.resolver(db), @@ -582,7 +607,7 @@ impl HasResolver for InferBodyId { } } -impl InferBodyId { +impl InferBodyId<'_> { pub fn expression_store_owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwnerId { match self { InferBodyId::DefWithBodyId(id) => id.into(), diff --git a/crates/hir-ty/src/lower.rs b/crates/hir-ty/src/lower.rs index fae63ddc2dea..7f70e8410cf8 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -49,6 +49,7 @@ use rustc_type_ir::{ TypeVisitableExt, Upcast, UpcastFrom, elaborate, inherent::{Clause as _, GenericArgs as _, IntoKind as _, Region as _, Ty as _}, }; +use salsa::Update; use smallvec::SmallVec; use stdx::{impl_from, never}; use thin_vec::ThinVec; @@ -232,7 +233,7 @@ pub struct TyLoweringContext<'db, 'a> { types: &'db crate::next_solver::DefaultAny<'db>, lang_items: &'db LangItems, resolver: &'a Resolver<'db>, - store: &'a ExpressionStore, + store: &'db ExpressionStore, def: ExpressionStoreOwnerId, generic_def: GenericDefId, generics: &'a OnceCell>, @@ -245,7 +246,7 @@ pub struct TyLoweringContext<'db, 'a> { lifetime_elision: LifetimeElisionKind<'db>, forbid_params_after: Option, forbid_params_after_reason: ForbidParamsAfterReason, - pub(crate) defined_anon_consts: ThinVec, + pub(crate) defined_anon_consts: ThinVec>, infer_vars: Option<&'a mut dyn TyLoweringInferVarsCtx<'db>>, } @@ -253,7 +254,7 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> { pub fn new( db: &'db dyn HirDatabase, resolver: &'a Resolver<'db>, - store: &'a ExpressionStore, + store: &'db ExpressionStore, def: ExpressionStoreOwnerId, generic_def: GenericDefId, generics: &'a OnceCell>, @@ -1185,12 +1186,34 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> { } #[derive(Clone, PartialEq, Eq)] -pub struct TyLoweringResult { +pub struct TyLoweringResult<'db, T> { pub value: T, - info: Option, ThinVec)>>, + info: Option>>, } -impl std::fmt::Debug for TyLoweringResult { +unsafe impl<'db, T: 'static + PartialEq> salsa::Update for TyLoweringResult<'db, T> { + unsafe fn maybe_update(old_pointer_: *mut Self, new_value_: Self) -> bool { + let old_pointer_ = unsafe { &mut *old_pointer_ }; + false + | { + if old_pointer_.value != new_value_.value { + old_pointer_.value = new_value_.value; + true + } else { + false + } + } + | unsafe { salsa::Update::maybe_update(&mut old_pointer_.info, new_value_.info) } + } +} + +#[derive(Clone, PartialEq, Eq, Update)] +struct TyLoweringResultInfo<'db> { + diagnostics: ThinVec, + anon_consts: ThinVec>, +} + +impl std::fmt::Debug for TyLoweringResult<'_, T> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut debug = f.debug_struct("TyLoweringResult"); debug.field("value", &self.value); @@ -1206,23 +1229,23 @@ impl std::fmt::Debug for TyLoweringResult { } } -impl TyLoweringResult { +impl<'db, T> TyLoweringResult<'db, T> { fn new( value: T, mut diagnostics: ThinVec, - mut defined_anon_consts: ThinVec, + mut defined_anon_consts: ThinVec>, ) -> Self { let info = if diagnostics.is_empty() && defined_anon_consts.is_empty() { None } else { diagnostics.shrink_to_fit(); defined_anon_consts.shrink_to_fit(); - Some(Box::new((diagnostics, defined_anon_consts))) + Some(Box::new(TyLoweringResultInfo { diagnostics, anon_consts: defined_anon_consts })) }; Self { value, info } } - fn from_ctx(value: T, ctx: TyLoweringContext<'_, '_>) -> Self { + fn from_ctx(value: T, ctx: TyLoweringContext<'db, '_>) -> Self { Self::new(value, ctx.diagnostics, ctx.defined_anon_consts) } @@ -1233,15 +1256,15 @@ impl TyLoweringResult { #[inline] pub fn diagnostics(&self) -> &[TyLoweringDiagnostic] { match &self.info { - Some(info) => &info.0, + Some(info) => &info.diagnostics, None => &[], } } #[inline] - pub fn defined_anon_consts(&self) -> &[AnonConstId] { + pub fn defined_anon_consts(&self) -> &[AnonConstId<'db>] { match &self.info { - Some(info) => &info.1, + Some(info) => &info.anon_consts, None => &[], } } @@ -1279,10 +1302,10 @@ pub(crate) fn impl_trait_query<'db>( } #[salsa::tracked(returns(ref))] -pub(crate) fn impl_trait_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn impl_trait_with_diagnostics<'db>( + db: &'db dyn HirDatabase, impl_id: ImplId, -) -> Option>> { +) -> Option>> { let impl_data = ImplSignature::of(db, impl_id); let resolver = impl_id.resolver(db); let generics = OnceCell::new(); @@ -1494,10 +1517,10 @@ pub(crate) fn type_for_const<'db>( /// Build the declared type of a const. #[salsa_macros::tracked(returns(ref))] -pub(crate) fn type_for_const_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn type_for_const_with_diagnostics<'db>( + db: &'db dyn HirDatabase, def: ConstId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { let resolver = def.resolver(db); let data = ConstSignature::of(db, def); let parent = def.loc(db).container; @@ -1525,10 +1548,10 @@ pub(crate) fn type_for_static<'db>( /// Build the declared type of a static. #[salsa_macros::tracked(returns(ref))] -pub(crate) fn type_for_static_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn type_for_static_with_diagnostics<'db>( + db: &'db dyn HirDatabase, def: StaticId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { let resolver = def.resolver(db); let data = StaticSignature::of(db, def); let generics = OnceCell::new(); @@ -1601,10 +1624,10 @@ pub(crate) fn value_ty<'db>( } #[salsa::tracked(returns(ref), cycle_result = type_for_type_alias_with_diagnostics_cycle_result)] -pub(crate) fn type_for_type_alias_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn type_for_type_alias_with_diagnostics<'db>( + db: &'db dyn HirDatabase, t: TypeAliasId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { let type_alias_data = TypeAliasSignature::of(db, t); let interner = DbInterner::new_no_crate(db); if type_alias_data.flags.contains(TypeAliasFlags::IS_EXTERN) { @@ -1635,11 +1658,11 @@ pub(crate) fn type_for_type_alias_with_diagnostics( } } -pub(crate) fn type_for_type_alias_with_diagnostics_cycle_result( - db: &dyn HirDatabase, +pub(crate) fn type_for_type_alias_with_diagnostics_cycle_result<'db>( + db: &'db dyn HirDatabase, _: salsa::Id, _adt: TypeAliasId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { TyLoweringResult::empty(StoredEarlyBinder::bind( Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed).store(), )) @@ -1653,10 +1676,10 @@ pub(crate) fn impl_self_ty_query<'db>( } #[salsa::tracked(returns(ref), cycle_result = impl_self_ty_with_diagnostics_cycle_result)] -pub(crate) fn impl_self_ty_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn impl_self_ty_with_diagnostics<'db>( + db: &'db dyn HirDatabase, impl_id: ImplId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { let resolver = impl_id.resolver(db); let generics = OnceCell::new(); let impl_data = ImplSignature::of(db, impl_id); @@ -1674,11 +1697,11 @@ pub(crate) fn impl_self_ty_with_diagnostics( TyLoweringResult::from_ctx(StoredEarlyBinder::bind(ty.store()), ctx) } -pub(crate) fn impl_self_ty_with_diagnostics_cycle_result( - db: &dyn HirDatabase, +pub(crate) fn impl_self_ty_with_diagnostics_cycle_result<'db>( + db: &'db dyn HirDatabase, _: salsa::Id, _impl_id: ImplId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { TyLoweringResult::empty(StoredEarlyBinder::bind( Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed).store(), )) @@ -1700,10 +1723,10 @@ pub(crate) fn const_param_types( } #[salsa::tracked(returns(ref), cycle_result = const_param_types_with_diagnostics_cycle_result)] -pub(crate) fn const_param_types_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn const_param_types_with_diagnostics<'db>( + db: &'db dyn HirDatabase, def: GenericDefId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, ArenaMap> { let mut result = ArenaMap::new(); let (data, store) = GenericParams::with_store(db, def); let resolver = def.resolver(db); @@ -1727,11 +1750,11 @@ pub(crate) fn const_param_types_with_diagnostics( TyLoweringResult::from_ctx(result, ctx) } -fn const_param_types_with_diagnostics_cycle_result( - _db: &dyn HirDatabase, +fn const_param_types_with_diagnostics_cycle_result<'db>( + _db: &'db dyn HirDatabase, _: salsa::Id, _def: GenericDefId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, ArenaMap> { TyLoweringResult::empty(ArenaMap::default()) } @@ -1762,10 +1785,10 @@ impl FieldType { /// Build the type of all specific fields of a struct or enum variant. #[salsa::tracked(returns(ref))] -pub(crate) fn field_types_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn field_types_with_diagnostics<'db>( + db: &'db dyn HirDatabase, variant_id: VariantId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, ArenaMap> { let var_data = variant_id.fields(db); let fields = var_data.fields(); if fields.is_empty() { @@ -2092,10 +2115,10 @@ pub struct TypeAliasBounds { } #[salsa::tracked(returns(ref))] -pub(crate) fn type_alias_bounds_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn type_alias_bounds_with_diagnostics<'db>( + db: &'db dyn HirDatabase, type_alias: TypeAliasId, -) -> TyLoweringResult>> { +) -> TyLoweringResult<'db, TypeAliasBounds>> { let type_alias_data = TypeAliasSignature::of(db, type_alias); let resolver = type_alias.resolver(db); let generics = OnceCell::new(); @@ -2178,17 +2201,17 @@ impl<'db> GenericPredicates { pub fn query_with_diagnostics( db: &'db dyn HirDatabase, def: GenericDefId, - ) -> TyLoweringResult { + ) -> TyLoweringResult<'db, GenericPredicates> { generic_predicates(db, def) } } /// A cycle can occur from malformed code. -fn generic_predicates_cycle_result( - db: &dyn HirDatabase, +fn generic_predicates_cycle_result<'db>( + db: &'db dyn HirDatabase, _: salsa::Id, _def: GenericDefId, -) -> TyLoweringResult { +) -> TyLoweringResult<'db, GenericPredicates> { TyLoweringResult::empty(GenericPredicates::from_explicit_own_predicates( StoredEarlyBinder::bind(Clauses::empty(DbInterner::new_no_crate(db)).store()), )) @@ -2328,10 +2351,10 @@ pub(crate) fn trait_environment<'db>(db: &'db dyn HirDatabase, def: GenericDefId /// Resolve the where clause(s) of an item with generics, /// with a given filter #[tracing::instrument(skip(db), ret)] -fn generic_predicates( - db: &dyn HirDatabase, +fn generic_predicates<'db>( + db: &'db dyn HirDatabase, def: GenericDefId, -) -> TyLoweringResult { +) -> TyLoweringResult<'db, GenericPredicates> { let generics = generics(db, def); let store = generics.store(); let generics = &OnceCell::from(generics); @@ -2542,10 +2565,10 @@ pub(crate) fn generic_defaults(db: &dyn HirDatabase, def: GenericDefId) -> Gener /// /// Diagnostics are only returned for this `GenericDefId` (returned defaults include parents). #[salsa_macros::tracked(returns(ref), cycle_result = generic_defaults_with_diagnostics_cycle_result)] -pub(crate) fn generic_defaults_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn generic_defaults_with_diagnostics<'db>( + db: &'db dyn HirDatabase, def: GenericDefId, -) -> TyLoweringResult { +) -> TyLoweringResult<'db, GenericDefaults> { let generics = generics(db, def); if generics.has_no_params() { return TyLoweringResult::empty(GenericDefaults(ThinVec::new())); @@ -2605,11 +2628,11 @@ pub(crate) fn generic_defaults_with_diagnostics( } } -fn generic_defaults_with_diagnostics_cycle_result( - _db: &dyn HirDatabase, +fn generic_defaults_with_diagnostics_cycle_result<'db>( + _db: &'db dyn HirDatabase, _: salsa::Id, _def: GenericDefId, -) -> TyLoweringResult { +) -> TyLoweringResult<'db, GenericDefaults> { TyLoweringResult::empty(GenericDefaults(ThinVec::new())) } @@ -2622,10 +2645,10 @@ pub(crate) fn callable_item_signature<'db>( } #[salsa::tracked(returns(ref))] -pub(crate) fn callable_item_signature_with_diagnostics( - db: &dyn HirDatabase, +pub(crate) fn callable_item_signature_with_diagnostics<'db>( + db: &'db dyn HirDatabase, def: CallableDefId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { match def { CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f), CallableDefId::StructId(s) => TyLoweringResult::empty(fn_sig_for_struct_constructor(db, s)), @@ -2635,10 +2658,10 @@ pub(crate) fn callable_item_signature_with_diagnostics( } } -fn fn_sig_for_fn( - db: &dyn HirDatabase, +fn fn_sig_for_fn<'db>( + db: &'db dyn HirDatabase, def: FunctionId, -) -> TyLoweringResult> { +) -> TyLoweringResult<'db, StoredEarlyBinder> { let data = FunctionSignature::of(db, def); let resolver = def.resolver(db); let interner = DbInterner::new_no_crate(db); diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index 9e0188fd2604..6418b3e6a924 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -122,7 +122,7 @@ pub enum CandidateSource { Trait(TraitId), } -impl<'a, 'db> InferenceContext<'a, 'db> { +impl<'db> InferenceContext<'db> { /// Performs method lookup. If lookup is successful, it will return the callee /// and store an appropriate adjustment for the self-expr. In some cases it may /// report an error (e.g., invoking the `drop` method). @@ -519,10 +519,10 @@ fn crates_containing_incoherent_inherent_impls(db: &dyn HirDatabase, krate: Crat krate.transitive_deps(db).into_iter().filter(|krate| krate.data(db).origin.is_lang()).collect() } -pub fn with_incoherent_inherent_impls( - db: &dyn HirDatabase, +pub fn with_incoherent_inherent_impls<'db>( + db: &'db dyn HirDatabase, krate: Crate, - self_ty: &SimplifiedType, + self_ty: &SimplifiedType<'db>, mut callback: impl FnMut(&[ImplId]), ) { let has_incoherent_impls = match self_ty.def() { @@ -544,7 +544,7 @@ pub fn with_incoherent_inherent_impls( } } -pub fn simplified_type_module(db: &dyn HirDatabase, ty: &SimplifiedType) -> Option { +pub fn simplified_type_module(db: &dyn HirDatabase, ty: &SimplifiedType<'_>) -> Option { match ty.def()? { SolverDefId::AdtId(id) => Some(id.module(db)), SolverDefId::TypeAliasId(id) => Some(id.module(db)), @@ -554,14 +554,14 @@ pub fn simplified_type_module(db: &dyn HirDatabase, ty: &SimplifiedType) -> Opti } #[derive(Debug, PartialEq, Eq)] -pub struct InherentImpls { - map: FxHashMap>, +pub struct InherentImpls<'db> { + map: FxHashMap, Box<[ImplId]>>, } #[salsa::tracked] -impl InherentImpls { +impl<'db> InherentImpls<'db> { #[salsa::tracked(returns(ref))] - pub fn for_crate(db: &dyn HirDatabase, krate: Crate) -> Self { + pub fn for_crate(db: &'db dyn HirDatabase, krate: Crate) -> InherentImpls<'db> { let _p = tracing::info_span!("inherent_impls_in_crate_query", ?krate).entered(); let crate_def_map = crate_def_map(db, krate); @@ -570,7 +570,7 @@ impl InherentImpls { } #[salsa::tracked(returns(ref))] - pub fn for_block(db: &dyn HirDatabase, block: BlockId) -> Option> { + pub fn for_block(db: &'db dyn HirDatabase, block: BlockId) -> Option>> { let _p = tracing::info_span!("inherent_impls_in_block_query").entered(); let block_def_map = block_def_map(db, block); @@ -579,8 +579,8 @@ impl InherentImpls { } } -impl InherentImpls { - fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap) -> Self { +impl<'db> InherentImpls<'db> { + fn collect_def_map(db: &'db dyn HirDatabase, def_map: &'db DefMap) -> Self { let mut map = FxHashMap::default(); collect(db, def_map, &mut map); let mut map = map @@ -590,10 +590,10 @@ impl InherentImpls { map.shrink_to_fit(); return Self { map }; - fn collect( - db: &dyn HirDatabase, + fn collect<'db>( + db: &'db dyn HirDatabase, def_map: &DefMap, - map: &mut FxHashMap>, + map: &mut FxHashMap, Vec>, ) { for (_module_id, module_data) in def_map.modules() { for impl_id in module_data.scope.inherent_impls() { @@ -619,15 +619,15 @@ impl InherentImpls { } } - pub fn for_self_ty(&self, self_ty: &SimplifiedType) -> &[ImplId] { + pub fn for_self_ty(&self, self_ty: &SimplifiedType<'db>) -> &[ImplId] { self.map.get(self_ty).map(|it| &**it).unwrap_or_default() } pub fn for_each_crate_and_block( - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, krate: Crate, block: Option, - for_each: &mut dyn FnMut(&InherentImpls), + for_each: &mut dyn FnMut(&InherentImpls<'db>), ) { let blocks = std::iter::successors(block, |block| block.loc(db).module.block(db)); blocks.filter_map(|block| Self::for_block(db, block).as_deref()).for_each(&mut *for_each); @@ -636,19 +636,19 @@ impl InherentImpls { } #[derive(Debug, PartialEq)] -struct OneTraitImpls { - non_blanket_impls: FxHashMap, Box<[BuiltinDeriveImplId]>)>, +struct OneTraitImpls<'db> { + non_blanket_impls: FxHashMap, (Box<[ImplId]>, Box<[BuiltinDeriveImplId]>)>, blanket_impls: Box<[ImplId]>, } #[derive(Default)] -struct OneTraitImplsBuilder { - non_blanket_impls: FxHashMap, Vec)>, +struct OneTraitImplsBuilder<'db> { + non_blanket_impls: FxHashMap, (Vec, Vec)>, blanket_impls: Vec, } -impl OneTraitImplsBuilder { - fn finish(self) -> OneTraitImpls { +impl<'db> OneTraitImplsBuilder<'db> { + fn finish(self) -> OneTraitImpls<'db> { let mut non_blanket_impls = self .non_blanket_impls .into_iter() @@ -663,14 +663,14 @@ impl OneTraitImplsBuilder { } #[derive(Debug, PartialEq)] -pub struct TraitImpls { - map: FxHashMap, +pub struct TraitImpls<'db> { + map: FxHashMap>, } #[salsa::tracked] -impl TraitImpls { +impl<'db> TraitImpls<'db> { #[salsa::tracked(returns(ref))] - pub fn for_crate(db: &dyn HirDatabase, krate: Crate) -> Arc { + pub fn for_crate(db: &'db dyn HirDatabase, krate: Crate) -> Arc> { let _p = tracing::info_span!("inherent_impls_in_crate_query", ?krate).entered(); let crate_def_map = crate_def_map(db, krate); @@ -679,7 +679,7 @@ impl TraitImpls { } #[salsa::tracked(returns(ref))] - pub fn for_block(db: &dyn HirDatabase, block: BlockId) -> Option> { + pub fn for_block(db: &'db dyn HirDatabase, block: BlockId) -> Option>> { let _p = tracing::info_span!("inherent_impls_in_block_query").entered(); let block_def_map = block_def_map(db, block); @@ -693,8 +693,8 @@ impl TraitImpls { } } -impl TraitImpls { - fn collect_def_map(db: &dyn HirDatabase, def_map: &DefMap) -> Self { +impl<'db> TraitImpls<'db> { + fn collect_def_map(db: &'db dyn HirDatabase, def_map: &DefMap) -> Self { let lang_items = hir_def::lang_item::lang_items(db, def_map.krate()); let mut map = FxHashMap::default(); collect(db, def_map, lang_items, &mut map); @@ -705,11 +705,11 @@ impl TraitImpls { map.shrink_to_fit(); return Self { map }; - fn collect( - db: &dyn HirDatabase, + fn collect<'db>( + db: &'db dyn HirDatabase, def_map: &DefMap, lang_items: &LangItems, - map: &mut FxHashMap, + map: &mut FxHashMap>, ) { for (_module_id, module_data) in def_map.modules() { for impl_id in module_data.scope.trait_impls() { @@ -770,7 +770,7 @@ impl TraitImpls { pub fn has_impls_for_trait_and_self_ty( &self, trait_: TraitId, - self_ty: &SimplifiedType, + self_ty: &SimplifiedType<'db>, ) -> bool { self.map.get(&trait_).is_some_and(|trait_impls| { trait_impls.non_blanket_impls.contains_key(self_ty) @@ -779,10 +779,10 @@ impl TraitImpls { } pub fn for_trait_and_self_ty( - &self, + &'db self, trait_: TraitId, - self_ty: &SimplifiedType, - ) -> (&[ImplId], &[BuiltinDeriveImplId]) { + self_ty: &SimplifiedType<'db>, + ) -> (&'db [ImplId], &'db [BuiltinDeriveImplId]) { self.map .get(&trait_) .and_then(|map| map.non_blanket_impls.get(self_ty)) @@ -806,7 +806,7 @@ impl TraitImpls { pub fn for_self_ty( &self, - self_ty: &SimplifiedType, + self_ty: &SimplifiedType<'db>, mut callback: impl FnMut(Either<&[ImplId], &[BuiltinDeriveImplId]>), ) { for for_trait in self.map.values() { @@ -818,10 +818,10 @@ impl TraitImpls { } pub fn for_each_crate_and_block( - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, krate: Crate, block: Option, - for_each: &mut dyn FnMut(&TraitImpls), + for_each: &mut dyn FnMut(&TraitImpls<'db>), ) { let blocks = std::iter::successors(block, |block| block.loc(db).module.block(db)); blocks.filter_map(|block| Self::for_block(db, block).as_deref()).for_each(&mut *for_each); @@ -830,11 +830,11 @@ impl TraitImpls { /// Like [`Self::for_each_crate_and_block()`], but takes in account two blocks, one for a trait and one for a self type. pub fn for_each_crate_and_block_trait_and_type( - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, krate: Crate, type_block: Option, trait_block: Option, - for_each: &mut dyn FnMut(&TraitImpls), + for_each: &mut dyn FnMut(&TraitImpls<'db>), ) { let in_self_and_deps = TraitImpls::for_crate_and_deps(db, krate); in_self_and_deps.iter().for_each(|impls| for_each(impls)); diff --git a/crates/hir-ty/src/method_resolution/confirm.rs b/crates/hir-ty/src/method_resolution/confirm.rs index d960a6547d46..6d948464b1c0 100644 --- a/crates/hir-ty/src/method_resolution/confirm.rs +++ b/crates/hir-ty/src/method_resolution/confirm.rs @@ -36,8 +36,8 @@ use crate::{ }, }; -struct ConfirmContext<'a, 'b, 'db> { - ctx: &'a mut InferenceContext<'b, 'db>, +struct ConfirmContext<'a, 'db> { + ctx: &'a mut InferenceContext<'db>, candidate: FunctionId, call_expr: ExprId, } @@ -49,7 +49,7 @@ pub(crate) struct ConfirmResult<'db> { pub(crate) adjustments: Box<[Adjustment]>, } -impl<'a, 'db> InferenceContext<'a, 'db> { +impl<'db> InferenceContext<'db> { pub(crate) fn confirm_method( &mut self, pick: &probe::Pick<'db>, @@ -70,12 +70,12 @@ impl<'a, 'db> InferenceContext<'a, 'db> { } } -impl<'a, 'b, 'db> ConfirmContext<'a, 'b, 'db> { +impl<'a, 'db> ConfirmContext<'a, 'db> { fn new( - ctx: &'a mut InferenceContext<'b, 'db>, + ctx: &'a mut InferenceContext<'db>, candidate: FunctionId, call_expr: ExprId, - ) -> ConfirmContext<'a, 'b, 'db> { + ) -> ConfirmContext<'a, 'db> { ConfirmContext { ctx, candidate, call_expr } } @@ -312,7 +312,7 @@ impl<'a, 'b, 'db> ConfirmContext<'a, 'b, 'db> { fn extract_existential_trait_ref(&self, self_ty: Ty<'db>, mut closure: F) -> R where - F: FnMut(&ConfirmContext<'a, 'b, 'db>, Ty<'db>, PolyExistentialTraitRef<'db>) -> R, + F: FnMut(&ConfirmContext<'a, 'db>, Ty<'db>, PolyExistentialTraitRef<'db>) -> R, { // If we specified that this is an object method, then the // self-type ought to be something that can be dereferenced to @@ -348,13 +348,13 @@ impl<'a, 'b, 'db> ConfirmContext<'a, 'b, 'db> { generic_args: Option<&HirGenericArgs>, parent_args: GenericArgs<'db>, ) -> GenericArgs<'db> { - struct LowererCtx<'a, 'b, 'db> { - ctx: &'a mut InferenceContext<'b, 'db>, + struct LowererCtx<'a, 'db> { + ctx: &'a mut InferenceContext<'db>, expr: ExprId, parent_args: &'a [GenericArg<'db>], } - impl<'db> GenericArgsLowerer<'db> for LowererCtx<'_, '_, 'db> { + impl<'db> GenericArgsLowerer<'db> for LowererCtx<'_, 'db> { fn report_len_mismatch( &mut self, def: GenericDefId, diff --git a/crates/hir-ty/src/method_resolution/probe.rs b/crates/hir-ty/src/method_resolution/probe.rs index 84edb510237d..ee8537d4d4d4 100644 --- a/crates/hir-ty/src/method_resolution/probe.rs +++ b/crates/hir-ty/src/method_resolution/probe.rs @@ -993,7 +993,7 @@ impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> { fn assemble_inherent_impl_candidates_for_type( &mut self, - self_ty: &SimplifiedType, + self_ty: &SimplifiedType<'db>, receiver_steps: usize, ) { let Some(module) = simplified_type_module(self.db(), self_ty) else { diff --git a/crates/hir-ty/src/mir.rs b/crates/hir-ty/src/mir.rs index d004e3b5daef..54232191e3e0 100644 --- a/crates/hir-ty/src/mir.rs +++ b/crates/hir-ty/src/mir.rs @@ -15,6 +15,7 @@ use rustc_type_ir::{ CollectAndApply, GenericTypeVisitable, inherent::{GenericArgs as _, IntoKind, Ty as _}, }; +use salsa::Update; use smallvec::{SmallVec, smallvec}; use stdx::impl_from; @@ -318,7 +319,12 @@ impl<'db> PlaceRef<'db> { pub fn store(&self) -> Place { Place { local: self.local, projection: self.projection.store() } } - pub fn ty(&self, body: &MirBody, infcx: &InferCtxt<'db>, env: ParamEnv<'db>) -> PlaceTy<'db> { + pub fn ty( + &self, + body: &MirBody<'db>, + infcx: &InferCtxt<'db>, + env: ParamEnv<'db>, + ) -> PlaceTy<'db> { PlaceTy::from_ty(body.locals[self.local].ty.as_ref()).multi_projection_ty( infcx, env, @@ -1059,21 +1065,21 @@ pub struct BasicBlock { pub is_cleanup: bool, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct MirBody { +#[derive(Debug, Clone, PartialEq, Eq, Update)] +pub struct MirBody<'db> { pub basic_blocks: Arena, pub locals: Arena, pub start_block: BasicBlockId, - pub owner: InferBodyId, + pub owner: InferBodyId<'db>, pub binding_locals: ArenaMap, pub upvar_locals: FxHashMap>, pub param_locals: Vec, /// This field stores the closures directly owned by this body. It is used /// in traversing every mir body. - pub closures: Vec, + pub closures: Vec>, } -impl MirBody { +impl MirBody<'_> { pub fn local_to_binding_map(&self) -> ArenaMap { self.binding_locals.iter().map(|(it, y)| (*y, it)).collect() } diff --git a/crates/hir-ty/src/mir/borrowck.rs b/crates/hir-ty/src/mir/borrowck.rs index c5367f630e1a..c19a3337258f 100644 --- a/crates/hir-ty/src/mir/borrowck.rs +++ b/crates/hir-ty/src/mir/borrowck.rs @@ -9,6 +9,7 @@ use either::Either; use hir_def::HasModule; use la_arena::ArenaMap; use rustc_hash::FxHashMap; +use salsa::Update; use stdx::never; use crate::{ @@ -56,17 +57,17 @@ pub struct BorrowRegion { pub places: Vec, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BorrowckResult { - owner: Either, +#[derive(Debug, Clone, PartialEq, Eq, Update)] +pub struct BorrowckResult<'db> { + owner: Either, InternedClosureId<'db>>, pub mutability_of_locals: ArenaMap, pub moved_out_of_ref: Vec, pub partially_moved: Vec, pub borrow_regions: Vec, } -impl BorrowckResult { - pub fn mir_body<'db>(&self, db: &'db dyn HirDatabase) -> &'db MirBody { +impl<'db> BorrowckResult<'db> { + pub fn mir_body(&self, db: &'db dyn HirDatabase) -> &'db MirBody<'db> { match self.owner { Either::Left(it) => db.mir_body(it).unwrap(), Either::Right(it) => db.mir_body_for_closure(it).unwrap(), @@ -76,23 +77,29 @@ impl BorrowckResult { fn all_mir_bodies<'db>( db: &'db dyn HirDatabase, - def: InferBodyId, - mut cb: impl FnMut(&'db MirBody, Either) -> BorrowckResult, + def: InferBodyId<'db>, + mut cb: impl FnMut( + &'db MirBody<'db>, + Either, InternedClosureId<'db>>, + ) -> BorrowckResult<'db>, mut merge_from_closures: impl FnMut( - (&mut BorrowckResult, &'db MirBody), - (&BorrowckResult, &'db MirBody), + (&mut BorrowckResult<'db>, &'db MirBody<'db>), + (&BorrowckResult<'db>, &'db MirBody<'db>), ), -) -> Result, MirLowerError> { +) -> Result]>, MirLowerError<'db>> { fn for_closure<'db>( db: &'db dyn HirDatabase, - c: InternedClosureId, - results: &mut Vec<(BorrowckResult, &'db MirBody)>, - cb: &mut impl FnMut(&'db MirBody, Either) -> BorrowckResult, + c: InternedClosureId<'db>, + results: &mut Vec<(BorrowckResult<'db>, &'db MirBody<'db>)>, + cb: &mut impl FnMut( + &'db MirBody<'db>, + Either, InternedClosureId<'db>>, + ) -> BorrowckResult<'db>, merge_from_closures: &mut impl FnMut( - (&mut BorrowckResult, &'db MirBody), - (&BorrowckResult, &'db MirBody), + (&mut BorrowckResult<'db>, &'db MirBody<'db>), + (&BorrowckResult<'db>, &'db MirBody<'db>), ), - ) -> Result<(), MirLowerError> { + ) -> Result<(), MirLowerError<'db>> { match db.mir_body_for_closure(c) { Ok(body) => { let parent_index = results.len(); @@ -108,8 +115,11 @@ fn all_mir_bodies<'db>( } fn merge<'db>( - results: &mut [(BorrowckResult, &'db MirBody)], - merge: &mut impl FnMut((&mut BorrowckResult, &'db MirBody), (&BorrowckResult, &'db MirBody)), + results: &mut [(BorrowckResult<'db>, &'db MirBody<'db>)], + merge: &mut impl FnMut( + (&mut BorrowckResult<'db>, &'db MirBody<'db>), + (&BorrowckResult<'db>, &'db MirBody<'db>), + ), parent_index: usize, ) { let (parent_and_before, children) = results.split_at_mut(parent_index + 1); @@ -134,10 +144,10 @@ fn all_mir_bodies<'db>( } #[salsa_macros::tracked(returns(ref), lru = 2024)] -pub fn borrowck_query( - db: &dyn HirDatabase, - def: InferBodyId, -) -> Result, MirLowerError> { +pub fn borrowck_query<'db>( + db: &'db dyn HirDatabase, + def: InferBodyId<'db>, +) -> Result]>, MirLowerError<'db>> { let _p = tracing::info_span!("borrowck_query").entered(); let module = def.module(db); let interner = DbInterner::new_with(db, module.krate(db)); @@ -191,7 +201,7 @@ pub fn borrowck_query( fn moved_out_of_ref<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, ) -> Vec { let db = infcx.interner.db; let mut result = vec![]; @@ -286,7 +296,7 @@ fn moved_out_of_ref<'db>( fn partially_moved<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, ) -> Vec { let db = infcx.interner.db; let mut result = vec![]; @@ -368,7 +378,7 @@ fn partially_moved<'db>( result } -fn borrow_regions(db: &dyn HirDatabase, body: &MirBody) -> Vec { +fn borrow_regions<'db>(db: &'db dyn HirDatabase, body: &MirBody<'db>) -> Vec { let mut borrows = FxHashMap::default(); for (_, block) in body.basic_blocks.iter() { db.unwind_if_revision_cancelled(); @@ -421,7 +431,7 @@ enum ProjectionCase { fn place_case<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, lvalue: &Place, ) -> ProjectionCase { let mut is_part_of = false; @@ -448,13 +458,13 @@ fn place_case<'db>( /// `Uninit` and `drop` and similar after initialization. fn ever_initialized_map( db: &dyn HirDatabase, - body: &MirBody, + body: &MirBody<'_>, ) -> ArenaMap> { let mut result: ArenaMap> = body.basic_blocks.iter().map(|it| (it.0, ArenaMap::default())).collect(); fn dfs( db: &dyn HirDatabase, - body: &MirBody, + body: &MirBody<'_>, l: LocalId, stack: &mut Vec, result: &mut ArenaMap>, @@ -567,7 +577,7 @@ fn record_usage_for_operand(arg: &Operand, result: &mut ArenaMap( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, ) -> ArenaMap { let db = infcx.interner.db; let mut result: ArenaMap = diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index eb0e4c60200f..ba138835cf9c 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -31,6 +31,7 @@ use rustc_type_ir::{ AliasTyKind, inherent::{GenericArgs as _, IntoKind, Region as _, SliceLike, Ty as _}, }; +use salsa::Update; use span::FileId; use stdx::never; use syntax::{SyntaxNodePtr, TextRange}; @@ -155,16 +156,16 @@ impl TlsData { } } -struct StackFrame<'a> { - locals: Locals<'a>, +struct StackFrame<'a, 'db> { + locals: Locals<'a, 'db>, destination: Option, prev_stack_ptr: usize, - span: (MirSpan, InferBodyId), + span: (MirSpan, InferBodyId<'db>), } #[derive(Clone)] -enum MirOrDynIndex<'a> { - Mir(&'a MirBody), +enum MirOrDynIndex<'db> { + Mir(&'db MirBody<'db>), Dyn(usize), } @@ -174,7 +175,7 @@ pub struct Evaluator<'a, 'db> { target_data_layout: &'db TargetDataLayout, stack: Vec, heap: Vec, - code_stack: Vec>, + code_stack: Vec>, /// Stores the global location of the statics. We const evaluate every static first time we need it /// and see it's missing, then we add it to this to reuse. static_locations: FxHashMap, @@ -189,11 +190,11 @@ pub struct Evaluator<'a, 'db> { layout_cache: RefCell, Arc>>, projected_ty_cache: RefCell, PlaceElem), PlaceTy<'db>>>, not_special_fn_cache: RefCell>, - mir_or_dyn_index_cache: RefCell), MirOrDynIndex<'a>>>, + mir_or_dyn_index_cache: RefCell), MirOrDynIndex<'db>>>, /// Constantly dropping and creating `Locals` is very costly. We store /// old locals that we normally want to drop here, to reuse their allocations /// later. - unused_locals_store: RefCell>>>, + unused_locals_store: RefCell, Vec>>>, cached_ptr_size: usize, cached_fn_trait_func: Option, cached_fn_mut_trait_func: Option, @@ -236,11 +237,11 @@ impl Interval { Self { addr, size } } - fn get<'b, 'a, 'db: 'a>(&self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> { + fn get<'b, 'a, 'db>(&self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> { memory.read_memory(self.addr, self.size) } - fn write_from_bytes<'a, 'db: 'a>( + fn write_from_bytes<'a, 'db>( &self, memory: &mut Evaluator<'a, 'db>, bytes: &[u8], @@ -248,7 +249,7 @@ impl Interval { memory.write_memory(self.addr, bytes) } - fn write_from_interval<'a, 'db: 'a>( + fn write_from_interval<'a, 'db>( &self, memory: &mut Evaluator<'a, 'db>, interval: Interval, @@ -262,10 +263,7 @@ impl Interval { } impl<'db> IntervalAndTy<'db> { - fn get<'b, 'a>(&self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> - where - 'db: 'a, - { + fn get<'b, 'a>(&self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> { memory.read_memory(self.interval.addr, self.interval.size) } @@ -273,11 +271,8 @@ impl<'db> IntervalAndTy<'db> { addr: Address, ty: Ty<'db>, evaluator: &Evaluator<'a, 'db>, - locals: &Locals<'a>, - ) -> Result<'db, IntervalAndTy<'db>> - where - 'db: 'a, - { + locals: &Locals<'a, 'db>, + ) -> Result<'db, IntervalAndTy<'db>> { let size = evaluator.size_of_sized(ty, locals, "type of interval")?; Ok(IntervalAndTy { interval: Interval { addr, size }, ty }) } @@ -295,7 +290,7 @@ impl From for IntervalOrOwned { } impl IntervalOrOwned { - fn get<'b, 'a, 'db: 'a>(&'b self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> { + fn get<'b, 'a, 'db>(&'b self, memory: &'b Evaluator<'a, 'db>) -> Result<'db, &'b [u8]> { Ok(match self { IntervalOrOwned::Owned(o) => o, IntervalOrOwned::Borrowed(b) => b.get(memory)?, @@ -354,9 +349,9 @@ impl Address { } } -#[derive(Clone, PartialEq, Eq)] -pub enum MirEvalError { - ConstEvalError(String, Box), +#[derive(Clone, PartialEq, Eq, Update)] +pub enum MirEvalError<'db> { + ConstEvalError(String, Box>), LayoutError(LayoutError, StoredTy), TargetDataLayoutNotAvailable(TargetLoadError), /// Means that code had undefined behavior. We don't try to actively detect UB, but if it was detected @@ -364,14 +359,15 @@ pub enum MirEvalError { UndefinedBehavior(String), Panic(String), // FIXME: This should be folded into ConstEvalError? - MirLowerError(FunctionId, MirLowerError), - MirLowerErrorForClosure(InternedClosureId, MirLowerError), + MirLowerError(FunctionId, MirLowerError<'db>), + MirLowerErrorForClosure(InternedClosureId<'db>, MirLowerError<'db>), TypeIsUnsized(StoredTy, &'static str), NotSupported(String), InvalidConst, InFunction( - Box, - Vec<(Either, MirSpan, InferBodyId)>, + Box>, + #[update(unsafe(with ( |a,b| todo!())))] + Vec<(Either>, MirSpan, InferBodyId<'db>)>, ), ExecutionLimitExceeded, StackOverflow, @@ -383,7 +379,7 @@ pub enum MirEvalError { InternalError(Box), } -impl MirEvalError { +impl MirEvalError<'_> { pub fn pretty_print( &self, f: &mut String, @@ -420,18 +416,18 @@ impl MirEvalError { (store, None) } }; - let span: InFile = match span { - MirSpan::ExprId(e) => match source_map.expr_syntax(*e) { + let span: InFile = match *span { + MirSpan::ExprId(e) => match source_map.expr_syntax(e) { Ok(s) => s.map(|it| it.into()), Err(_) => continue, }, - MirSpan::PatId(p) => match source_map.pat_syntax(*p) { + MirSpan::PatId(p) => match source_map.pat_syntax(p) { Ok(s) => s.map(|it| it.syntax_node_ptr()), Err(_) => continue, }, MirSpan::BindingId(b) => { match source_map - .patterns_for_binding(*b) + .patterns_for_binding(b) .iter() .find_map(|p| source_map.pat_syntax(*p).ok()) { @@ -525,7 +521,7 @@ impl MirEvalError { } } -impl std::fmt::Debug for MirEvalError { +impl std::fmt::Debug for MirEvalError<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::ConstEvalError(arg0, arg1) => { @@ -564,7 +560,7 @@ impl std::fmt::Debug for MirEvalError { } } -type Result<'db, T> = std::result::Result; +type Result<'db, T> = std::result::Result>; #[derive(Debug, Default)] struct DropFlags<'db> { @@ -595,9 +591,9 @@ impl<'db> DropFlags<'db> { } #[derive(Debug)] -struct Locals<'a> { +struct Locals<'a, 'db> { ptr: ArenaMap, - body: &'a MirBody, + body: &'db MirBody<'db>, drop_flags: DropFlags<'a>, } @@ -615,9 +611,9 @@ impl MirOutput { } } -pub fn interpret_mir<'a, 'db: 'a>( +pub fn interpret_mir<'db>( db: &'db dyn HirDatabase, - body: &MirBody, + body: &'db MirBody<'db>, // FIXME: This is workaround. Ideally, const generics should have a separate body (issue #7434), but now // they share their body with their parent, so in MIR lowering we have locals of the parent body, which // might have placeholders. With this argument, we (wrongly) assume that every placeholder type has @@ -657,10 +653,10 @@ const EXECUTION_LIMIT: usize = 100_000; #[cfg(not(test))] const EXECUTION_LIMIT: usize = 10_000_000; -impl<'a, 'db: 'a> Evaluator<'a, 'db> { +impl<'a, 'db> Evaluator<'a, 'db> { pub fn new( db: &'db dyn HirDatabase, - owner: InferBodyId, + owner: InferBodyId<'db>, assert_placeholder_ty_is_unused: bool, trait_env: Option>, ) -> Result<'db, Evaluator<'a, 'db>> { @@ -718,11 +714,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { self.infcx.interner.lang_items() } - fn place_addr(&self, p: &Place, locals: &Locals<'a>) -> Result<'db, Address> { + fn place_addr(&self, p: &Place, locals: &Locals<'a, 'db>) -> Result<'db, Address> { Ok(self.place_addr_and_ty_and_metadata(p, locals)?.0) } - fn place_interval(&self, p: &Place, locals: &Locals<'a>) -> Result<'db, Interval> { + fn place_interval(&self, p: &Place, locals: &Locals<'a, 'db>) -> Result<'db, Interval> { let place_addr_and_ty = self.place_addr_and_ty_and_metadata(p, locals)?; Ok(Interval { addr: place_addr_and_ty.0, @@ -752,7 +748,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn place_addr_and_ty_and_metadata<'b>( &'b self, p: &Place, - locals: &'b Locals<'a>, + locals: &'b Locals<'a, 'db>, ) -> Result<'db, (Address, Ty<'db>, Option)> { let mut addr = locals.ptr[p.local].addr; let mut ty = PlaceTy::from_ty(locals.body.locals[p.local].ty.as_ref()); @@ -873,11 +869,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { self.layout(Ty::new_adt(self.interner(), adt, subst)) } - fn place_ty<'b>(&'b self, p: &Place, locals: &'b Locals<'a>) -> Result<'db, Ty<'db>> { + fn place_ty<'b>(&'b self, p: &Place, locals: &'b Locals<'a, 'db>) -> Result<'db, Ty<'db>> { Ok(self.place_addr_and_ty_and_metadata(p, locals)?.1) } - fn operand_ty(&self, o: &Operand, locals: &Locals<'a>) -> Result<'db, Ty<'db>> { + fn operand_ty(&self, o: &Operand, locals: &Locals<'a, 'db>) -> Result<'db, Ty<'db>> { Ok(match &o.kind { OperandKind::Copy(p) | OperandKind::Move(p) => self.place_ty(p, locals)?, OperandKind::Constant { konst: _, ty } => ty.as_ref(), @@ -898,7 +894,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn operand_ty_and_eval( &mut self, o: &Operand, - locals: &mut Locals<'a>, + locals: &mut Locals<'a, 'db>, ) -> Result<'db, IntervalAndTy<'db>> { Ok(IntervalAndTy { interval: self.eval_operand(o, locals)?, @@ -908,7 +904,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn interpret_mir( &mut self, - body: &'a MirBody, + body: &'db MirBody<'db>, args: impl Iterator, ) -> Result<'db, Interval> { if let Some(it) = self.stack_depth_limit.checked_sub(1) { @@ -1070,8 +1066,8 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn fill_locals_for_body( &mut self, - body: &MirBody, - locals: &mut Locals<'a>, + body: &'db MirBody<'db>, + locals: &mut Locals<'a, 'db>, args: impl Iterator, ) -> Result<'db, ()> { let mut remain_args = body.param_locals.len(); @@ -1094,9 +1090,9 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn create_locals_for_body( &mut self, - body: &'a MirBody, + body: &'db MirBody<'db>, destination: Option, - ) -> Result<'db, (Locals<'a>, usize)> { + ) -> Result<'db, (Locals<'a, 'db>, usize)> { let mut locals = match self.unused_locals_store.borrow_mut().entry(body.owner).or_default().pop() { None => Locals { ptr: ArenaMap::new(), body, drop_flags: DropFlags::default() }, @@ -1139,7 +1135,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { Ok((locals, prev_stack_pointer)) } - fn eval_rvalue(&mut self, r: &Rvalue, locals: &mut Locals<'a>) -> Result<'db, IntervalOrOwned> { + fn eval_rvalue( + &mut self, + r: &Rvalue, + locals: &mut Locals<'a, 'db>, + ) -> Result<'db, IntervalOrOwned> { use IntervalOrOwned::*; Ok(match r { Rvalue::Use(it) => Borrowed(self.eval_operand(it, locals)?), @@ -1804,7 +1804,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { &mut self, it: VariantId, subst: GenericArgs<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, ) -> Result<'db, (usize, Arc, Option<(usize, usize, i128)>)> { let adt = it.adt_id(self.db); if let Some(f) = locals.body.owner.as_variant() @@ -1897,7 +1897,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { Ok(result) } - fn eval_operand(&mut self, it: &Operand, locals: &mut Locals<'a>) -> Result<'db, Interval> { + fn eval_operand( + &mut self, + it: &Operand, + locals: &mut Locals<'a, 'db>, + ) -> Result<'db, Interval> { Ok(match &it.kind { OperandKind::Copy(p) | OperandKind::Move(p) => { locals.drop_flags.remove_place(p.as_ref()); @@ -2050,7 +2054,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { #[allow(clippy::double_parens)] fn allocate_const_in_heap( &mut self, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, konst: Const<'db>, ) -> Result<'db, Interval> { match konst.kind() { @@ -2092,7 +2096,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn allocate_allocation_in_heap( &mut self, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, allocation: Allocation<'db>, ) -> Result<'db, Interval> { let AllocationData { ty, memory: ref v, ref memory_map } = *allocation; @@ -2131,7 +2135,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { Ok(Interval::new(addr, size)) } - fn eval_place(&mut self, p: &Place, locals: &Locals<'a>) -> Result<'db, Interval> { + fn eval_place(&mut self, p: &Place, locals: &Locals<'a, 'db>) -> Result<'db, Interval> { let addr = self.place_addr(p, locals)?; Ok(Interval::new( addr, @@ -2234,7 +2238,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn size_align_of( &self, ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, ) -> Result<'db, Option<(usize, usize)>> { if let Some(layout) = self.layout_cache.borrow().get(&ty) { return Ok(layout @@ -2264,7 +2268,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn size_of_sized( &self, ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, what: &'static str, ) -> Result<'db, usize> { match self.size_align_of(ty, locals)? { @@ -2278,7 +2282,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn size_align_of_sized( &self, ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, what: &'static str, ) -> Result<'db, (usize, usize)> { match self.size_align_of(ty, locals)? { @@ -2319,13 +2323,13 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { &self, bytes: &[u8], ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, ) -> Result<'db, ComplexMemoryMap<'db>> { - fn rec<'a, 'db: 'a>( + fn rec<'a, 'db>( this: &Evaluator<'a, 'db>, bytes: &[u8], ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, mm: &mut ComplexMemoryMap<'db>, stack_depth_limit: usize, ) -> Result<'db, ()> { @@ -2500,7 +2504,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { ty_of_bytes: impl Fn(&[u8]) -> Result<'db, Ty<'db>> + Copy, addr: Address, ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, ) -> Result<'db, ()> { // FIXME: support indirect references let layout = self.layout(ty)?; @@ -2632,10 +2636,10 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { bytes: Interval, destination: Interval, args: &[IntervalAndTy<'db>], - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, target_bb: Option, span: MirSpan, - ) -> Result<'db, Option>> { + ) -> Result<'db, Option>> { let id = from_bytes!(usize, bytes.get(self)?); let next_ty = self.vtable_map.ty(id)?; use rustc_type_ir::TyKind; @@ -2658,14 +2662,14 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn exec_closure( &mut self, - closure: InternedClosureId, + closure: InternedClosureId<'db>, closure_data: Interval, generic_args: GenericArgs<'db>, destination: Interval, args: &[IntervalAndTy<'db>], - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, span: MirSpan, - ) -> Result<'db, Option>> { + ) -> Result<'db, Option>> { let mir_body = self .db .monomorphized_mir_body_for_closure( @@ -2701,10 +2705,10 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { generic_args: GenericArgs<'db>, destination: Interval, args: &[IntervalAndTy<'db>], - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, target_bb: Option, span: MirSpan, - ) -> Result<'db, Option>> { + ) -> Result<'db, Option>> { match def { CallableDefId::FunctionId(def) => { if self.detect_fn_trait(def).is_some() { @@ -2759,9 +2763,9 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { &self, def: FunctionId, generic_args: GenericArgs<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, span: MirSpan, - ) -> Result<'db, MirOrDynIndex<'a>> { + ) -> Result<'db, MirOrDynIndex<'db>> { let pair = (def, generic_args); if let Some(r) = self.mir_or_dyn_index_cache.borrow().get(&pair) { return Ok(r.clone()); @@ -2801,11 +2805,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { mut def: FunctionId, args: &[IntervalAndTy<'db>], generic_args: GenericArgs<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, destination: Interval, target_bb: Option, span: MirSpan, - ) -> Result<'db, Option>> { + ) -> Result<'db, Option>> { if self.detect_and_exec_special_function( def, args, @@ -2867,20 +2871,20 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn exec_looked_up_function( &mut self, - mir_body: &'a MirBody, - locals: &Locals<'a>, + mir_body: &'db MirBody<'db>, + locals: &Locals<'a, 'db>, def: FunctionId, arg_bytes: impl Iterator, span: MirSpan, destination: Interval, target_bb: Option, - ) -> Result<'db, Option>> { - Ok(if let Some(target_bb) = target_bb { + ) -> Result<'db, Option>> { + if let Some(target_bb) = target_bb { let (mut locals, prev_stack_ptr) = self.create_locals_for_body(mir_body, Some(destination))?; self.fill_locals_for_body(mir_body, &mut locals, arg_bytes.into_iter())?; let span = (span, locals.body.owner); - Some(StackFrame { locals, destination: Some(target_bb), prev_stack_ptr, span }) + Ok(Some(StackFrame { locals, destination: Some(target_bb), prev_stack_ptr, span })) } else { let result = self.interpret_mir(mir_body, arg_bytes).map_err(|e| { MirEvalError::InFunction( @@ -2889,8 +2893,8 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { ) })?; destination.write_from_interval(self, result)?; - None - }) + Ok(None) + } } fn exec_fn_trait( @@ -2898,11 +2902,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { def: FunctionId, args: &[IntervalAndTy<'db>], generic_args: GenericArgs<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, destination: Interval, target_bb: Option, span: MirSpan, - ) -> Result<'db, Option>> { + ) -> Result<'db, Option>> { let func = args .first() .ok_or_else(|| MirEvalError::InternalError("fn trait with no arg".into()))?; @@ -2967,7 +2971,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { } } - fn eval_static(&mut self, st: StaticId, locals: &Locals<'a>) -> Result<'db, Address> { + fn eval_static(&mut self, st: StaticId, locals: &Locals<'a, 'db>) -> Result<'db, Address> { if let Some(o) = self.static_locations.get(&st) { return Ok(*o); }; @@ -2995,7 +2999,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn const_eval_discriminant(&self, variant: EnumVariantId) -> Result<'db, i128> { let r = self.db.const_eval_discriminant(variant); match r { - Ok(r) => Ok(r), + Ok(r) => Ok(r as i128), Err(e) => { let db = self.db; let loc = variant.lookup(db); @@ -3017,7 +3021,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn drop_place( &mut self, place: &Place, - locals: &mut Locals<'a>, + locals: &mut Locals<'a, 'db>, span: MirSpan, ) -> Result<'db, ()> { let (addr, ty, metadata) = self.place_addr_and_ty_and_metadata(place, locals)?; @@ -3034,7 +3038,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn run_drop_glue_deep( &mut self, ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, addr: Address, _metadata: &[u8], span: MirSpan, @@ -3138,7 +3142,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { pub fn render_const_using_debug_impl<'db>( db: &'db dyn HirDatabase, - owner: InferBodyId, + owner: InferBodyId<'db>, c: Allocation<'db>, ty: Ty<'db>, ) -> Result<'db, String> { diff --git a/crates/hir-ty/src/mir/eval/shim.rs b/crates/hir-ty/src/mir/eval/shim.rs index b59d6c1cfbe7..dc41f175720f 100644 --- a/crates/hir-ty/src/mir/eval/shim.rs +++ b/crates/hir-ty/src/mir/eval/shim.rs @@ -28,13 +28,13 @@ enum EvalLangItem { DropInPlace, } -impl<'a, 'db: 'a> Evaluator<'a, 'db> { +impl<'a, 'db> Evaluator<'a, 'db> { pub(super) fn detect_and_exec_special_function( &mut self, def: FunctionId, args: &[IntervalAndTy<'db>], generic_args: GenericArgs<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, destination: Interval, span: MirSpan, ) -> Result<'db, bool> { @@ -133,7 +133,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { def: FunctionId, args: &[IntervalAndTy<'db>], self_ty: Ty<'db>, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, destination: Interval, span: MirSpan, ) -> Result<'db, ()> { @@ -191,7 +191,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { layout: Arc, addr: Address, def: FunctionId, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, destination: Interval, span: MirSpan, ) -> Result<'db, ()> { @@ -297,7 +297,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { it: EvalLangItem, generic_args: GenericArgs<'db>, args: &[IntervalAndTy<'db>], - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, span: MirSpan, ) -> Result<'db, Vec> { use EvalLangItem::*; @@ -369,7 +369,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { id: i64, args: &[IntervalAndTy<'db>], destination: Interval, - _locals: &Locals<'a>, + _locals: &Locals<'a, 'db>, _span: MirSpan, ) -> Result<'db, ()> { match id { @@ -400,7 +400,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { args: &[IntervalAndTy<'db>], _generic_args: GenericArgs<'db>, destination: Interval, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, span: MirSpan, ) -> Result<'db, ()> { match as_str { @@ -564,7 +564,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { args: &[IntervalAndTy<'db>], generic_args: GenericArgs<'db>, destination: Interval, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, span: MirSpan, needs_override: bool, ) -> Result<'db, bool> { @@ -1342,7 +1342,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { &mut self, ty: Ty<'db>, metadata: Interval, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, ) -> Result<'db, (usize, usize)> { Ok(match ty.kind() { TyKind::Str => (from_bytes!(usize, metadata.get(self)?), 1), @@ -1402,7 +1402,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { args: &[IntervalAndTy<'db>], generic_args: GenericArgs<'db>, destination: Interval, - locals: &Locals<'a>, + locals: &Locals<'a, 'db>, _span: MirSpan, ) -> Result<'db, ()> { // We are a single threaded runtime with no UB checking and no optimization, so diff --git a/crates/hir-ty/src/mir/eval/shim/simd.rs b/crates/hir-ty/src/mir/eval/shim/simd.rs index a9d0bee62325..ff16ea68704d 100644 --- a/crates/hir-ty/src/mir/eval/shim/simd.rs +++ b/crates/hir-ty/src/mir/eval/shim/simd.rs @@ -6,7 +6,7 @@ use crate::consteval::try_const_usize; use super::*; -impl<'a, 'db: 'a> Evaluator<'a, 'db> { +impl<'a, 'db> Evaluator<'a, 'db> { fn detect_simd_ty(&self, ty: Ty<'db>) -> Result<'db, (usize, Ty<'db>)> { match ty.kind() { TyKind::Adt(adt_def, subst) => { @@ -54,7 +54,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { args: &[IntervalAndTy<'db>], _generic_args: GenericArgs<'db>, destination: Interval, - _locals: &Locals<'a>, + _locals: &Locals<'a, 'db>, _span: MirSpan, ) -> Result<'db, ()> { match name { diff --git a/crates/hir-ty/src/mir/eval/tests.rs b/crates/hir-ty/src/mir/eval/tests.rs index 0e94a5b92dd1..b57bea8bd48d 100644 --- a/crates/hir-ty/src/mir/eval/tests.rs +++ b/crates/hir-ty/src/mir/eval/tests.rs @@ -15,7 +15,7 @@ use crate::{ use super::{MirEvalError, interpret_mir}; -fn eval_main(db: &TestDB, file_id: EditionedFileId) -> Result<(String, String), MirEvalError> { +fn eval_main(db: &TestDB, file_id: EditionedFileId) -> Result<(String, String), MirEvalError<'_>> { crate::attach_db(db, || { let interner = DbInterner::new_no_crate(db); let module_id = db.module_for_file(file_id.file_id(db)); @@ -123,7 +123,7 @@ fn check_panic(#[rust_analyzer::rust_fixture] ra_fixture: &str, expected_panic: fn check_error_with( #[rust_analyzer::rust_fixture] ra_fixture: &str, - expect_err: impl FnOnce(MirEvalError) -> bool, + expect_err: impl FnOnce(MirEvalError<'_>) -> bool, ) { let (db, file_ids) = TestDB::with_many_files(ra_fixture); crate::attach_db(&db, || { diff --git a/crates/hir-ty/src/mir/lower.rs b/crates/hir-ty/src/mir/lower.rs index 4359a1acb51c..14c517e74d7f 100644 --- a/crates/hir-ty/src/mir/lower.rs +++ b/crates/hir-ty/src/mir/lower.rs @@ -23,6 +23,7 @@ use la_arena::{ArenaMap, RawIdx}; use rustc_apfloat::Float; use rustc_hash::FxHashMap; use rustc_type_ir::inherent::{Const as _, GenericArgs as _, IntoKind, Ty as _}; +use salsa::Update; use span::{Edition, FileId}; use syntax::TextRange; @@ -80,15 +81,15 @@ struct DropScope { } struct MirLowerCtx<'a, 'db> { - result: MirBody, - owner: InferBodyId, + result: MirBody<'db>, + owner: InferBodyId<'db>, store_owner: ExpressionStoreOwnerId, current_loop_blocks: Option, labeled_loop_blocks: FxHashMap, discr_temp: Option, db: &'db dyn HirDatabase, store: &'a ExpressionStore, - infer: &'a InferenceResult, + infer: &'a InferenceResult<'db>, types: &'db crate::next_solver::DefaultAny<'db>, resolver: Resolver<'db>, drop_scopes: Vec, @@ -97,9 +98,9 @@ struct MirLowerCtx<'a, 'db> { } // FIXME: Make this smaller, its stored in database queries -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum MirLowerError { - ConstEvalError(Box, Box), +#[derive(Debug, Clone, PartialEq, Eq, Update)] +pub enum MirLowerError<'db> { + ConstEvalError(Box, Box>), LayoutError(LayoutError), IncompleteExpr, IncompletePattern, @@ -110,7 +111,7 @@ pub enum MirLowerError { UnresolvedMethod(String), UnresolvedField, UnsizedTemporary(StoredTy), - MissingFunctionDefinition(InferBodyId, ExprId), + MissingFunctionDefinition(InferBodyId<'db>, ExprId), HasErrors, /// This should never happen. Type mismatch should catch everything. TypeError(&'static str), @@ -168,7 +169,7 @@ impl Drop for DropScopeToken { // } // } -impl MirLowerError { +impl MirLowerError<'_> { pub fn pretty_print( &self, f: &mut String, @@ -265,13 +266,13 @@ macro_rules! implementation_error { }}; } -impl From for MirLowerError { +impl From for MirLowerError<'_> { fn from(value: LayoutError) -> Self { MirLowerError::LayoutError(value) } } -impl MirLowerError { +impl MirLowerError<'_> { fn unresolved_path( db: &dyn HirDatabase, p: &Path, @@ -285,14 +286,14 @@ impl MirLowerError { } } -type Result<'db, T> = std::result::Result; +type Result<'db, T> = std::result::Result>; impl<'a, 'db> MirLowerCtx<'a, 'db> { fn new( db: &'db dyn HirDatabase, - owner: InferBodyId, + owner: InferBodyId<'db>, store: &'a ExpressionStore, - infer: &'a InferenceResult, + infer: &'a InferenceResult<'db>, ) -> Self { let mut basic_blocks = Arena::new(); let start_block = basic_blocks.alloc(BasicBlock { @@ -1528,7 +1529,7 @@ impl<'a, 'db> MirLowerCtx<'a, 'db> { fn lower_const( &mut self, - const_id: GeneralConstId, + const_id: GeneralConstId<'db>, prev_block: BasicBlockId, place: PlaceRef<'db>, subst: GenericArgs<'db>, @@ -1542,7 +1543,7 @@ impl<'a, 'db> MirLowerCtx<'a, 'db> { fn lower_const_to_operand( &mut self, subst: GenericArgs<'db>, - const_id: GeneralConstId, + const_id: GeneralConstId<'db>, ) -> Result<'db, Operand> { let konst = Const::new_unevaluated( self.interner(), @@ -1982,7 +1983,7 @@ impl<'a, 'db> MirLowerCtx<'a, 'db> { fn const_eval_discriminant(&self, variant: EnumVariantId) -> Result<'db, i128> { let r = self.db.const_eval_discriminant(variant); match r { - Ok(r) => Ok(r), + Ok(r) => Ok(r as i128), Err(e) => { let edition = self.edition(); let db = self.db; @@ -2129,8 +2130,8 @@ fn cast_kind<'db>( #[salsa_macros::tracked(returns(ref), cycle_result = mir_body_for_closure_cycle_result)] pub fn mir_body_for_closure_query<'db>( db: &'db dyn HirDatabase, - closure: InternedClosureId, -) -> Result<'db, MirBody> { + closure: InternedClosureId<'db>, +) -> Result<'db, MirBody<'db>> { let InternedClosure { owner: body_owner, expr, .. } = closure.loc(db); let store = ExpressionStore::of(db, body_owner.expression_store_owner(db)); let infer = InferenceResult::of(db, body_owner); @@ -2286,7 +2287,10 @@ pub fn mir_body_for_closure_query<'db>( } #[salsa_macros::tracked(returns(ref), cycle_result = mir_body_cycle_result)] -pub fn mir_body_query<'db>(db: &'db dyn HirDatabase, def: InferBodyId) -> Result<'db, MirBody> { +pub fn mir_body_query<'db>( + db: &'db dyn HirDatabase, + def: InferBodyId<'db>, +) -> Result<'db, MirBody<'db>> { let krate = def.krate(db); let edition = krate.data(db).edition; let detail = match def { @@ -2329,16 +2333,16 @@ pub fn mir_body_query<'db>(db: &'db dyn HirDatabase, def: InferBodyId) -> Result fn mir_body_cycle_result<'db>( _db: &'db dyn HirDatabase, _: salsa::Id, - _def: InferBodyId, -) -> Result<'db, MirBody> { + _def: InferBodyId<'db>, +) -> Result<'db, MirBody<'db>> { Err(MirLowerError::Loop) } fn mir_body_for_closure_cycle_result<'db>( _db: &'db dyn HirDatabase, _: salsa::Id, - _def: InternedClosureId, -) -> Result<'db, MirBody> { + _def: InternedClosureId<'db>, +) -> Result<'db, MirBody<'db>> { Err(MirLowerError::Loop) } @@ -2346,13 +2350,13 @@ fn mir_body_for_closure_cycle_result<'db>( /// then delegates to [`lower_to_mir_with_store`]. pub fn lower_body_to_mir<'db>( db: &'db dyn HirDatabase, - owner: InferBodyId, + owner: InferBodyId<'db>, store: &ExpressionStore, - infer: &InferenceResult, + infer: &InferenceResult<'db>, root_expr: ExprId, self_param: Option, params: &[PatId], -) -> Result<'db, MirBody> { +) -> Result<'db, MirBody<'db>> { // Extract params and self_param only when lowering the body's root expression for a function. if let Some(fid) = owner.as_function() { let callable_sig = @@ -2380,13 +2384,13 @@ pub fn lower_body_to_mir<'db>( /// const (picks bindings owned by `root_expr`). pub fn lower_to_mir_with_store<'db>( db: &'db dyn HirDatabase, - owner: InferBodyId, + owner: InferBodyId<'db>, store: &ExpressionStore, - infer: &InferenceResult, + infer: &InferenceResult<'db>, root_expr: ExprId, params: impl Iterator)> + Clone, self_param: Option<(BindingId, Ty<'db>)>, -) -> Result<'db, MirBody> { +) -> Result<'db, MirBody<'db>> { if infer.has_type_mismatches() || infer.is_erroneous() { return Err(MirLowerError::HasErrors); } diff --git a/crates/hir-ty/src/mir/monomorphization.rs b/crates/hir-ty/src/mir/monomorphization.rs index 06871a3f1842..8cd0ef465eea 100644 --- a/crates/hir-ty/src/mir/monomorphization.rs +++ b/crates/hir-ty/src/mir/monomorphization.rs @@ -39,7 +39,7 @@ struct Filler<'db> { } impl<'db> FallibleTypeFolder> for Filler<'db> { - type Error = MirLowerError; + type Error = MirLowerError<'db>; fn cx(&self) -> DbInterner<'db> { self.infcx.interner @@ -106,7 +106,7 @@ impl<'db> Filler<'db> { Self { infcx, trait_env: env, subst } } - fn fill_ty(&mut self, t: &mut StoredTy) -> Result<(), MirLowerError> { + fn fill_ty(&mut self, t: &mut StoredTy) -> Result<(), MirLowerError<'db>> { // Can't deep normalized as that'll try to normalize consts and fail. *t = t.as_ref().try_fold_with(self)?.store(); if references_non_lt_error(&t.as_ref()) { @@ -116,7 +116,7 @@ impl<'db> Filler<'db> { } } - fn fill_const(&mut self, t: &mut StoredConst) -> Result<(), MirLowerError> { + fn fill_const(&mut self, t: &mut StoredConst) -> Result<(), MirLowerError<'db>> { // Can't deep normalized as that'll try to normalize consts and fail. *t = t.as_ref().try_fold_with(self)?.store(); if references_non_lt_error(&t.as_ref()) { @@ -126,7 +126,7 @@ impl<'db> Filler<'db> { } } - fn fill_args(&mut self, t: &mut StoredGenericArgs) -> Result<(), MirLowerError> { + fn fill_args(&mut self, t: &mut StoredGenericArgs) -> Result<(), MirLowerError<'db>> { // Can't deep normalized as that'll try to normalize consts and fail. *t = t.as_ref().try_fold_with(self)?.store(); if references_non_lt_error(&t.as_ref()) { @@ -136,7 +136,7 @@ impl<'db> Filler<'db> { } } - fn fill_operand(&mut self, op: &mut Operand) -> Result<(), MirLowerError> { + fn fill_operand(&mut self, op: &mut Operand) -> Result<(), MirLowerError<'db>> { match &mut op.kind { OperandKind::Constant { konst, ty } => { self.fill_const(konst)?; @@ -159,7 +159,7 @@ impl<'db> Filler<'db> { Ok(()) } - fn fill_body(&mut self, body: &mut MirBody) -> Result<(), MirLowerError> { + fn fill_body(&mut self, body: &mut MirBody<'db>) -> Result<(), MirLowerError<'db>> { for (_, l) in body.locals.iter_mut() { self.fill_ty(&mut l.ty)?; } @@ -239,49 +239,49 @@ impl<'db> Filler<'db> { } #[salsa_macros::tracked(returns(ref), cycle_result = monomorphized_mir_body_cycle_result)] -pub fn monomorphized_mir_body_query( - db: &dyn HirDatabase, - owner: InferBodyId, +pub fn monomorphized_mir_body_query<'db>( + db: &'db dyn HirDatabase, + owner: InferBodyId<'db>, subst: StoredGenericArgs, trait_env: StoredParamEnvAndCrate, -) -> Result { - let mut filler = Filler::new(db, trait_env.as_ref(), subst.as_ref()); +) -> Result, MirLowerError<'db>> { + let mut filler = Filler::new(db, trait_env.as_ref(db), subst.as_ref()); let body = db.mir_body(owner)?; let mut body = (*body).clone(); filler.fill_body(&mut body)?; Ok(body) } -fn monomorphized_mir_body_cycle_result( - _db: &dyn HirDatabase, +fn monomorphized_mir_body_cycle_result<'db>( + _db: &'db dyn HirDatabase, _: salsa::Id, - _: InferBodyId, + _: InferBodyId<'db>, _: StoredGenericArgs, _: StoredParamEnvAndCrate, -) -> Result { +) -> Result, MirLowerError<'db>> { Err(MirLowerError::Loop) } #[salsa_macros::tracked(returns(ref), cycle_result = monomorphized_mir_body_for_closure_cycle_result)] -pub fn monomorphized_mir_body_for_closure_query( - db: &dyn HirDatabase, - closure: InternedClosureId, +pub fn monomorphized_mir_body_for_closure_query<'db>( + db: &'db dyn HirDatabase, + closure: InternedClosureId<'db>, subst: StoredGenericArgs, trait_env: StoredParamEnvAndCrate, -) -> Result { - let mut filler = Filler::new(db, trait_env.as_ref(), subst.as_ref()); +) -> Result, MirLowerError<'db>> { + let mut filler = Filler::new(db, trait_env.as_ref(db), subst.as_ref()); let body = db.mir_body_for_closure(closure)?; let mut body = (*body).clone(); filler.fill_body(&mut body)?; Ok(body) } -fn monomorphized_mir_body_for_closure_cycle_result( - _db: &dyn HirDatabase, +fn monomorphized_mir_body_for_closure_cycle_result<'db>( + _db: &'db dyn HirDatabase, _: salsa::Id, - _: InternedClosureId, + _: InternedClosureId<'db>, _: StoredGenericArgs, _: StoredParamEnvAndCrate, -) -> Result { +) -> Result, MirLowerError<'db>> { Err(MirLowerError::Loop) } diff --git a/crates/hir-ty/src/mir/pretty.rs b/crates/hir-ty/src/mir/pretty.rs index 3e414544241c..8893069f0c0a 100644 --- a/crates/hir-ty/src/mir/pretty.rs +++ b/crates/hir-ty/src/mir/pretty.rs @@ -43,7 +43,7 @@ macro_rules! wln { }; } -impl MirBody { +impl MirBody<'_> { pub fn pretty_print(&self, db: &dyn HirDatabase, display_target: DisplayTarget) -> String { let hir_body = ExpressionStore::of(db, self.owner.expression_store_owner(db)); let mut ctx = MirPrettyCtx::new(self, hir_body, db, display_target); @@ -100,7 +100,7 @@ impl MirBody { } struct MirPrettyCtx<'a, 'db> { - body: &'a MirBody, + body: &'a MirBody<'db>, hir_body: &'a ExpressionStore, db: &'db dyn HirDatabase, result: String, @@ -153,7 +153,7 @@ impl<'a, 'db> MirPrettyCtx<'a, 'db> { } } - fn for_closure(&mut self, closure: InternedClosureId) { + fn for_closure(&mut self, closure: InternedClosureId<'db>) { let body = match self.db.mir_body_for_closure(closure) { Ok(it) => it, Err(e) => { @@ -187,7 +187,7 @@ impl<'a, 'db> MirPrettyCtx<'a, 'db> { } fn new( - body: &'a MirBody, + body: &'a MirBody<'db>, hir_body: &'a ExpressionStore, db: &'db dyn HirDatabase, display_target: DisplayTarget, diff --git a/crates/hir-ty/src/next_solver.rs b/crates/hir-ty/src/next_solver.rs index f0d33ad2ddaf..42fd31f2594d 100644 --- a/crates/hir-ty/src/next_solver.rs +++ b/crates/hir-ty/src/next_solver.rs @@ -143,7 +143,7 @@ impl std::fmt::Debug for DefaultAny<'_> { } #[inline] -pub fn default_types<'a, 'db>(db: &'db dyn HirDatabase) -> &'a DefaultAny<'db> { +pub fn default_types<'db>(db: &'db dyn HirDatabase) -> &'db DefaultAny<'db> { static TYPES: OnceLock> = OnceLock::new(); let interner = DbInterner::new_no_crate(db); diff --git a/crates/hir-ty/src/next_solver/binder.rs b/crates/hir-ty/src/next_solver/binder.rs index 95f437165d04..3e7195525b2e 100644 --- a/crates/hir-ty/src/next_solver/binder.rs +++ b/crates/hir-ty/src/next_solver/binder.rs @@ -1,5 +1,6 @@ use hir_def::TraitId; use macros::{TypeFoldable, TypeVisitable}; +use salsa::Update; use crate::next_solver::{ Binder, Clauses, DbInterner, EarlyBinder, FnSig, FnSigKind, GenericArg, PolyFnSig, @@ -7,7 +8,7 @@ use crate::next_solver::{ TraitRef, Ty, }; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Update)] pub struct StoredEarlyBinder(T); impl StoredEarlyBinder { diff --git a/crates/hir-ty/src/next_solver/def_id.rs b/crates/hir-ty/src/next_solver/def_id.rs index 63337b297dc7..afffd45f9c8f 100644 --- a/crates/hir-ty/src/next_solver/def_id.rs +++ b/crates/hir-ty/src/next_solver/def_id.rs @@ -29,25 +29,25 @@ pub enum Ctor { } #[derive(PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash)] -pub enum SolverDefId { +pub enum SolverDefId<'db> { AdtId(AdtId), ConstId(ConstId), FunctionId(FunctionId), ImplId(ImplId), BuiltinDeriveImplId(BuiltinDeriveImplId), StaticId(StaticId), - AnonConstId(AnonConstId), + AnonConstId(AnonConstId<'db>), TraitId(TraitId), TypeAliasId(TypeAliasId), - InternedClosureId(InternedClosureId), - InternedCoroutineId(InternedCoroutineId), - InternedCoroutineClosureId(InternedCoroutineClosureId), + InternedClosureId(InternedClosureId<'db>), + InternedCoroutineId(InternedCoroutineId<'db>), + InternedCoroutineClosureId(InternedCoroutineClosureId<'db>), InternedOpaqueTyId(InternedOpaqueTyId), EnumVariantId(EnumVariantId), Ctor(Ctor), } -impl std::fmt::Debug for SolverDefId { +impl std::fmt::Debug for SolverDefId<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let interner = DbInterner::conjure(); let db = interner.db; @@ -121,26 +121,98 @@ impl std::fmt::Debug for SolverDefId { } } -impl_from!( - AdtId(StructId, EnumId, UnionId), - ConstId, - FunctionId, - ImplId, - BuiltinDeriveImplId, - StaticId, - AnonConstId, - TraitId, - TypeAliasId, - InternedClosureId, - InternedCoroutineId, - InternedCoroutineClosureId, - InternedOpaqueTyId, - EnumVariantId, - Ctor - for SolverDefId -); - -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { + fn from(it: AdtId) -> SolverDefId<'db> { + SolverDefId::AdtId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: StructId) -> SolverDefId<'db> { + SolverDefId::AdtId(AdtId::StructId(it)) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: EnumId) -> SolverDefId<'db> { + SolverDefId::AdtId(AdtId::EnumId(it)) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: UnionId) -> SolverDefId<'db> { + SolverDefId::AdtId(AdtId::UnionId(it)) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: ConstId) -> SolverDefId<'db> { + SolverDefId::ConstId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: FunctionId) -> SolverDefId<'db> { + SolverDefId::FunctionId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: ImplId) -> SolverDefId<'db> { + SolverDefId::ImplId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: BuiltinDeriveImplId) -> SolverDefId<'db> { + SolverDefId::BuiltinDeriveImplId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: StaticId) -> SolverDefId<'db> { + SolverDefId::StaticId(it) + } +} +impl<'db> From> for SolverDefId<'db> { + fn from(it: AnonConstId<'db>) -> SolverDefId<'db> { + SolverDefId::AnonConstId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: TraitId) -> SolverDefId<'db> { + SolverDefId::TraitId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: TypeAliasId) -> SolverDefId<'db> { + SolverDefId::TypeAliasId(it) + } +} +impl<'db> From> for SolverDefId<'db> { + fn from(it: InternedClosureId<'db>) -> SolverDefId<'db> { + SolverDefId::InternedClosureId(it) + } +} +impl<'db> From> for SolverDefId<'db> { + fn from(it: InternedCoroutineId<'db>) -> SolverDefId<'db> { + SolverDefId::InternedCoroutineId(it) + } +} +impl<'db> From> for SolverDefId<'db> { + fn from(it: InternedCoroutineClosureId<'db>) -> SolverDefId<'db> { + SolverDefId::InternedCoroutineClosureId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: InternedOpaqueTyId) -> SolverDefId<'db> { + SolverDefId::InternedOpaqueTyId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: EnumVariantId) -> SolverDefId<'db> { + SolverDefId::EnumVariantId(it) + } +} +impl<'db> From for SolverDefId<'db> { + fn from(it: Ctor) -> SolverDefId<'db> { + SolverDefId::Ctor(it) + } +} + +impl<'db> From for SolverDefId<'db> { fn from(value: GenericDefId) -> Self { match value { GenericDefId::AdtId(adt_id) => SolverDefId::AdtId(adt_id), @@ -154,9 +226,9 @@ impl From for SolverDefId { } } -impl From for SolverDefId { +impl<'db> From> for SolverDefId<'db> { #[inline] - fn from(value: GeneralConstId) -> Self { + fn from(value: GeneralConstId<'db>) -> Self { match value { GeneralConstId::ConstId(const_id) => SolverDefId::ConstId(const_id), GeneralConstId::StaticId(static_id) => SolverDefId::StaticId(static_id), @@ -165,7 +237,7 @@ impl From for SolverDefId { } } -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { #[inline] fn from(value: DefWithBodyId) -> Self { match value { @@ -177,9 +249,9 @@ impl From for SolverDefId { } } -impl From for SolverDefId { +impl<'db> From> for SolverDefId<'db> { #[inline] - fn from(value: InferBodyId) -> Self { + fn from(value: InferBodyId<'db>) -> Self { match value { InferBodyId::DefWithBodyId(id) => id.into(), InferBodyId::AnonConstId(id) => id.into(), @@ -187,7 +259,7 @@ impl From for SolverDefId { } } -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { #[inline] fn from(value: VariantId) -> Self { match value { @@ -198,7 +270,7 @@ impl From for SolverDefId { } } -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { #[inline] fn from(value: ExpressionStoreOwnerId) -> Self { match value { @@ -209,10 +281,10 @@ impl From for SolverDefId { } } -impl TryFrom for AttrDefId { +impl TryFrom> for AttrDefId { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { match value { SolverDefId::AdtId(it) => Ok(it.into()), SolverDefId::ConstId(it) => Ok(it.into()), @@ -234,11 +306,11 @@ impl TryFrom for AttrDefId { } } -impl TryFrom for DefWithBodyId { +impl TryFrom> for DefWithBodyId { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { let id = match value { SolverDefId::ConstId(id) => id.into(), SolverDefId::FunctionId(id) => id.into(), @@ -260,11 +332,11 @@ impl TryFrom for DefWithBodyId { } } -impl TryFrom for InferBodyId { +impl<'db> TryFrom> for InferBodyId<'db> { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'db>) -> Result { let id = match value { SolverDefId::ConstId(id) => id.into(), SolverDefId::FunctionId(id) => id.into(), @@ -286,10 +358,10 @@ impl TryFrom for InferBodyId { } } -impl TryFrom for GenericDefId { +impl TryFrom> for GenericDefId { type Error = (); - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { Ok(match value { SolverDefId::AdtId(adt_id) => GenericDefId::AdtId(adt_id), SolverDefId::ConstId(const_id) => GenericDefId::ConstId(const_id), @@ -310,8 +382,8 @@ impl TryFrom for GenericDefId { } } -impl<'db> inherent::DefId> for SolverDefId { - fn as_local(self) -> Option { +impl<'db> inherent::DefId> for SolverDefId<'db> { + fn as_local(self) -> Option> { Some(self) } fn is_local(self) -> bool { @@ -321,17 +393,17 @@ impl<'db> inherent::DefId> for SolverDefId { macro_rules! declare_id_wrapper { ($name:ident, $wraps:ident) => { - declare_id_wrapper!($name, $wraps, SolverDefId); + declare_id_wrapper!($name, $wraps, SolverDefId<'db>); }; - ($name:ident, $wraps:ident, $local:ident) => { + ($name:ident, $wraps:ident, $local:ty) => { declare_id_wrapper!($name, $wraps, $local, no_try_from); - impl TryFrom for $name { + impl TryFrom> for $name { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { match value { SolverDefId::$wraps(it) => Ok(Self(it)), _ => Err(()), @@ -340,7 +412,7 @@ macro_rules! declare_id_wrapper { } }; - ($name:ident, $wraps:ident, $local:ident, no_try_from) => { + ($name:ident, $wraps:ident, $local:ty, no_try_from) => { #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct $name(pub $wraps); @@ -364,9 +436,9 @@ macro_rules! declare_id_wrapper { } } - impl From<$name> for SolverDefId { + impl<'db> From<$name> for SolverDefId<'db> { #[inline] - fn from(value: $name) -> SolverDefId { + fn from(value: $name) -> SolverDefId<'db> { value.0.into() } } @@ -384,9 +456,158 @@ macro_rules! declare_id_wrapper { declare_id_wrapper!(TraitIdWrapper, TraitId); declare_id_wrapper!(TypeAliasIdWrapper, TypeAliasId); -declare_id_wrapper!(ClosureIdWrapper, InternedClosureId); -declare_id_wrapper!(CoroutineIdWrapper, InternedCoroutineId); -declare_id_wrapper!(CoroutineClosureIdWrapper, InternedCoroutineClosureId); +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct ClosureIdWrapper<'db>(pub InternedClosureId<'db>); + +impl std::fmt::Debug for ClosureIdWrapper<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&SolverDefId::from(self.0), f) + } +} + +impl<'db> From> for InternedClosureId<'db> { + #[inline] + fn from(value: ClosureIdWrapper<'db>) -> InternedClosureId<'db> { + value.0 + } +} + +impl<'db> From> for ClosureIdWrapper<'db> { + #[inline] + fn from(value: InternedClosureId<'db>) -> ClosureIdWrapper<'db> { + Self(value) + } +} + +impl<'db> From> for SolverDefId<'db> { + #[inline] + fn from(value: ClosureIdWrapper<'db>) -> SolverDefId<'db> { + value.0.into() + } +} + +impl<'db> TryFrom> for ClosureIdWrapper<'db> { + type Error = (); + + #[inline] + fn try_from(value: SolverDefId<'db>) -> Result { + match value { + SolverDefId::InternedClosureId(it) => Ok(Self(it)), + _ => Err(()), + } + } +} + +impl<'db> inherent::DefId, SolverDefId<'db>> for ClosureIdWrapper<'db> { + fn as_local(self) -> Option> { + Some(self.into()) + } + fn is_local(self) -> bool { + true + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct CoroutineIdWrapper<'db>(pub InternedCoroutineId<'db>); + +impl std::fmt::Debug for CoroutineIdWrapper<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&SolverDefId::from(self.0), f) + } +} + +impl<'db> From> for InternedCoroutineId<'db> { + #[inline] + fn from(value: CoroutineIdWrapper<'db>) -> InternedCoroutineId<'db> { + value.0 + } +} + +impl<'db> From> for CoroutineIdWrapper<'db> { + #[inline] + fn from(value: InternedCoroutineId<'db>) -> CoroutineIdWrapper<'db> { + Self(value) + } +} + +impl<'db> From> for SolverDefId<'db> { + #[inline] + fn from(value: CoroutineIdWrapper<'db>) -> SolverDefId<'db> { + value.0.into() + } +} + +impl<'db> TryFrom> for CoroutineIdWrapper<'db> { + type Error = (); + + #[inline] + fn try_from(value: SolverDefId<'db>) -> Result { + match value { + SolverDefId::InternedCoroutineId(it) => Ok(Self(it)), + _ => Err(()), + } + } +} + +impl<'db> inherent::DefId, SolverDefId<'db>> for CoroutineIdWrapper<'db> { + fn as_local(self) -> Option> { + Some(self.into()) + } + fn is_local(self) -> bool { + true + } +} + +#[derive(Clone, Copy, PartialEq, Eq, Hash)] +pub struct CoroutineClosureIdWrapper<'db>(pub InternedCoroutineClosureId<'db>); + +impl std::fmt::Debug for CoroutineClosureIdWrapper<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&SolverDefId::from(self.0), f) + } +} + +impl<'db> From> for InternedCoroutineClosureId<'db> { + #[inline] + fn from(value: CoroutineClosureIdWrapper<'db>) -> InternedCoroutineClosureId<'db> { + value.0 + } +} + +impl<'db> From> for CoroutineClosureIdWrapper<'db> { + #[inline] + fn from(value: InternedCoroutineClosureId<'db>) -> CoroutineClosureIdWrapper<'db> { + Self(value) + } +} + +impl<'db> From> for SolverDefId<'db> { + #[inline] + fn from(value: CoroutineClosureIdWrapper<'db>) -> SolverDefId<'db> { + value.0.into() + } +} + +impl<'db> TryFrom> for CoroutineClosureIdWrapper<'db> { + type Error = (); + + #[inline] + fn try_from(value: SolverDefId<'db>) -> Result { + match value { + SolverDefId::InternedCoroutineClosureId(it) => Ok(Self(it)), + _ => Err(()), + } + } +} + +impl<'db> inherent::DefId, SolverDefId<'db>> for CoroutineClosureIdWrapper<'db> { + fn as_local(self) -> Option> { + Some(self.into()) + } + fn is_local(self) -> bool { + true + } +} declare_id_wrapper!(AdtIdWrapper, AdtId); declare_id_wrapper!(OpaqueTyIdWrapper, InternedOpaqueTyId, OpaqueTyIdWrapper); @@ -394,13 +615,13 @@ macro_rules! declare_ty_const_pair { ( $ty_id_name:ident, $const_id_name:ident, $term_id_name:ident ) => { declare_id_wrapper!($ty_id_name, TypeAliasId); declare_id_wrapper!($const_id_name, ConstId); - declare_id_wrapper!($term_id_name, TermId, SolverDefId, no_try_from); + declare_id_wrapper!($term_id_name, TermId, SolverDefId<'db>, no_try_from); - impl TryFrom for $term_id_name { + impl TryFrom> for $term_id_name { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { match value { SolverDefId::TypeAliasId(it) => Ok(Self(TermId::TypeAliasId(it))), SolverDefId::ConstId(it) => Ok(Self(TermId::ConstId(it))), @@ -443,7 +664,7 @@ macro_rules! declare_ty_const_pair { } } - impl From<$const_id_name> for GeneralConstIdWrapper { + impl<'db> From<$const_id_name> for GeneralConstIdWrapper<'db> { fn from(value: $const_id_name) -> Self { GeneralConstIdWrapper(GeneralConstId::ConstId(value.0)) } @@ -463,7 +684,7 @@ pub enum TermId { } impl_from!(TypeAliasId, ConstId for TermId); -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { fn from(value: TermId) -> Self { match value { TermId::TypeAliasId(id) => id.into(), @@ -473,28 +694,28 @@ impl From for SolverDefId { } #[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct GeneralConstIdWrapper(pub GeneralConstId); +pub struct GeneralConstIdWrapper<'db>(pub GeneralConstId<'db>); -impl std::fmt::Debug for GeneralConstIdWrapper { +impl std::fmt::Debug for GeneralConstIdWrapper<'_> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(&self.0, f) } } -impl From for GeneralConstId { +impl<'db> From> for GeneralConstId<'db> { #[inline] - fn from(value: GeneralConstIdWrapper) -> GeneralConstId { + fn from(value: GeneralConstIdWrapper<'db>) -> GeneralConstId<'db> { value.0 } } -impl From for GeneralConstIdWrapper { +impl<'db> From> for GeneralConstIdWrapper<'db> { #[inline] - fn from(value: GeneralConstId) -> GeneralConstIdWrapper { + fn from(value: GeneralConstId<'db>) -> GeneralConstIdWrapper<'db> { Self(value) } } -impl From for SolverDefId { +impl<'db> From> for SolverDefId<'db> { #[inline] - fn from(value: GeneralConstIdWrapper) -> SolverDefId { + fn from(value: GeneralConstIdWrapper<'db>) -> SolverDefId<'db> { match value.0 { GeneralConstId::ConstId(id) => SolverDefId::ConstId(id), GeneralConstId::StaticId(id) => SolverDefId::StaticId(id), @@ -502,10 +723,10 @@ impl From for SolverDefId { } } } -impl TryFrom for GeneralConstIdWrapper { +impl<'db> TryFrom> for GeneralConstIdWrapper<'db> { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'db>) -> Result { match value { SolverDefId::ConstId(it) => Ok(Self(it.into())), SolverDefId::StaticId(it) => Ok(Self(it.into())), @@ -514,8 +735,8 @@ impl TryFrom for GeneralConstIdWrapper { } } } -impl<'db> inherent::DefId> for GeneralConstIdWrapper { - fn as_local(self) -> Option { +impl<'db> inherent::DefId> for GeneralConstIdWrapper<'db> { + fn as_local(self) -> Option> { Some(self.into()) } fn is_local(self) -> bool { @@ -543,9 +764,9 @@ impl From for CallableIdWrapper { Self(value) } } -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { #[inline] - fn from(value: CallableIdWrapper) -> SolverDefId { + fn from(value: CallableIdWrapper) -> SolverDefId<'db> { match value.0 { CallableDefId::FunctionId(it) => it.into(), CallableDefId::StructId(it) => Ctor::Struct(it).into(), @@ -553,10 +774,10 @@ impl From for SolverDefId { } } } -impl TryFrom for CallableIdWrapper { +impl TryFrom> for CallableIdWrapper { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { match value { SolverDefId::FunctionId(it) => Ok(Self(it.into())), SolverDefId::Ctor(Ctor::Struct(it)) => Ok(Self(it.into())), @@ -566,7 +787,7 @@ impl TryFrom for CallableIdWrapper { } } impl<'db> inherent::DefId> for CallableIdWrapper { - fn as_local(self) -> Option { + fn as_local(self) -> Option> { Some(self.into()) } fn is_local(self) -> bool { @@ -582,19 +803,19 @@ pub enum AnyImplId { impl_from!(ImplId, BuiltinDeriveImplId for AnyImplId); -impl From for SolverDefId { +impl<'db> From for SolverDefId<'db> { #[inline] - fn from(value: AnyImplId) -> SolverDefId { + fn from(value: AnyImplId) -> SolverDefId<'db> { match value { AnyImplId::ImplId(it) => it.into(), AnyImplId::BuiltinDeriveImplId(it) => it.into(), } } } -impl TryFrom for AnyImplId { +impl TryFrom> for AnyImplId { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result { + fn try_from(value: SolverDefId<'_>) -> Result { match value { SolverDefId::ImplId(it) => Ok(it.into()), SolverDefId::BuiltinDeriveImplId(it) => Ok(it.into()), @@ -603,7 +824,7 @@ impl TryFrom for AnyImplId { } } impl<'db> inherent::DefId> for AnyImplId { - fn as_local(self) -> Option { + fn as_local(self) -> Option> { Some(self.into()) } fn is_local(self) -> bool { diff --git a/crates/hir-ty/src/next_solver/fulfill.rs b/crates/hir-ty/src/next_solver/fulfill.rs index 33dd33cb1d80..e422f75a0207 100644 --- a/crates/hir-ty/src/next_solver/fulfill.rs +++ b/crates/hir-ty/src/next_solver/fulfill.rs @@ -287,7 +287,7 @@ impl<'db> FulfillmentCtxt<'db> { /// This function can be also return false positives, which will lead to poor diagnostics /// so we want to keep this visitor *precise* too. pub struct StalledOnCoroutines<'a, 'db> { - pub stalled_coroutines: &'a [SolverDefId], + pub stalled_coroutines: &'a [SolverDefId<'db>], pub span: Span, pub cache: FxHashSet>, } diff --git a/crates/hir-ty/src/next_solver/generic_arg.rs b/crates/hir-ty/src/next_solver/generic_arg.rs index 51f070cd64e8..41f95f563784 100644 --- a/crates/hir-ty/src/next_solver/generic_arg.rs +++ b/crates/hir-ty/src/next_solver/generic_arg.rs @@ -543,7 +543,7 @@ impl<'db> GenericArgs<'db> { /// replace defaults of generic parameters. pub fn for_item( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, mk_kind: F, ) -> GenericArgs<'db> where @@ -564,7 +564,7 @@ impl<'db> GenericArgs<'db> { } /// Creates an all-error `GenericArgs`. - pub fn error_for_item(interner: DbInterner<'db>, def_id: SolverDefId) -> GenericArgs<'db> { + pub fn error_for_item(interner: DbInterner<'db>, def_id: SolverDefId<'db>) -> GenericArgs<'db> { GenericArgs::for_item(interner, def_id, |_, id, _| GenericArg::error_from_id(interner, id)) } @@ -587,7 +587,7 @@ impl<'db> GenericArgs<'db> { /// Like `for_item()`, but calls first uses the args from `first`. pub fn fill_rest( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, first: impl IntoIterator>, mut fallback: F, ) -> GenericArgs<'db> diff --git a/crates/hir-ty/src/next_solver/generics.rs b/crates/hir-ty/src/next_solver/generics.rs index a798582cb989..a1df4979c5d8 100644 --- a/crates/hir-ty/src/next_solver/generics.rs +++ b/crates/hir-ty/src/next_solver/generics.rs @@ -8,7 +8,7 @@ use super::SolverDefId; use super::DbInterner; -pub(crate) fn generics(interner: DbInterner<'_>, def: SolverDefId) -> Generics<'_> { +pub(crate) fn generics<'db>(interner: DbInterner<'db>, def: SolverDefId<'db>) -> Generics<'db> { let db = interner.db; let def = match (def.try_into(), def) { (Ok(def), _) => def, diff --git a/crates/hir-ty/src/next_solver/infer/context.rs b/crates/hir-ty/src/next_solver/infer/context.rs index 1e2a3ff0c2b3..270bc73d5f53 100644 --- a/crates/hir-ty/src/next_solver/infer/context.rs +++ b/crates/hir-ty/src/next_solver/infer/context.rs @@ -158,7 +158,7 @@ impl<'db> rustc_type_ir::InferCtxtLike for InferCtxt<'db> { self.next_const_var(Span::Dummy) } - fn fresh_args_for_item(&self, def_id: SolverDefId) -> GenericArgs<'db> { + fn fresh_args_for_item(&self, def_id: SolverDefId<'db>) -> GenericArgs<'db> { self.fresh_args_for_item(Span::Dummy, def_id) } diff --git a/crates/hir-ty/src/next_solver/infer/mod.rs b/crates/hir-ty/src/next_solver/infer/mod.rs index 6b6dd549b34e..48b0785f5c2b 100644 --- a/crates/hir-ty/src/next_solver/infer/mod.rs +++ b/crates/hir-ty/src/next_solver/infer/mod.rs @@ -296,7 +296,7 @@ pub struct TypeTrace<'db> { /// Times when we replace bound regions with existentials: #[derive(Clone, Copy, Debug)] -pub enum BoundRegionConversionTime { +pub enum BoundRegionConversionTime<'db> { /// when a fn is called FnCall, @@ -304,7 +304,7 @@ pub enum BoundRegionConversionTime { HigherRankedType, /// when projecting an associated type - AssocTypeProjection(SolverDefId), + AssocTypeProjection(SolverDefId<'db>), } /// See the `region_obligations` field for more information. @@ -839,7 +839,7 @@ impl<'db> InferCtxt<'db> { /// Given a set of generics defined on a type or impl, returns the generic parameters mapping /// each type/region parameter to a fresh inference variable. - pub fn fresh_args_for_item(&self, span: Span, def_id: SolverDefId) -> GenericArgs<'db> { + pub fn fresh_args_for_item(&self, span: Span, def_id: SolverDefId<'db>) -> GenericArgs<'db> { GenericArgs::for_item(self.interner, def_id, |_index, kind, _| self.var_for_def(kind, span)) } @@ -847,7 +847,7 @@ impl<'db> InferCtxt<'db> { pub fn fill_rest_fresh_args( &self, span: Span, - def_id: SolverDefId, + def_id: SolverDefId<'db>, first: impl IntoIterator>, ) -> GenericArgs<'db> { GenericArgs::fill_rest(self.interner, def_id, first, |_index, kind, _| { @@ -901,7 +901,7 @@ impl<'db> InferCtxt<'db> { } #[inline(always)] - pub fn can_define_opaque_ty(&self, id: impl Into) -> bool { + pub fn can_define_opaque_ty(&self, id: impl Into>) -> bool { match self.typing_mode_raw().assert_not_erased() { TypingMode::Analysis { defining_opaque_types_and_generators } => { defining_opaque_types_and_generators.contains(&id.into()) @@ -1100,7 +1100,7 @@ impl<'db> InferCtxt<'db> { pub fn instantiate_binder_with_fresh_vars( &self, span: Span, - _lbrct: BoundRegionConversionTime, + _lbrct: BoundRegionConversionTime<'db>, value: Binder<'db, T>, ) -> T where diff --git a/crates/hir-ty/src/next_solver/infer/relate/generalize.rs b/crates/hir-ty/src/next_solver/infer/relate/generalize.rs index e55e43a4cdb3..3b957c9c7289 100644 --- a/crates/hir-ty/src/next_solver/infer/relate/generalize.rs +++ b/crates/hir-ty/src/next_solver/infer/relate/generalize.rs @@ -394,7 +394,7 @@ impl<'db> TypeRelation> for Generalizer<'_, 'db> { &mut self, a_ty: Ty<'db>, _: Ty<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, a_args: GenericArgs<'db>, b_args: GenericArgs<'db>, mk: impl FnOnce(GenericArgs<'db>) -> Ty<'db>, diff --git a/crates/hir-ty/src/next_solver/infer/relate/lattice.rs b/crates/hir-ty/src/next_solver/infer/relate/lattice.rs index f3af697febcb..f34afead74ff 100644 --- a/crates/hir-ty/src/next_solver/infer/relate/lattice.rs +++ b/crates/hir-ty/src/next_solver/infer/relate/lattice.rs @@ -91,7 +91,7 @@ impl<'db> TypeRelation> for LatticeOp<'_, 'db> { &mut self, a_ty: Ty<'db>, b_ty: Ty<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, a_args: GenericArgs<'db>, b_args: GenericArgs<'db>, mk: impl FnOnce(GenericArgs<'db>) -> Ty<'db>, diff --git a/crates/hir-ty/src/next_solver/interner.rs b/crates/hir-ty/src/next_solver/interner.rs index b466fe0f1810..c3ff9b3b7eaf 100644 --- a/crates/hir-ty/src/next_solver/interner.rs +++ b/crates/hir-ty/src/next_solver/interner.rs @@ -200,6 +200,7 @@ macro_rules! impl_stored_interned_slice { Self { interned: it.interned.to_owned() } } + // FIXME: This transmute is not safe as is! #[inline] pub fn as_ref<'a, 'db>(&'a self) -> $name<'db> { let it = $name { interned: self.interned.as_ref() }; @@ -377,7 +378,7 @@ impl<'db> DbInterner<'db> { } #[inline] - pub fn default_types<'a>(&self) -> &'a crate::next_solver::DefaultAny<'db> { + pub fn default_types(&self) -> &'db crate::next_solver::DefaultAny<'db> { crate::next_solver::default_types(self.db) } @@ -880,18 +881,18 @@ macro_rules! is_lang_item { } impl<'db> Interner for DbInterner<'db> { - type DefId = SolverDefId; - type LocalDefId = SolverDefId; + type DefId = SolverDefId<'db>; + type LocalDefId = SolverDefId<'db>; type LocalDefIds = SolverDefIds<'db>; type TraitId = TraitIdWrapper; type ForeignId = TypeAliasIdWrapper; type FunctionId = CallableIdWrapper; - type ClosureId = ClosureIdWrapper; - type CoroutineClosureId = CoroutineClosureIdWrapper; - type CoroutineId = CoroutineIdWrapper; + type ClosureId = ClosureIdWrapper<'db>; + type CoroutineClosureId = CoroutineClosureIdWrapper<'db>; + type CoroutineId = CoroutineIdWrapper<'db>; type AdtId = AdtIdWrapper; type ImplId = AnyImplId; - type UnevaluatedConstId = GeneralConstIdWrapper; + type UnevaluatedConstId = GeneralConstIdWrapper<'db>; type TraitAssocTyId = TraitAssocTyId; type TraitAssocConstId = TraitAssocConstId; type TraitAssocTermId = TraitAssocTermId; @@ -1107,7 +1108,7 @@ impl<'db> Interner for DbInterner<'db> { AdtDef::new(def_id.0, self) } - fn alias_term_kind_from_def_id(self, def_id: SolverDefId) -> AliasTermKind<'db> { + fn alias_term_kind_from_def_id(self, def_id: SolverDefId<'db>) -> AliasTermKind<'db> { match def_id { SolverDefId::InternedOpaqueTyId(def_id) => { AliasTermKind::OpaqueTy { def_id: def_id.into() } @@ -1607,7 +1608,7 @@ impl<'db> Interner for DbInterner<'db> { ) { let krate = self.krate.expect("trait solving requires setting `DbInterner::krate`"); let trait_block = trait_def_id.0.loc(self.db).container.block(self.db); - let mut consider_impls_for_simplified_type = |simp: SimplifiedType| { + let mut consider_impls_for_simplified_type = |simp: SimplifiedType<'_>| { let type_block = simp.def().and_then(|def_id| { let module = match def_id { SolverDefId::AdtId(AdtId::StructId(id)) => id.module(self.db), @@ -1972,14 +1973,14 @@ impl<'db> Interner for DbInterner<'db> { return SolverDefIds::new_from_slice(&result); - struct CoroutinesVisitor<'a> { - db: &'a dyn HirDatabase, - owner: InferBodyId, - store: &'a ExpressionStore, - coroutines: &'a mut Vec, + struct CoroutinesVisitor<'a, 'db> { + db: &'db dyn HirDatabase, + owner: InferBodyId<'db>, + store: &'db ExpressionStore, + coroutines: &'a mut Vec>, } - impl StoreVisitor for CoroutinesVisitor<'_> { + impl<'db> StoreVisitor for CoroutinesVisitor<'_, 'db> { fn on_expr(&mut self, expr: ExprId) { if let hir_def::hir::Expr::Closure { closure_kind: @@ -2264,7 +2265,10 @@ impl<'db> DbInterner<'db> { } } -fn predicates_of(db: &dyn HirDatabase, def_id: SolverDefId) -> &GenericPredicates { +fn predicates_of<'db>( + db: &'db dyn HirDatabase, + def_id: SolverDefId<'db>, +) -> &'db GenericPredicates { match def_id { SolverDefId::BuiltinDeriveImplId(impl_) => crate::builtin_derive::predicates(db, impl_), SolverDefId::AnonConstId(anon_const) => { @@ -2319,13 +2323,13 @@ macro_rules! TrivialTypeTraversalImpls { } TrivialTypeTraversalImpls! { - SolverDefId, + SolverDefId<'_>, TraitIdWrapper, TypeAliasIdWrapper, CallableIdWrapper, - ClosureIdWrapper, - CoroutineIdWrapper, - CoroutineClosureIdWrapper, + ClosureIdWrapper<'_>, + CoroutineIdWrapper<'_>, + CoroutineClosureIdWrapper<'_>, AdtIdWrapper, TraitAssocTyId, TraitAssocConstId, @@ -2341,7 +2345,7 @@ TrivialTypeTraversalImpls! { InherentAssocTermId, OpaqueTyIdWrapper, AnyImplId, - GeneralConstIdWrapper, + GeneralConstIdWrapper<'_>, Safety, Span, ParamConst, diff --git a/crates/hir-ty/src/next_solver/opaques.rs b/crates/hir-ty/src/next_solver/opaques.rs index bdb3f3087103..dd5f72979515 100644 --- a/crates/hir-ty/src/next_solver/opaques.rs +++ b/crates/hir-ty/src/next_solver/opaques.rs @@ -30,8 +30,8 @@ interned_slice!( SolverDefIds, StoredSolverDefIds, def_ids, - SolverDefId, - SolverDefId, + SolverDefId<'db>, + SolverDefId<'static>, ); impl_foldable_for_interned_slice!(SolverDefIds); diff --git a/crates/hir-ty/src/next_solver/region.rs b/crates/hir-ty/src/next_solver/region.rs index 72a25f4df6da..b589e80d9999 100644 --- a/crates/hir-ty/src/next_solver/region.rs +++ b/crates/hir-ty/src/next_solver/region.rs @@ -164,7 +164,7 @@ pub struct EarlyParamRegion { /// should basically always be `BoundRegionKind::Named` as otherwise there is no way of telling /// different parameters apart. pub struct LateParamRegion<'db> { - pub scope: SolverDefId, + pub scope: SolverDefId<'db>, pub bound_region: BoundRegionKind<'db>, } diff --git a/crates/hir-ty/src/next_solver/ty.rs b/crates/hir-ty/src/next_solver/ty.rs index fe31d44207df..59ac3481b228 100644 --- a/crates/hir-ty/src/next_solver/ty.rs +++ b/crates/hir-ty/src/next_solver/ty.rs @@ -43,7 +43,7 @@ use super::{ util::{FloatExt, IntegerExt}, }; -pub type SimplifiedType = rustc_type_ir::fast_reject::SimplifiedType; +pub type SimplifiedType<'db> = rustc_type_ir::fast_reject::SimplifiedType>; pub type TyKind<'db> = rustc_type_ir::TyKind>; pub type FnHeader<'db> = rustc_type_ir::FnHeader>; pub type AliasTyKind<'db> = rustc_type_ir::AliasTyKind>; @@ -1186,7 +1186,7 @@ impl<'db> rustc_type_ir::inherent::Ty> for Ty<'db> { fn new_coroutine( interner: DbInterner<'db>, - def_id: CoroutineIdWrapper, + def_id: CoroutineIdWrapper<'db>, args: as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::Coroutine(def_id, args)) @@ -1194,7 +1194,7 @@ impl<'db> rustc_type_ir::inherent::Ty> for Ty<'db> { fn new_coroutine_closure( interner: DbInterner<'db>, - def_id: CoroutineClosureIdWrapper, + def_id: CoroutineClosureIdWrapper<'db>, args: as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::CoroutineClosure(def_id, args)) @@ -1202,7 +1202,7 @@ impl<'db> rustc_type_ir::inherent::Ty> for Ty<'db> { fn new_closure( interner: DbInterner<'db>, - def_id: ClosureIdWrapper, + def_id: ClosureIdWrapper<'db>, args: as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::Closure(def_id, args)) @@ -1210,7 +1210,7 @@ impl<'db> rustc_type_ir::inherent::Ty> for Ty<'db> { fn new_coroutine_witness( interner: DbInterner<'db>, - def_id: CoroutineIdWrapper, + def_id: CoroutineIdWrapper<'db>, args: as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::CoroutineWitness(def_id, args)) @@ -1218,7 +1218,7 @@ impl<'db> rustc_type_ir::inherent::Ty> for Ty<'db> { fn new_coroutine_witness_for_coroutine( interner: DbInterner<'db>, - def_id: CoroutineIdWrapper, + def_id: CoroutineIdWrapper<'db>, coroutine_args: as Interner>::GenericArgs, ) -> Self { // HACK: Coroutine witness types are lifetime erased, so they diff --git a/crates/hir-ty/src/next_solver/util.rs b/crates/hir-ty/src/next_solver/util.rs index fb3bd18bf48a..7e40e3c17d51 100644 --- a/crates/hir-ty/src/next_solver/util.rs +++ b/crates/hir-ty/src/next_solver/util.rs @@ -456,7 +456,7 @@ pub fn apply_args_to_binder<'db, T: TypeFoldable>>( pub fn explicit_item_bounds<'db>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, ) -> EarlyBinder<'db, impl DoubleEndedIterator> + ExactSizeIterator> { let db = interner.db(); let clauses = match def_id { @@ -469,7 +469,7 @@ pub fn explicit_item_bounds<'db>( pub fn explicit_item_self_bounds<'db>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, ) -> EarlyBinder<'db, impl DoubleEndedIterator> + ExactSizeIterator> { let db = interner.db(); let clauses = match def_id { diff --git a/crates/hir-ty/src/opaques.rs b/crates/hir-ty/src/opaques.rs index dfd1fd96c656..1d7cd1b05dfe 100644 --- a/crates/hir-ty/src/opaques.rs +++ b/crates/hir-ty/src/opaques.rs @@ -22,8 +22,8 @@ use crate::{ pub(crate) fn opaque_types_defined_by( db: &dyn HirDatabase, - def_id: InferBodyId, - result: &mut Vec, + def_id: InferBodyId<'_>, + result: &mut Vec>, ) { if let Some(func) = def_id.as_function() { // A function may define its own RPITs. @@ -83,7 +83,7 @@ pub(crate) fn opaque_types_defined_by( db: &dyn HirDatabase, opaques: &Option>>, mut make_impl_trait: impl FnMut(ImplTraitIdx) -> ImplTraitId, - result: &mut Vec, + result: &mut Vec>, ) { if let Some(opaques) = opaques { for (opaque_idx, _) in (**opaques).as_ref().skip_binder().impl_traits.iter() { diff --git a/crates/hir-ty/src/tests.rs b/crates/hir-ty/src/tests.rs index ce4eff701c90..fb1d9b167ae8 100644 --- a/crates/hir-ty/src/tests.rs +++ b/crates/hir-ty/src/tests.rs @@ -324,7 +324,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { crate::attach_db(&db, || { let mut buf = String::new(); - let mut infer_def = |inference_result: &InferenceResult, + let mut infer_def = |inference_result: &InferenceResult<'_>, store: &ExpressionStore, source_map: &ExpressionStoreSourceMap, self_param: Option<( diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index 4c76ae901da8..36b341e89b47 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -61,13 +61,13 @@ pub struct StoredParamEnvAndCrate { impl StoredParamEnvAndCrate { #[inline] - pub fn param_env(&self) -> ParamEnv<'_> { + pub fn param_env<'db>(&self, _db: &'db dyn HirDatabase) -> ParamEnv<'db> { ParamEnv { clauses: self.param_env.as_ref() } } #[inline] - pub fn as_ref(&self) -> ParamEnvAndCrate<'_> { - ParamEnvAndCrate { param_env: self.param_env(), krate: self.krate } + pub fn as_ref<'db>(&self, db: &'db dyn HirDatabase) -> ParamEnvAndCrate<'db> { + ParamEnvAndCrate { param_env: self.param_env(db), krate: self.krate } } } @@ -172,7 +172,7 @@ pub enum WherePredicateEvaluation { pub fn where_predicate_must_hold<'db>( db: &'db dyn HirDatabase, resolver: &Resolver<'db>, - store: &ExpressionStore, + store: &'db ExpressionStore, def: ExpressionStoreOwnerId, generic_def: GenericDefId, env: ParamEnvAndCrate<'db>, diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs index ed073cb43789..696e4fd20c89 100644 --- a/crates/hir/src/diagnostics.rs +++ b/crates/hir/src/diagnostics.rs @@ -136,7 +136,7 @@ diagnostics![AnyDiagnostic<'db> -> MissingUnsafe, MovedOutOfRef<'db>, MutableRefBinding, - NeedMut, + NeedMut<'db>, NonExhaustiveLet, NonExhaustiveRecordExpr, NonExhaustiveRecordPat, @@ -167,8 +167,8 @@ diagnostics![AnyDiagnostic<'db> -> UnresolvedMethodCall<'db>, UnresolvedModule, UnresolvedIdent, - UnusedMut, - UnusedVariable, + UnusedMut<'db>, + UnusedVariable<'db>, GenericArgsProhibited, ParenthesizedGenericArgsWithoutFnTrait, BadRtn, @@ -464,19 +464,19 @@ pub struct TypeMismatch<'db> { } #[derive(Debug)] -pub struct NeedMut { - pub local: Local, +pub struct NeedMut<'db> { + pub local: Local<'db>, pub span: InFile, } #[derive(Debug)] -pub struct UnusedMut { - pub local: Local, +pub struct UnusedMut<'db> { + pub local: Local<'db>, } #[derive(Debug)] -pub struct UnusedVariable { - pub local: Local, +pub struct UnusedVariable<'db> { + pub local: Local<'db>, } #[derive(Debug)] @@ -804,7 +804,7 @@ impl<'db> AnyDiagnostic<'db> { d: &'db InferenceDiagnostic, source_map: &hir_def::expr_store::BodySourceMap, sig_map: &hir_def::expr_store::ExpressionStoreSourceMap, - type_owner: TypeOwnerId, + type_owner: TypeOwnerId<'db>, ) -> Option> { let expr_syntax = |expr| Self::expr_syntax(expr, source_map); let pat_syntax = |pat| Self::pat_syntax(pat, source_map); @@ -1099,7 +1099,7 @@ impl<'db> AnyDiagnostic<'db> { db: &'db dyn HirDatabase, d: &'db SolverDiagnosticKind, span: SpanSyntax, - type_owner: TypeOwnerId, + type_owner: TypeOwnerId<'db>, ) -> Option> { let interner = DbInterner::new_no_crate(db); Some(match d { diff --git a/crates/hir/src/display.rs b/crates/hir/src/display.rs index ed18482bf380..94e50f8e2d6e 100644 --- a/crates/hir/src/display.rs +++ b/crates/hir/src/display.rs @@ -509,7 +509,7 @@ impl<'db> HirDisplay<'db> for Field { } } -impl<'db> HirDisplay<'db> for TupleField { +impl<'db> HirDisplay<'db> for TupleField<'db> { fn hir_fmt(&self, f: &mut HirFormatter<'_, 'db>) -> Result { write!(f, "pub {}: ", self.name().display(f.db, f.edition()))?; self.ty(f.db).hir_fmt(f) diff --git a/crates/hir/src/from_id.rs b/crates/hir/src/from_id.rs index 219eb9c3b926..e94279bc4583 100644 --- a/crates/hir/src/from_id.rs +++ b/crates/hir/src/from_id.rs @@ -254,7 +254,7 @@ impl TryFrom for GenericDefId { } } -impl From<(DefWithBodyId, BindingId)> for Local { +impl<'db> From<(DefWithBodyId, BindingId)> for Local<'db> { fn from((parent, binding_id): (DefWithBodyId, BindingId)) -> Self { Local { parent: parent.into(), parent_infer: parent.into(), binding_id } } diff --git a/crates/hir/src/has_source.rs b/crates/hir/src/has_source.rs index 9bff8bda3a96..40808294bbc1 100644 --- a/crates/hir/src/has_source.rs +++ b/crates/hir/src/has_source.rs @@ -265,7 +265,7 @@ impl HasSource for LifetimeParam { } } -impl HasSource for LocalSource { +impl HasSource for LocalSource<'_> { type Ast = Either; fn source(self, _: &dyn HirDatabase) -> Option> { diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index f676a700cc4f..11cc702fae04 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -703,7 +703,7 @@ impl Module { self, db: &dyn HirDatabase, visible_from: Option, - ) -> Vec<(Name, ScopeDef)> { + ) -> Vec<(Name, ScopeDef<'_>)> { self.id.def_map(db)[self.id] .scope .entries() @@ -1367,18 +1367,18 @@ pub struct Field { } #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)] -pub struct TupleField { - pub owner: InferBodyId, +pub struct TupleField<'db> { + pub owner: InferBodyId<'db>, pub tuple: TupleId, pub index: u32, } -impl TupleField { +impl<'db> TupleField<'db> { pub fn name(&self) -> Name { Name::new_tuple_field(self.index as usize) } - pub fn ty<'db>(&self, db: &'db dyn HirDatabase) -> Type<'db> { + pub fn ty(&self, db: &'db dyn HirDatabase) -> Type<'db> { let interner = DbInterner::new_no_crate(db); let ty = InferenceResult::of(db, self.owner) .tuple_field_access_type(self.tuple) @@ -1703,7 +1703,7 @@ impl EnumVariant { self.source(db)?.value.const_arg()?.expr() } - pub fn eval(self, db: &dyn HirDatabase) -> Result { + pub fn eval(self, db: &dyn HirDatabase) -> Result> { db.const_eval_discriminant(self.into()) } @@ -1870,21 +1870,24 @@ impl Variant { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct AnonConst { - id: AnonConstId, +pub struct AnonConst<'db> { + id: AnonConstId<'db>, } -impl AnonConst { +impl<'db> AnonConst<'db> { pub fn owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwner { self.id.loc(db).owner.into() } - pub fn ty<'db>(self, db: &'db dyn HirDatabase) -> Type<'db> { + pub fn ty(self, db: &'db dyn HirDatabase) -> Type<'db> { let loc = self.id.loc(db); Type { owner: self.id.into(), ty: loc.ty.get() } } - pub fn eval(self, db: &dyn HirDatabase) -> Result, ConstEvalError> { + pub fn eval( + self, + db: &'db dyn HirDatabase, + ) -> Result, ConstEvalError<'db>> { let interner = DbInterner::new_no_crate(db); let ty = self.id.loc(db).ty.get().instantiate_identity().skip_norm_wip(); db.anon_const_eval(self.id, GenericArgs::empty(interner), None).map(|it| EvaluatedConst { @@ -1896,9 +1899,9 @@ impl AnonConst { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum InferBody { +pub enum InferBody<'db> { Body(DefWithBody), - AnonConst(AnonConst), + AnonConst(AnonConst<'db>), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -1996,7 +1999,7 @@ impl DefWithBody { } #[deprecated = "you should really not use this, this is exported for analysis-stats only"] - pub fn run_mir_body(self, db: &dyn HirDatabase) -> Result<(), MirLowerError> { + pub fn run_mir_body(self, db: &dyn HirDatabase) -> Result<(), MirLowerError<'_>> { let Some(id) = self.id() else { return Ok(()) }; db.mir_body(id.into()).map(drop) } @@ -2375,7 +2378,7 @@ impl Function { } } - fn fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId, PolyFnSig<'db>) { + fn fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId<'db>, PolyFnSig<'db>) { let fn_ptr = self.fn_ptr_type(db); let TyKind::FnPtr(sig_tys, hdr) = fn_ptr.ty.skip_binder().kind() else { unreachable!(); @@ -2639,7 +2642,7 @@ impl Function { self, db: &dyn HirDatabase, span_formatter: impl Fn(FileId, TextRange) -> String, - ) -> Result { + ) -> Result> { let AnyFunctionId::FunctionId(id) = self.id else { return Err(ConstEvalError::MirEvalError(MirEvalError::NotSupported( "evaluation of builtin derive impl methods is not supported".to_owned(), @@ -2732,7 +2735,7 @@ impl<'db> Param<'db> { Some(self.as_local(db)?.name(db)) } - pub fn as_local(&self, db: &dyn HirDatabase) -> Option { + pub fn as_local(&self, db: &'db dyn HirDatabase) -> Option> { match self.func { Callee::Def(CallableDefId::FunctionId(it)) => { let parent = DefWithBodyId::FunctionId(it); @@ -2919,7 +2922,7 @@ impl Const { } /// Evaluate the constant. - pub fn eval(self, db: &dyn HirDatabase) -> Result, ConstEvalError> { + pub fn eval(self, db: &dyn HirDatabase) -> Result, ConstEvalError<'_>> { let interner = DbInterner::new_no_crate(db); let ty = db.value_ty(self.id.into()).unwrap().instantiate_identity().skip_norm_wip(); db.const_eval(self.id, GenericArgs::empty(interner), None).map(|it| EvaluatedConst { @@ -2937,7 +2940,7 @@ impl HasVisibility for Const { } pub struct EvaluatedConst<'db> { - def: InferBodyId, + def: InferBodyId<'db>, allocation: hir_ty::next_solver::Allocation<'db>, ty: Ty<'db>, } @@ -2947,7 +2950,7 @@ impl<'db> EvaluatedConst<'db> { format!("{}", self.allocation.display(db, display_target)) } - pub fn render_debug(&self, db: &'db dyn HirDatabase) -> Result { + pub fn render_debug(&self, db: &'db dyn HirDatabase) -> Result> { let ty = self.allocation.ty.kind(); if let TyKind::Int(_) | TyKind::Uint(_) = ty { let b = &self.allocation.memory; @@ -3000,7 +3003,7 @@ impl Static { } /// Evaluate the static initializer. - pub fn eval(self, db: &dyn HirDatabase) -> Result, ConstEvalError> { + pub fn eval(self, db: &dyn HirDatabase) -> Result, ConstEvalError<'_>> { let ty = db.value_ty(self.id.into()).unwrap().instantiate_identity().skip_norm_wip(); db.const_eval_static(self.id).map(|it| EvaluatedConst { allocation: it, @@ -4004,17 +4007,21 @@ impl GenericDef { // We cannot call this `Substitution` unfortunately... #[derive(Debug)] pub struct GenericSubstitution<'db> { - owner: TypeOwnerId, + owner: TypeOwnerId<'db>, def: GenericDefId, subst: GenericArgs<'db>, } impl<'db> GenericSubstitution<'db> { - fn new(def: GenericDefId, subst: GenericArgs<'db>, owner: TypeOwnerId) -> Self { + fn new(def: GenericDefId, subst: GenericArgs<'db>, owner: TypeOwnerId<'db>) -> Self { Self { owner, def, subst } } - fn new_from_fn(def: Function, subst: GenericArgs<'db>, owner: TypeOwnerId) -> Option { + fn new_from_fn( + def: Function, + subst: GenericArgs<'db>, + owner: TypeOwnerId<'db>, + ) -> Option { match def.id { AnyFunctionId::FunctionId(def) => Some(Self::new(def.into(), subst, owner)), AnyFunctionId::BuiltinDeriveImplMethod { .. } => None, @@ -4075,18 +4082,18 @@ impl<'db> GenericSubstitution<'db> { /// A single local definition. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Local { +pub struct Local<'db> { pub(crate) parent: ExpressionStoreOwnerId, - pub(crate) parent_infer: InferBodyId, + pub(crate) parent_infer: InferBodyId<'db>, pub(crate) binding_id: BindingId, } -pub struct LocalSource { - pub local: Local, +pub struct LocalSource<'db> { + pub local: Local<'db>, pub source: InFile>, } -impl LocalSource { +impl<'db> LocalSource<'db> { pub fn as_ident_pat(&self) -> Option<&ast::IdentPat> { match &self.source.value { Either::Left(it) => Some(it), @@ -4122,7 +4129,7 @@ impl LocalSource { } } -impl Local { +impl<'db> Local<'db> { pub fn is_param(self, db: &dyn HirDatabase) -> bool { // FIXME: This parses! let src = self.primary_source(db); @@ -4177,7 +4184,7 @@ impl Local { self.binding_id.into_raw().into_u32() } - pub fn ty(self, db: &dyn HirDatabase) -> Type<'_> { + pub fn ty(self, db: &'db dyn HirDatabase) -> Type<'db> { let def = self.parent; let infer = InferenceResult::of(db, self.parent_infer); let ty = infer.binding_ty(self.binding_id); @@ -4185,7 +4192,7 @@ impl Local { } /// All definitions for this local. Example: `let (a$0, _) | (_, a$0) = it;` - pub fn sources(self, db: &dyn HirDatabase) -> Vec { + pub fn sources(self, db: &dyn HirDatabase) -> Vec> { let b; let (_, source_map) = match self.parent { ExpressionStoreOwnerId::Signature(generic_def_id) => { @@ -4226,7 +4233,7 @@ impl Local { } /// The leftmost definition for this local. Example: `let (a$0, _) | (_, a) = it;` - pub fn primary_source(self, db: &dyn HirDatabase) -> LocalSource { + pub fn primary_source(self, db: &dyn HirDatabase) -> LocalSource<'db> { let b; let (_, source_map) = match self.parent { ExpressionStoreOwnerId::Signature(generic_def_id) => { @@ -4267,13 +4274,13 @@ impl Local { } } -impl PartialOrd for Local { +impl PartialOrd for Local<'_> { fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } -impl Ord for Local { +impl Ord for Local<'_> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { self.binding_id.cmp(&other.binding_id) } @@ -4736,7 +4743,7 @@ impl Impl { pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec { let module = trait_.module(db).id; let mut all = Vec::new(); - let mut handle_impls = |impls: &TraitImpls| { + let mut handle_impls = |impls: &TraitImpls<'_>| { impls.for_trait(trait_.id, |impls| match impls { Either::Left(impls) => all.extend(impls.iter().copied().map(Impl::from)), Either::Right(impls) => all.extend(impls.iter().copied().map(Impl::from)), @@ -4860,7 +4867,7 @@ impl Impl { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub struct TraitRef<'db> { - owner: TypeOwnerId, + owner: TypeOwnerId<'db>, trait_ref: hir_ty::next_solver::TraitRef<'db>, } @@ -4891,15 +4898,15 @@ impl<'db> TraitRef<'db> { } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -enum AnyClosureId { - ClosureId(InternedClosureId), - CoroutineClosureId(InternedCoroutineClosureId), +enum AnyClosureId<'db> { + ClosureId(InternedClosureId<'db>), + CoroutineClosureId(InternedCoroutineClosureId<'db>), } #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Closure<'db> { - owner: TypeOwnerId, - id: AnyClosureId, + owner: TypeOwnerId<'db>, + id: AnyClosureId<'db>, subst: GenericArgs<'db>, } @@ -5028,13 +5035,13 @@ impl FnTrait { #[derive(Clone, Debug, PartialEq, Eq)] pub struct ClosureCapture<'db> { owner: ExpressionStoreOwnerId, - infer_owner: InferBodyId, + infer_owner: InferBodyId<'db>, closure: ExprId, capture: &'db hir_ty::closure_analysis::CapturedPlace, } impl<'db> ClosureCapture<'db> { - pub fn local(&self) -> Local { + pub fn local(&self) -> Local<'db> { Local { parent: self.owner, parent_infer: self.infer_owner, @@ -5222,16 +5229,33 @@ impl CaptureUsageSource { } #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -enum TypeOwnerId { +enum TypeOwnerId<'db> { GenericDefId(GenericDefId), BuiltinDeriveImplId(BuiltinDeriveImplId), - AnonConstId(AnonConstId), + AnonConstId(AnonConstId<'db>), // FIXME: What do when we unify two different crates? Currently we just randomly keep one. NoParams(base_db::Crate), } -impl_from!(GenericDefId, BuiltinDeriveImplId, AnonConstId for TypeOwnerId); -impl TypeOwnerId { +impl<'db> From for TypeOwnerId<'db> { + fn from(it: GenericDefId) -> TypeOwnerId<'db> { + TypeOwnerId::GenericDefId(it) + } +} + +impl<'db> From for TypeOwnerId<'db> { + fn from(it: BuiltinDeriveImplId) -> TypeOwnerId<'db> { + TypeOwnerId::BuiltinDeriveImplId(it) + } +} + +impl<'db> From> for TypeOwnerId<'db> { + fn from(it: AnonConstId<'db>) -> TypeOwnerId<'db> { + TypeOwnerId::AnonConstId(it) + } +} + +impl TypeOwnerId<'_> { fn unify(self, other: Self) -> Option { match (self, other) { (TypeOwnerId::NoParams(_), owner) => Some(owner), @@ -5297,7 +5321,7 @@ impl TypeOwnerId { /// with types of different origins will cause errors or panics. Instead, use the `instantiate` methods. #[derive(Clone, Debug)] pub struct Type<'db> { - owner: TypeOwnerId, + owner: TypeOwnerId<'db>, ty: EarlyBinder<'db, Ty<'db>>, } @@ -5492,7 +5516,7 @@ impl<'db> Type<'db> { tys: impl IntoIterator>>, ) -> Self { let interner = DbInterner::new_no_crate(db); - let mut owner = None::; + let mut owner = None::>; let ty = EarlyBinder::bind(Ty::new_tup_from_iter( interner, tys.into_iter().map(|ty| { @@ -6035,7 +6059,10 @@ impl<'db> Type<'db> { } // FIXME: We should probably remove this. - pub fn fingerprint_for_trait_impl(&self, db: &'db dyn HirDatabase) -> Option { + pub fn fingerprint_for_trait_impl( + &self, + db: &'db dyn HirDatabase, + ) -> Option> { fast_reject::simplify_type( DbInterner::new_no_crate(db), self.ty.skip_binder(), @@ -6538,7 +6565,7 @@ impl<'db> Type<'db> { pub fn walk(&self, db: &'db dyn HirDatabase, callback: impl FnMut(Type<'db>)) { struct Visitor<'db, F> { db: &'db dyn HirDatabase, - owner: TypeOwnerId, + owner: TypeOwnerId<'db>, callback: F, visited: FxHashSet>, } @@ -6671,8 +6698,8 @@ pub struct Callable<'db> { #[derive(Clone, PartialEq, Eq, Hash, Debug)] enum Callee<'db> { Def(CallableDefId), - Closure(InternedClosureId, GenericArgs<'db>), - CoroutineClosure(InternedCoroutineClosureId, GenericArgs<'db>), + Closure(InternedClosureId<'db>, GenericArgs<'db>), + CoroutineClosure(InternedCoroutineClosureId<'db>, GenericArgs<'db>), FnPtr, FnImpl(traits::FnTrait), BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId }, @@ -6881,17 +6908,17 @@ pub enum BindingMode { /// For IDE only #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] -pub enum ScopeDef { +pub enum ScopeDef<'db> { ModuleDef(ModuleDef), GenericParam(GenericParam), ImplSelfType(Impl), AdtSelfType(Adt), - Local(Local), + Local(Local<'db>), Label(Label), Unknown, } -impl ScopeDef { +impl ScopeDef<'_> { pub fn all_items(def: PerNs) -> ArrayVec { let mut items = ArrayVec::new(); @@ -6948,7 +6975,7 @@ impl ScopeDef { } } -impl From for ScopeDef { +impl From for ScopeDef<'_> { fn from(item: ItemInNs) -> Self { match item { ItemInNs::Types(id) => ScopeDef::ModuleDef(id), @@ -7006,7 +7033,7 @@ pub enum PredicatePolarity { #[derive(Debug, Clone, PartialEq, Eq)] pub struct TraitPredicate<'db> { inner: hir_ty::next_solver::TraitPredicate<'db>, - owner: TypeOwnerId, + owner: TypeOwnerId<'db>, } impl<'db> TraitPredicate<'db> { @@ -7129,7 +7156,7 @@ impl HasCrate for Module { } } -impl HasCrate for AnonConst { +impl<'db> HasCrate for AnonConst<'db> { fn krate(&self, db: &dyn HirDatabase) -> Crate { hir_def::HasModule::krate(&self.id.loc(db).owner, db).into() } @@ -7251,7 +7278,6 @@ impl_has_name!( Macro, ExternAssocItem, AssocItem, - Local, DeriveHelper, ToolModule, Label, @@ -7275,7 +7301,19 @@ macro_rules! impl_has_name_no_db { }; } -impl_has_name_no_db!(TupleField, StaticLifetime, BuiltinType, BuiltinAttr); +impl_has_name_no_db!(StaticLifetime, BuiltinType, BuiltinAttr); + +impl HasName for Local<'_> { + fn name(&self, db: &dyn HirDatabase) -> Option { + (*self).name(db).into() + } +} + +impl HasName for TupleField<'_> { + fn name(&self, _db: &dyn HirDatabase) -> Option { + (*self).name().into() + } +} impl HasName for Param<'_> { fn name(&self, db: &dyn HirDatabase) -> Option { @@ -7411,10 +7449,10 @@ fn as_name_opt(name: Option) -> Name { #[track_caller] fn generic_args_from_tys<'db>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, args: impl IntoIterator>>, -) -> (GenericArgs<'db>, TypeOwnerId) { - let mut owner = None::; +) -> (GenericArgs<'db>, TypeOwnerId<'db>) { + let mut owner = None::>; let mut args = args.into_iter(); let args = GenericArgs::for_item(interner, def_id, |_, id, _| { if matches!(id, GenericParamId::TypeParamId(_)) diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs index dd4cc7b0df7f..6292d73e4bc5 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs @@ -68,11 +68,11 @@ use crate::{ const CONTINUE_NO_BREAKS: ControlFlow = ControlFlow::Continue(()); #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum PathResolution { +pub enum PathResolution<'db> { /// An item Def(ModuleDef), /// A local binding (only value namespace) - Local(Local), + Local(Local<'db>), /// A type parameter TypeParam(TypeParam), /// A const parameter @@ -83,7 +83,7 @@ pub enum PathResolution { DeriveHelper(DeriveHelper), } -impl PathResolution { +impl<'db> PathResolution<'db> { pub(crate) fn in_type_ns(&self) -> Option { match self { PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())), @@ -117,21 +117,21 @@ impl PathResolution { } #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct PathResolutionPerNs { - pub type_ns: Option, - pub value_ns: Option, - pub macro_ns: Option, +pub struct PathResolutionPerNs<'db> { + pub type_ns: Option>, + pub value_ns: Option>, + pub macro_ns: Option>, } -impl PathResolutionPerNs { +impl<'db> PathResolutionPerNs<'db> { pub fn new( - type_ns: Option, - value_ns: Option, - macro_ns: Option, + type_ns: Option>, + value_ns: Option>, + macro_ns: Option>, ) -> Self { PathResolutionPerNs { type_ns, value_ns, macro_ns } } - pub fn any(&self) -> Option { + pub fn any(&self) -> Option> { self.type_ns.or(self.value_ns).or(self.macro_ns) } } @@ -166,8 +166,8 @@ pub struct Semantics<'db, DB: ?Sized> { } type DefWithoutBodyWithAnonConsts = Either; -type ExprToAnonConst = FxHashMap; -type DefAnonConstsMap = FxHashMap; +type ExprToAnonConst<'db> = FxHashMap>; +type DefAnonConstsMap<'db> = FxHashMap>; pub struct SemanticsImpl<'db> { pub db: &'db dyn HirDatabase, @@ -175,7 +175,7 @@ pub struct SemanticsImpl<'db> { /// MacroCall to its expansion's MacroCallId cache macro_call_cache: RefCell, MacroCallId>>, /// All anon consts defined by a *signature* (not a body). - signature_anon_consts_cache: RefCell, + signature_anon_consts_cache: RefCell>, } impl fmt::Debug for Semantics<'_, DB> { @@ -799,7 +799,11 @@ impl<'db> SemanticsImpl<'db> { /// Checks if renaming `renamed` to `new_name` may introduce conflicts with other locals, /// and returns the conflicting locals. - pub fn rename_conflicts(&self, to_be_renamed: &Local, new_name: &Name) -> Vec { + pub fn rename_conflicts<'a>( + &self, + to_be_renamed: &Local<'a>, + new_name: &Name, + ) -> Vec> { let (store, root_expr) = to_be_renamed.parent_infer.store_and_root_expr(self.db); let resolver = to_be_renamed.parent.resolver(self.db); let starting_expr = store.binding_owner(to_be_renamed.binding_id).unwrap_or(root_expr); @@ -829,7 +833,7 @@ impl<'db> SemanticsImpl<'db> { pub fn as_format_args_parts( &self, string: &ast::String, - ) -> Option>)>> { + ) -> Option, InlineAsmOperand>>)>> { let string_start = string.syntax().text_range().start(); let token = self.wrap_token_infile(string.syntax().clone()); self.descend_into_macros_breakable(token, |token, _| { @@ -886,7 +890,7 @@ impl<'db> SemanticsImpl<'db> { TextRange, HirFileRange, ast::String, - Option>, + Option, InlineAsmOperand>>, )> { let original_token = self.wrap_token_infile(original_token).map(ast::String::cast).transpose()?; @@ -908,7 +912,7 @@ impl<'db> SemanticsImpl<'db> { TextRange, HirFileRange, ast::String, - Option>, + Option, InlineAsmOperand>>, )> { let relative_offset = offset.checked_sub(original_token.value.syntax().text_range().start())?; @@ -940,13 +944,13 @@ impl<'db> SemanticsImpl<'db> { &self, InFile { value: string, file_id }: InFile<&ast::String>, offset: TextSize, - ) -> Option<(TextRange, Option>)> { + ) -> Option<(TextRange, Option, InlineAsmOperand>>)> { debug_assert!(offset <= string.syntax().text_range().len()); let literal = string.syntax().parent().filter(|it| it.kind() == SyntaxKind::LITERAL)?; let parent = literal.parent()?; if let Some(format_args) = ast::FormatArgsExpr::cast(parent.clone()) { let source_analyzer = - &self.analyze_impl(InFile::new(file_id, format_args.syntax()), None, false)?; + self.analyze_impl(InFile::new(file_id, format_args.syntax()), None, false)?; source_analyzer .resolve_offset_in_format_args(self.db, InFile::new(file_id, &format_args), offset) .map(|(range, res)| (range, res.map(Either::Left))) @@ -1910,14 +1914,14 @@ impl<'db> SemanticsImpl<'db> { self.analyze(call.syntax())?.resolve_method_call_as_callable(self.db, call) } - pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option> { + pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option>> { self.analyze(field.syntax())?.resolve_field(field) } pub fn resolve_field_fallback( &self, field: &ast::FieldExpr, - ) -> Option<(Either, Function>, Option>)> + ) -> Option<(Either>, Function>, Option>)> { self.analyze(field.syntax())?.resolve_field_fallback(self.db, field) } @@ -1925,7 +1929,7 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_record_field( &self, field: &ast::RecordExprField, - ) -> Option<(Field, Option, Type<'db>)> { + ) -> Option<(Field, Option>, Type<'db>)> { self.resolve_record_field_with_substitution(field) .map(|(field, local, ty, _)| (field, local, ty)) } @@ -1933,7 +1937,7 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_record_field_with_substitution( &self, field: &ast::RecordExprField, - ) -> Option<(Field, Option, Type<'db>, GenericSubstitution<'db>)> { + ) -> Option<(Field, Option>, Type<'db>, GenericSubstitution<'db>)> { self.analyze(field.syntax())?.resolve_record_field(self.db, field) } @@ -2038,18 +2042,18 @@ impl<'db> SemanticsImpl<'db> { Some(Macro { id }) } - pub fn resolve_path(&self, path: &ast::Path) -> Option { + pub fn resolve_path(&self, path: &ast::Path) -> Option> { self.resolve_path_with_subst(path).map(|(it, _)| it) } - pub fn resolve_path_per_ns(&self, path: &ast::Path) -> Option { + pub fn resolve_path_per_ns(&self, path: &ast::Path) -> Option> { self.analyze(path.syntax())?.resolve_hir_path_per_ns(self.db, path) } pub fn resolve_path_with_subst( &self, path: &ast::Path, - ) -> Option<(PathResolution, Option>)> { + ) -> Option<(PathResolution<'db>, Option>)> { self.analyze(path.syntax())?.resolve_path(self.db, path) } @@ -2118,17 +2122,17 @@ impl<'db> SemanticsImpl<'db> { .unwrap_or_default() } - fn with_ctx) -> T, T>(&self, f: F) -> T { + fn with_ctx) -> T, T>(&self, f: F) -> T { let mut ctx = SourceToDefCtx { db: self.db, cache: &mut self.s2d_cache.borrow_mut() }; f(&mut ctx) } - pub fn to_def(&self, src: &T) -> Option { + pub fn to_def>(&self, src: &T) -> Option { let src = self.find_file(src.syntax()).with_value(src); T::to_def(self, src) } - pub fn to_def2(&self, src: InFile<&T>) -> Option { + pub fn to_def2>(&self, src: InFile<&T>) -> Option { T::to_def(self, src) } @@ -2191,9 +2195,9 @@ impl<'db> SemanticsImpl<'db> { fn populate_anon_const_cache_for<'a>( &self, - cache: &'a mut DefAnonConstsMap, + cache: &'a mut DefAnonConstsMap<'db>, def: DefWithoutBodyWithAnonConsts, - ) -> &'a ExprToAnonConst { + ) -> &'a ExprToAnonConst<'db> { cache.entry(def).or_insert_with(|| match def { Either::Left(def) => { let all_anon_consts = @@ -2216,7 +2220,7 @@ impl<'db> SemanticsImpl<'db> { &self, def: DefWithoutBodyWithAnonConsts, root_expr: ExprId, - ) -> Option { + ) -> Option> { let mut cache = self.signature_anon_consts_cache.borrow_mut(); let anon_consts_map = self.populate_anon_const_cache_for(&mut cache, def); anon_consts_map.get(&root_expr).copied() @@ -2227,7 +2231,7 @@ impl<'db> SemanticsImpl<'db> { def: ExpressionStoreOwnerId, store: &ExpressionStore, node: ExprOrPatId, - ) -> Option { + ) -> Option> { let handle_def_without_body = |def| { let root_expr = match node { ExprOrPatId::ExprId(expr) => store.find_root_for_expr(expr), @@ -2248,7 +2252,7 @@ impl<'db> SemanticsImpl<'db> { fn with_all_infers_for_store( &self, owner: ExpressionStoreOwnerId, - callback: &mut dyn FnMut(&'db InferenceResult), + callback: &mut dyn FnMut(&'db InferenceResult<'db>), ) { let mut handle_def_without_body = |def| { let mut cache = self.signature_anon_consts_cache.borrow_mut(); @@ -2469,7 +2473,7 @@ impl<'db> SemanticsImpl<'db> { &self, element: Either<&ast::Expr, &ast::StmtList>, text_range: TextRange, - ) -> Option> { + ) -> Option>> { let sa = self.analyze(element.either(|e| e.syntax(), |s| s.syntax()))?; let infer_body = sa.infer_body?; let store = sa.store()?; @@ -2518,7 +2522,7 @@ impl<'db> SemanticsImpl<'db> { let mut exprs: Vec<_> = exprs.into_iter().filter_map(|e| sa.expr_id(e).and_then(|e| e.as_expr())).collect(); - let mut locals: FxIndexSet = FxIndexSet::default(); + let mut locals: FxIndexSet> = FxIndexSet::default(); let mut add_to_locals_used = |id, parent_expr| { let path = match id { ExprOrPatId::ExprId(expr_id) => { @@ -2649,16 +2653,16 @@ fn macro_call_to_macro_id( } } -pub trait ToDef: AstNode + Clone { +pub trait ToDef<'db>: AstNode + Clone { type Def; - fn to_def(sema: &SemanticsImpl<'_>, src: InFile<&Self>) -> Option; + fn to_def(sema: &SemanticsImpl<'db>, src: InFile<&Self>) -> Option; } macro_rules! to_def_impls { - ($(($def:path, $ast:path, $meth:ident)),* ,) => {$( - impl ToDef for $ast { + ($(($def:ty, $ast:path, $meth:ident)),* ,) => {$( + impl<'db> ToDef<'db> for $ast { type Def = $def; - fn to_def(sema: &SemanticsImpl<'_>, src: InFile<&Self>) -> Option { + fn to_def(sema: &SemanticsImpl<'db>, src: InFile<&Self>) -> Option { sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from) } } @@ -2685,7 +2689,7 @@ to_def_impls![ (crate::ConstParam, ast::ConstParam, const_param_to_def), (crate::GenericParam, ast::GenericParam, generic_param_to_def), (crate::Macro, ast::Macro, macro_to_def), - (crate::Local, ast::SelfParam, self_param_to_def), + (crate::Local<'db>, ast::SelfParam, self_param_to_def), (crate::Label, ast::Label, label_to_def), (crate::Adt, ast::Adt, adt_to_def), (crate::ExternCrateDecl, ast::ExternCrate, extern_crate_to_def), @@ -2694,10 +2698,10 @@ to_def_impls![ (MacroCallId, ast::MacroCall, macro_call_to_macro_call), ]; -impl ToDef for ast::IdentPat { - type Def = crate::Local; +impl<'db> ToDef<'db> for ast::IdentPat { + type Def = crate::Local<'db>; - fn to_def(sema: &SemanticsImpl<'_>, src: InFile<&Self>) -> Option { + fn to_def(sema: &SemanticsImpl<'db>, src: InFile<&Self>) -> Option { sema.with_ctx(|ctx| ctx.bind_pat_to_def(src, sema)) } } @@ -2728,7 +2732,7 @@ fn find_root(node: &SyntaxNode) -> SyntaxNode { #[derive(Debug)] pub struct SemanticsScope<'db> { pub db: &'db dyn HirDatabase, - infer_body: Option, + infer_body: Option>, file_id: HirFileId, resolver: Resolver<'db>, } @@ -2769,7 +2773,7 @@ impl<'db> SemanticsScope<'db> { } /// Calls the passed closure `f` on all names in scope. - pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef)) { + pub fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef<'db>)) { let scope = self.resolver.names_in_scope(self.db); for (name, entries) in scope { for entry in entries { @@ -2806,7 +2810,7 @@ impl<'db> SemanticsScope<'db> { /// Resolve a path as-if it was written at the given scope. This is /// necessary a heuristic, as it doesn't take hygiene into account. - pub fn speculative_resolve(&self, ast_path: &ast::Path) -> Option { + pub fn speculative_resolve(&self, ast_path: &ast::Path) -> Option> { let mut kind = PathKind::Plain; let mut segments = vec![]; let mut first = true; @@ -2854,7 +2858,7 @@ impl<'db> SemanticsScope<'db> { /// `Ty::Assoc` syntax). pub fn assoc_type_shorthand_candidates( &self, - resolution: &PathResolution, + resolution: &PathResolution<'db>, mut cb: impl FnMut(TypeAlias), ) { let (Some(def), Some(resolution)) = (self.resolver.generic_def(), resolution.in_type_ns()) diff --git a/crates/hir/src/semantics/source_to_def.rs b/crates/hir/src/semantics/source_to_def.rs index 583b3e4bdace..e900b9bd90b1 100644 --- a/crates/hir/src/semantics/source_to_def.rs +++ b/crates/hir/src/semantics/source_to_def.rs @@ -178,7 +178,7 @@ pub(super) struct SourceToDefCtx<'db, 'cache> { pub(super) cache: &'cache mut SourceToDefCache<'db>, } -impl SourceToDefCtx<'_, '_> { +impl<'db> SourceToDefCtx<'db, '_> { pub(super) fn file_to_def(&mut self, file: FileId) -> &SmallVec<[ModuleId; 1]> { let _p = tracing::info_span!("SourceToDefCtx::file_to_def").entered(); self.cache.file_to_def_cache.entry(file).or_insert_with(|| { @@ -348,8 +348,8 @@ impl SourceToDefCtx<'_, '_> { pub(super) fn bind_pat_to_def( &mut self, src: InFile<&ast::IdentPat>, - semantics: &SemanticsImpl<'_>, - ) -> Option { + semantics: &SemanticsImpl<'db>, + ) -> Option> { let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?; let (store, source_map) = ExpressionStore::with_source_map(self.db, container); let src = src.cloned().map(ast::Pat::from); diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs index 687f130af482..27f188588829 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs @@ -76,8 +76,8 @@ pub(crate) struct SourceAnalyzer<'db> { pub(crate) file_id: HirFileId, pub(crate) resolver: Resolver<'db>, pub(crate) body_or_sig: Option>, - pub(crate) type_owner: TypeOwnerId, - pub(crate) infer_body: Option, + pub(crate) type_owner: TypeOwnerId<'db>, + pub(crate) infer_body: Option>, } #[derive(Debug)] @@ -86,19 +86,19 @@ pub(crate) enum BodyOrSig<'db> { def: DefWithBodyId, body: &'db Body, source_map: &'db BodySourceMap, - infer: Option<&'db InferenceResult>, + infer: Option<&'db InferenceResult<'db>>, }, VariantFields { def: VariantId, store: &'db ExpressionStore, source_map: &'db ExpressionStoreSourceMap, - infer: Option<&'db InferenceResult>, + infer: Option<&'db InferenceResult<'db>>, }, Sig { def: GenericDefId, store: &'db ExpressionStore, source_map: &'db ExpressionStoreSourceMap, - infer: Option<&'db InferenceResult>, + infer: Option<&'db InferenceResult<'db>>, #[expect(dead_code)] generics: &'db GenericParams, }, @@ -128,7 +128,7 @@ impl<'db> SourceAnalyzer<'db> { def: DefWithBodyId, node @ InFile { file_id, .. }: InFile<&SyntaxNode>, offset: Option, - infer: Option<&'db InferenceResult>, + infer: Option<&'db InferenceResult<'db>>, ) -> SourceAnalyzer<'db> { let (body, source_map) = Body::with_source_map(db, def); let scopes = ExprScopes::of(db, def); @@ -294,11 +294,11 @@ impl<'db> SourceAnalyzer<'db> { }) } - fn infer(&self) -> Option<&InferenceResult> { - self.body_or_sig.as_ref().and_then(|it| match it { + fn infer(&self) -> Option<&'db InferenceResult<'db>> { + self.body_or_sig.as_ref().and_then(|it| match *it { BodyOrSig::VariantFields { infer, .. } | BodyOrSig::Sig { infer, .. } - | BodyOrSig::Body { infer, .. } => infer.as_deref(), + | BodyOrSig::Body { infer, .. } => infer, }) } @@ -310,9 +310,9 @@ impl<'db> SourceAnalyzer<'db> { &self, ) -> Option<( ExpressionStoreOwnerId, - &ExpressionStore, - &ExpressionStoreSourceMap, - Option<&InferenceResult>, + &'db ExpressionStore, + &'db ExpressionStoreSourceMap, + Option<&'db InferenceResult<'db>>, )> { self.body_or_sig.as_ref().map(|it| match *it { BodyOrSig::VariantFields { def, store, source_map, infer, .. } => { @@ -327,18 +327,18 @@ impl<'db> SourceAnalyzer<'db> { }) } - pub(crate) fn store(&self) -> Option<&ExpressionStore> { - self.body_or_sig.as_ref().map(|it| match it { - BodyOrSig::Sig { store, .. } => &**store, - BodyOrSig::VariantFields { store, .. } => &**store, + pub(crate) fn store(&self) -> Option<&'db ExpressionStore> { + self.body_or_sig.as_ref().map(|it| match *it { + BodyOrSig::Sig { store, .. } => store, + BodyOrSig::VariantFields { store, .. } => store, BodyOrSig::Body { body, .. } => &body.store, }) } - pub(crate) fn store_sm(&self) -> Option<&ExpressionStoreSourceMap> { - self.body_or_sig.as_ref().map(|it| match it { - BodyOrSig::Sig { source_map, .. } => &**source_map, - BodyOrSig::VariantFields { source_map, .. } => &**source_map, + pub(crate) fn store_sm(&self) -> Option<&'db ExpressionStoreSourceMap> { + self.body_or_sig.as_ref().map(|it| match *it { + BodyOrSig::Sig { source_map, .. } => source_map, + BodyOrSig::VariantFields { source_map, .. } => source_map, BodyOrSig::Body { source_map, .. } => &source_map.store, }) } @@ -467,8 +467,8 @@ impl<'db> SourceAnalyzer<'db> { .lower_ty(type_ref); struct VarsCtx<'a, 'db> { - types: &'db DefaultAny<'db>, - infer: Option<&'a InferenceResult>, + types: &'a DefaultAny<'db>, + infer: Option<&'a InferenceResult<'db>>, } impl<'db> TyLoweringInferVarsCtx<'db> for VarsCtx<'_, 'db> { @@ -507,7 +507,7 @@ impl<'db> SourceAnalyzer<'db> { fn expr_id_is_diverging( &self, store: &ExpressionStore, - infer: &InferenceResult, + infer: &InferenceResult<'_>, expr_id: ExprOrPatId, ) -> bool { // FIXME: This is an approximation, perhaps we need to store a set of diverging exprs in inference? @@ -681,7 +681,7 @@ impl<'db> SourceAnalyzer<'db> { pub(crate) fn resolve_field( &self, field: &ast::FieldExpr, - ) -> Option> { + ) -> Option>> { let def = self.infer_body?; let expr_id = self.expr_id(field.clone().into())?.as_expr()?; self.infer()?.field_resolution(expr_id).map(|it| { @@ -692,7 +692,7 @@ impl<'db> SourceAnalyzer<'db> { fn field_subst( &self, field_expr: ExprId, - infer: &InferenceResult, + infer: &InferenceResult<'_>, _db: &'db dyn HirDatabase, ) -> Option> { let body = self.store()?; @@ -707,7 +707,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, field: &ast::FieldExpr, - ) -> Option<(Either, Function>, Option>)> + ) -> Option<(Either>, Function>, Option>)> { let def = self.infer_body?; let expr_id = self.expr_id(field.clone().into())?.as_expr()?; @@ -940,7 +940,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, field: &ast::RecordExprField, - ) -> Option<(Field, Option, Type<'db>, GenericSubstitution<'db>)> { + ) -> Option<(Field, Option>, Type<'db>, GenericSubstitution<'db>)> { let record_expr = ast::RecordExpr::cast(field.syntax().parent().and_then(|p| p.parent())?)?; let expr = ast::Expr::from(record_expr); let expr_id = self.store_sm()?.node_expr(InFile::new(self.file_id, &expr))?; @@ -1151,7 +1151,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, path: &ast::Path, - ) -> Option<(PathResolution, Option>)> { + ) -> Option<(PathResolution<'db>, Option>)> { let parent = path.syntax().parent(); let parent = || parent.clone(); @@ -1477,9 +1477,9 @@ impl<'db> SourceAnalyzer<'db> { pub(crate) fn resolve_hir_path_per_ns( &self, - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, path: &ast::Path, - ) -> Option { + ) -> Option> { let mut collector = ExprCollector::new(db, self.resolver.module(), self.file_id); let hir_path = collector.lower_path(path.clone(), &mut ExprCollector::impl_trait_error_allocator)?; @@ -1618,7 +1618,7 @@ impl<'db> SourceAnalyzer<'db> { db: &'db dyn HirDatabase, format_args: InFile<&ast::FormatArgsExpr>, offset: TextSize, - ) -> Option<(TextRange, Option)> { + ) -> Option<(TextRange, Option>)> { let (hygiene, implicits) = self.store_sm()?.implicit_format_args(format_args)?; implicits.iter().find(|(range, _)| range.contains_inclusive(offset)).map(|(range, name)| { ( @@ -1656,9 +1656,9 @@ impl<'db> SourceAnalyzer<'db> { pub(crate) fn as_format_args_parts<'a>( &'a self, - db: &'a dyn HirDatabase, + db: &'db dyn HirDatabase, format_args: InFile<&ast::FormatArgsExpr>, - ) -> Option)> + 'a> { + ) -> Option>)> + 'a> { let (hygiene, names) = self.store_sm()?.implicit_format_args(format_args)?; Some(names.iter().map(move |(range, name)| { ( @@ -1836,14 +1836,14 @@ fn adjust( } #[inline] -pub(crate) fn resolve_hir_path( - db: &dyn HirDatabase, - resolver: &Resolver<'_>, - infer_body: Option, +pub(crate) fn resolve_hir_path<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, + infer_body: Option>, path: &Path, hygiene: HygieneId, store: Option<&ExpressionStore>, -) -> Option { +) -> Option> { resolve_hir_path_(db, resolver, infer_body, path, false, hygiene, store, false).any() } @@ -1859,16 +1859,16 @@ pub(crate) fn resolve_hir_path_as_attr_macro( .map(Into::into) } -fn resolve_hir_path_( - db: &dyn HirDatabase, - resolver: &Resolver<'_>, - infer_body: Option, +fn resolve_hir_path_<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, + infer_body: Option>, path: &Path, prefer_value_ns: bool, hygiene: HygieneId, store: Option<&ExpressionStore>, resolve_per_ns: bool, -) -> PathResolutionPerNs { +) -> PathResolutionPerNs<'db> { let types = || { let (ty, unresolved) = match path.type_anchor() { Some(type_ref) => resolver.generic_def().and_then(|def| { @@ -1982,14 +1982,14 @@ fn resolve_hir_path_( } } -fn resolve_hir_value_path( - db: &dyn HirDatabase, - resolver: &Resolver<'_>, +fn resolve_hir_value_path<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, store_owner: Option, - infer_body: Option, + infer_body: Option>, path: &Path, hygiene: HygieneId, -) -> Option { +) -> Option> { resolver.resolve_path_in_value_ns_fully(db, path, hygiene).and_then(|val| { let res = match val { ValueNs::LocalBinding(binding_id) => { @@ -2021,12 +2021,12 @@ fn resolve_hir_value_path( /// } /// ``` /// then we know that `foo` in `my::foo::Bar` refers to the module, not the function. -fn resolve_hir_path_qualifier( - db: &dyn HirDatabase, - resolver: &Resolver<'_>, +fn resolve_hir_path_qualifier<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, path: &Path, store: &ExpressionStore, -) -> Option { +) -> Option> { (|| { let (ty, unresolved) = match path.type_anchor() { Some(type_ref) => resolver.generic_def().and_then(|def| { @@ -2115,7 +2115,7 @@ pub(crate) fn name_hygiene(db: &dyn HirDatabase, name: InFile<&SyntaxNode>) -> H fn record_literal_matched_fields( db: &dyn HirDatabase, - infer: &InferenceResult, + infer: &InferenceResult<'_>, id: ExprId, expr: &Expr, ) -> Option<(VariantId, Vec)> { @@ -2147,7 +2147,7 @@ fn record_literal_matched_fields( fn record_pattern_matched_fields( db: &dyn HirDatabase, - infer: &InferenceResult, + infer: &InferenceResult<'_>, id: PatId, pat: &Pat, ) -> Option<(VariantId, Vec)> { diff --git a/crates/hir/src/term_search/expr.rs b/crates/hir/src/term_search/expr.rs index a824c8bdca5d..07994268696e 100644 --- a/crates/hir/src/term_search/expr.rs +++ b/crates/hir/src/term_search/expr.rs @@ -65,7 +65,7 @@ pub enum Expr<'db> { /// Static variable Static(Static), /// Local variable - Local(Local), + Local(Local<'db>), /// Constant generic parameter ConstParam(ConstParam), /// Well known type (such as `true` for bool) diff --git a/crates/hir/src/term_search/tactics.rs b/crates/hir/src/term_search/tactics.rs index 2b7f7da3bf0d..bed785eb6aad 100644 --- a/crates/hir/src/term_search/tactics.rs +++ b/crates/hir/src/term_search/tactics.rs @@ -37,7 +37,7 @@ use super::{LookupTable, NewTypesKey, TermSearchCtx}; /// depend on the current state of `lookup`_ pub(super) fn trivial<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - defs: &'a FxHashSet, + defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { let db = ctx.sema.db; @@ -102,7 +102,7 @@ pub(super) fn trivial<'a, 'lt, 'db, DB: HirDatabase>( /// depend on the current state of `lookup`_ pub(super) fn assoc_const<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - defs: &'a FxHashSet, + defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { let db = ctx.sema.db; @@ -150,7 +150,7 @@ pub(super) fn assoc_const<'a, 'lt, 'db, DB: HirDatabase>( /// * `should_continue` - Function that indicates when to stop iterating pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - _defs: &'a FxHashSet, + _defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { @@ -303,7 +303,7 @@ pub(super) fn data_constructor<'a, 'lt, 'db, DB: HirDatabase>( /// * `should_continue` - Function that indicates when to stop iterating pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - defs: &'a FxHashSet, + defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { @@ -440,7 +440,7 @@ pub(super) fn free_function<'a, 'lt, 'db, DB: HirDatabase>( /// * `should_continue` - Function that indicates when to stop iterating pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - _defs: &'a FxHashSet, + _defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { @@ -561,7 +561,7 @@ pub(super) fn impl_method<'a, 'lt, 'db, DB: HirDatabase>( /// * `should_continue` - Function that indicates when to stop iterating pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - _defs: &'a FxHashSet, + _defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { @@ -605,7 +605,7 @@ pub(super) fn struct_projection<'a, 'lt, 'db, DB: HirDatabase>( /// * `lookup` - Lookup table for types pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - _defs: &'a FxHashSet, + _defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { let db = ctx.sema.db; @@ -637,7 +637,7 @@ pub(super) fn famous_types<'a, 'lt, 'db, DB: HirDatabase>( /// * `should_continue` - Function that indicates when to stop iterating pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - _defs: &'a FxHashSet, + _defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { @@ -745,7 +745,7 @@ pub(super) fn impl_static_method<'a, 'lt, 'db, DB: HirDatabase>( /// * `should_continue` - Function that indicates when to stop iterating pub(super) fn make_tuple<'a, 'lt, 'db, DB: HirDatabase>( ctx: &'a TermSearchCtx<'_, 'db, DB>, - _defs: &'a FxHashSet, + _defs: &'a FxHashSet>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator> + use<'a, 'db, 'lt, DB> { diff --git a/crates/ide-assists/src/handlers/convert_bool_to_enum.rs b/crates/ide-assists/src/handlers/convert_bool_to_enum.rs index 4c3168219fc6..865995def013 100644 --- a/crates/ide-assists/src/handlers/convert_bool_to_enum.rs +++ b/crates/ide-assists/src/handlers/convert_bool_to_enum.rs @@ -95,16 +95,16 @@ pub(crate) fn convert_bool_to_enum(acc: &mut Assists, ctx: &AssistContext<'_, '_ ) } -struct BoolNodeData { +struct BoolNodeData<'db> { target_node: SyntaxNode, name: ast::Name, ty_annotation: Option, initializer: Option, - definition: Definition, + definition: Definition<'db>, } /// Attempts to find an appropriate node to apply the action to. -fn find_bool_node(ctx: &AssistContext<'_, '_>) -> Option { +fn find_bool_node<'db>(ctx: &AssistContext<'_, 'db>) -> Option> { let name = ctx.find_node_at_offset::()?; if let Some(ident_pat) = name.syntax().parent().and_then(ast::IdentPat::cast) { @@ -213,7 +213,7 @@ fn replace_usages( edit: &mut SourceChangeBuilder, ctx: &AssistContext<'_, '_>, usages: UsageSearchResult, - target_definition: Definition, + target_definition: Definition<'_>, target_module: &hir::Module, delayed_mutations: &mut Vec<(FileId, ImportScope, ast::Path)>, make: &SyntaxFactory, @@ -427,7 +427,7 @@ fn find_negated_usage(name: &ast::NameLike) -> Option<(ast::PrefixExpr, ast::Exp fn find_record_expr_usage( name: &ast::NameLike, got_field: hir::Field, - target_definition: Definition, + target_definition: Definition<'_>, ) -> Option<(ast::RecordExprField, ast::Expr)> { let name_ref = name.as_name_ref()?; let record_field = ast::RecordExprField::for_field_name(name_ref)?; diff --git a/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs b/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs index a6a47d78a8e0..d67decc19a39 100644 --- a/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs +++ b/crates/ide-assists/src/handlers/convert_tuple_struct_to_named_struct.rs @@ -168,7 +168,7 @@ fn process_struct_name_reference( r: FileReference, editor: &SyntaxEditor, source: &ast::SourceFile, - strukt_def: &Definition, + strukt_def: &Definition<'_>, names: &[ast::Name], ) -> Option<()> { let make = editor.make(); diff --git a/crates/ide-assists/src/handlers/expand_glob_import.rs b/crates/ide-assists/src/handlers/expand_glob_import.rs index f5d2a6cfc519..a2b15fd4c252 100644 --- a/crates/ide-assists/src/handlers/expand_glob_import.rs +++ b/crates/ide-assists/src/handlers/expand_glob_import.rs @@ -238,24 +238,24 @@ fn find_parent_and_path( } } -fn def_is_referenced_in(def: Definition, ctx: &AssistContext<'_, '_>) -> bool { +fn def_is_referenced_in<'db>(def: Definition<'db>, ctx: &AssistContext<'_, 'db>) -> bool { let search_scope = SearchScope::single_file(ctx.file_id()); def.usages(&ctx.sema).in_scope(&search_scope).at_least_one() } #[derive(Debug, Clone)] -struct Ref { +struct Ref<'db> { // could be alias visible_name: Name, - def: Definition, + def: Definition<'db>, is_pub: bool, } -impl Ref { +impl<'db> Ref<'db> { fn from_scope_def( - ctx: &AssistContext<'_, '_>, + ctx: &AssistContext<'_, 'db>, name: Name, - scope_def: ScopeDef, + scope_def: ScopeDef<'db>, ) -> Option { match scope_def { ScopeDef::ModuleDef(def) => Some(Ref { @@ -269,10 +269,10 @@ impl Ref { } #[derive(Debug, Clone)] -struct Refs(Vec); +struct Refs<'db>(Vec>); -impl Refs { - fn used_refs(&self, ctx: &AssistContext<'_, '_>) -> Refs { +impl<'db> Refs<'db> { + fn used_refs(&self, ctx: &AssistContext<'_, 'db>) -> Refs<'db> { Refs( self.0 .clone() @@ -296,18 +296,18 @@ impl Refs { ) } - fn filter_out_by_defs(&self, defs: Vec) -> Refs { + fn filter_out_by_defs(&self, defs: Vec>) -> Refs<'db> { Refs(self.0.clone().into_iter().filter(|r| !defs.contains(&r.def)).collect()) } } -fn find_refs_in_mod( - ctx: &AssistContext<'_, '_>, +fn find_refs_in_mod<'db>( + ctx: &AssistContext<'_, 'db>, expandable: Expandable, current_module: Module, visible_from: Module, must_be_pub: bool, -) -> Refs { +) -> Refs<'db> { match expandable { Expandable::Module(module) => { let module_scope = module.scope(ctx.db(), Some(visible_from)); @@ -376,7 +376,7 @@ fn is_visible_from(ctx: &AssistContext<'_, '_>, expandable: &Expandable, from: M // use foo::*$0; // use baz::Baz; // ↑ --------------- -fn find_imported_defs(ctx: &AssistContext<'_, '_>, use_item: Use) -> Vec { +fn find_imported_defs<'db>(ctx: &AssistContext<'_, 'db>, use_item: Use) -> Vec> { [Direction::Prev, Direction::Next] .into_iter() .flat_map(|dir| { @@ -401,7 +401,10 @@ fn find_imported_defs(ctx: &AssistContext<'_, '_>, use_item: Use) -> Vec) -> Vec { +fn find_names_to_import<'db>( + refs_in_target: Refs<'db>, + imported_defs: Vec>, +) -> Vec { let final_refs = refs_in_target.filter_out_by_defs(imported_defs); final_refs.0.iter().map(|r| r.visible_name.clone()).collect() } diff --git a/crates/ide-assists/src/handlers/extract_function.rs b/crates/ide-assists/src/handlers/extract_function.rs index f8572dcd3a85..c2eb49dde569 100644 --- a/crates/ide-assists/src/handlers/extract_function.rs +++ b/crates/ide-assists/src/handlers/extract_function.rs @@ -324,7 +324,7 @@ struct Function<'db> { control_flow: ControlFlow<'db>, ret_ty: RetType<'db>, body: FunctionBody, - outliving_locals: Vec, + outliving_locals: Vec>, /// Whether at least one of the container's tail expr is contained in the range we're extracting. contains_tail_expr: bool, mods: ContainerInfo<'db>, @@ -332,7 +332,7 @@ struct Function<'db> { #[derive(Debug)] struct Param<'db> { - var: Local, + var: Local<'db>, ty: hir::Type<'db>, move_local: bool, requires_mut: bool, @@ -441,8 +441,8 @@ enum FunctionBody { } #[derive(Debug)] -struct OutlivedLocal { - local: Local, +struct OutlivedLocal<'db> { + local: Local<'db>, mut_usage_outside_body: bool, } @@ -452,7 +452,7 @@ struct OutlivedLocal { struct LocalUsages(ide_db::search::UsageSearchResult); impl LocalUsages { - fn find_local_usages(ctx: &AssistContext<'_, '_>, var: Local) -> Self { + fn find_local_usages<'db>(ctx: &AssistContext<'_, 'db>, var: Local<'db>) -> Self { Self( Definition::Local(var) .usages(&ctx.sema) @@ -807,10 +807,10 @@ impl FunctionBody { impl FunctionBody { /// Analyzes a function body, returning the used local variables that are referenced in it as well as /// whether it contains an await expression. - fn analyze( + fn analyze<'db>( &self, - sema: &Semantics<'_, RootDatabase>, - ) -> (FxIndexSet, Option) { + sema: &Semantics<'db, RootDatabase>, + ) -> (FxIndexSet>, Option) { let mut self_param = None; let mut res = FxIndexSet::default(); @@ -819,7 +819,7 @@ impl FunctionBody { FunctionBody::Span { parent, text_range, .. } => (*text_range, Either::Right(parent)), }; - let mut add_name_if_local = |local_ref: Local| { + let mut add_name_if_local = |local_ref: Local<'db>| { // locals defined inside macros are not relevant to us let InFile { file_id, value } = local_ref.primary_source(sema.db).source; if !file_id.is_macro() { @@ -965,10 +965,10 @@ impl FunctionBody { } /// Local variables defined inside `body` that are accessed outside of it - fn ret_values<'a>( + fn ret_values<'a, 'db>( &self, - ctx: &'a AssistContext<'_, '_>, - ) -> impl Iterator + 'a { + ctx: &'a AssistContext<'_, 'db>, + ) -> impl Iterator> + 'a { let range = self.text_range(); locals_defined_in_body(&ctx.sema, self) .into_iter() @@ -1070,7 +1070,7 @@ impl FunctionBody { &self, ctx: &AssistContext<'_, 'db>, container_info: &ContainerInfo<'db>, - locals: FxIndexSet, + locals: FxIndexSet>, ) -> Vec> { locals .into_iter() @@ -1254,10 +1254,10 @@ fn path_element_of(reference: &FileReference) -> Option { } /// list local variables defined inside `body` -fn locals_defined_in_body( - sema: &Semantics<'_, RootDatabase>, +fn locals_defined_in_body<'db>( + sema: &Semantics<'db, RootDatabase>, body: &FunctionBody, -) -> FxIndexSet { +) -> FxIndexSet> { // FIXME: this doesn't work well with macros // see https://github.com/rust-lang/rust-analyzer/pull/7535#discussion_r570048550 let mut res = FxIndexSet::default(); @@ -1272,11 +1272,11 @@ fn locals_defined_in_body( } /// Returns usage details if local variable is used after(outside of) body -fn local_outlives_body( - ctx: &AssistContext<'_, '_>, +fn local_outlives_body<'db>( + ctx: &AssistContext<'_, 'db>, body_range: TextRange, - local: Local, -) -> Option { + local: Local<'db>, +) -> Option> { let usages = LocalUsages::find_local_usages(ctx, local); let mut has_mut_usages = false; let mut any_outlives = false; @@ -1299,7 +1299,7 @@ fn local_outlives_body( fn is_defined_outside_of_body( ctx: &AssistContext<'_, '_>, body: &FunctionBody, - src: &LocalSource, + src: &LocalSource<'_>, ) -> bool { src.original_file(ctx.db()) == ctx.file_id() && !body.contains_node(src.syntax()) } @@ -1547,7 +1547,7 @@ impl<'db> FlowHandler<'db> { fn path_expr_from_local( make: &SyntaxFactory, ctx: &AssistContext<'_, '_>, - var: Local, + var: Local<'_>, edition: Edition, ) -> ast::Expr { let name = var.name(ctx.db()).display(ctx.db(), edition).to_string(); @@ -2012,10 +2012,10 @@ fn make_ty( make.ty(&ty_str) } -fn rewrite_body_segment( - ctx: &AssistContext<'_, '_>, +fn rewrite_body_segment<'db>( + ctx: &AssistContext<'_, 'db>, to_this_param: Option, - params: &[Param<'_>], + params: &[Param<'db>], handler: &FlowHandler<'_>, syntax: &SyntaxNode, ) -> SyntaxNode { @@ -2030,15 +2030,15 @@ fn rewrite_body_segment( } /// change all usages to account for added `&`/`&mut` for some params -fn fix_param_usages( +fn fix_param_usages<'db>( editor: &SyntaxEditor, source_syntax: &SyntaxNode, syntax: &SyntaxNode, - ctx: &AssistContext<'_, '_>, - to_this_param: Option, - params: &[Param<'_>], + ctx: &AssistContext<'_, 'db>, + to_this_param: Option>, + params: &[Param<'db>], ) { - let mut usages_for_param: Vec<(&Param<'_>, Vec)> = Vec::new(); + let mut usages_for_param: Vec<(&Param<'db>, Vec)> = Vec::new(); let mut usages_for_self_param: Vec = Vec::new(); let source_range = source_syntax.text_range(); let syntax_offset = source_range.start() - syntax.text_range().start(); diff --git a/crates/ide-assists/src/handlers/extract_module.rs b/crates/ide-assists/src/handlers/extract_module.rs index 40c54e98820a..60a1c7ab44eb 100644 --- a/crates/ide-assists/src/handlers/extract_module.rs +++ b/crates/ide-assists/src/handlers/extract_module.rs @@ -362,11 +362,11 @@ impl Module { (refs, adt_fields, use_stmts_to_be_inserted) } - fn expand_and_group_usages_file_wise( + fn expand_and_group_usages_file_wise<'db>( &self, - ctx: &AssistContext<'_, '_>, + ctx: &AssistContext<'_, 'db>, replace_range: TextRange, - node_def: Definition, + node_def: Definition<'db>, refs_in_files: &mut FxHashMap>, use_stmts_to_be_inserted: &mut FxHashMap, ) { @@ -535,12 +535,12 @@ impl Module { imports_to_remove } - fn process_def_in_sel( + fn process_def_in_sel<'db>( &mut self, - def: Definition, + def: Definition<'db>, use_node: &SyntaxNode, curr_parent_module: &Option, - ctx: &AssistContext<'_, '_>, + ctx: &AssistContext<'_, 'db>, make: &SyntaxFactory, ) -> Option { //We only need to find in the current file @@ -738,7 +738,7 @@ fn check_intersection_and_push( } fn check_def_in_mod_and_out_sel( - def: Definition, + def: Definition<'_>, ctx: &AssistContext<'_, '_>, curr_parent_module: &Option, selection_range: TextRange, diff --git a/crates/ide-assists/src/handlers/extract_variable.rs b/crates/ide-assists/src/handlers/extract_variable.rs index e1b91c9e89d5..873f7a8f906f 100644 --- a/crates/ide-assists/src/handlers/extract_variable.rs +++ b/crates/ide-assists/src/handlers/extract_variable.rs @@ -513,7 +513,7 @@ impl Anchor { } } -fn like_const_value(ctx: &AssistContext<'_, '_>, path_resolution: hir::PathResolution) -> bool { +fn like_const_value(ctx: &AssistContext<'_, '_>, path_resolution: hir::PathResolution<'_>) -> bool { let db = ctx.db(); let adt_like_const_value = |adt: Option| matches!(adt, Some(hir::Adt::Struct(s)) if s.kind(db) == hir::StructKind::Unit); match path_resolution { diff --git a/crates/ide-assists/src/handlers/inline_call.rs b/crates/ide-assists/src/handlers/inline_call.rs index 8897e59355e4..c9aaa27f71e6 100644 --- a/crates/ide-assists/src/handlers/inline_call.rs +++ b/crates/ide-assists/src/handlers/inline_call.rs @@ -339,12 +339,12 @@ fn get_fn_params<'db>( Some(params) } -fn inline( - sema: &Semantics<'_, RootDatabase>, +fn inline<'db>( + sema: &Semantics<'db, RootDatabase>, function_def_file_id: EditionedFileId, function: hir::Function, fn_body: &ast::BlockExpr, - params: &[(ast::Pat, Option, hir::Param<'_>)], + params: &[(ast::Pat, Option, hir::Param<'db>)], CallInfo { node, arguments, generic_arg_list, krate }: &CallInfo, file_editor: &SyntaxEditor, ) -> ast::Expr { diff --git a/crates/ide-assists/src/handlers/remove_unused_imports.rs b/crates/ide-assists/src/handlers/remove_unused_imports.rs index 2958acc4783a..d6582a955912 100644 --- a/crates/ide-assists/src/handlers/remove_unused_imports.rs +++ b/crates/ide-assists/src/handlers/remove_unused_imports.rs @@ -140,7 +140,7 @@ fn is_path_per_ns_unused_in_scope( ctx: &AssistContext<'_, '_>, u: &ast::UseTree, scope: &mut Vec, - path: &PathResolutionPerNs, + path: &PathResolutionPerNs<'_>, ) -> bool { if let Some(PathResolution::Def(ModuleDef::Trait(ref t))) = path.type_ns { if is_trait_unused_in_scope(ctx, u, scope, t) { @@ -159,7 +159,7 @@ fn is_path_unused_in_scope( ctx: &AssistContext<'_, '_>, u: &ast::UseTree, scope: &mut Vec, - path: &[Option], + path: &[Option>], ) -> bool { !path .iter() @@ -182,9 +182,9 @@ fn is_trait_unused_in_scope( .any(|(d, rename)| used_once_in_scope(ctx, d, rename, scope)) } -fn used_once_in_scope( - ctx: &AssistContext<'_, '_>, - def: Definition, +fn used_once_in_scope<'db>( + ctx: &AssistContext<'_, 'db>, + def: Definition<'db>, rename: Option, scopes: &Vec, ) -> bool { diff --git a/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs b/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs index 979f83297863..2be8dd1fbda8 100644 --- a/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs +++ b/crates/ide-assists/src/handlers/replace_named_generic_with_impl.rs @@ -155,10 +155,10 @@ fn find_path_type( } /// Returns all usage references for the given type parameter definition. -fn find_usages( - sema: &Semantics<'_, RootDatabase>, +fn find_usages<'db>( + sema: &Semantics<'db, RootDatabase>, fn_: &ast::Fn, - type_param_def: Definition, + type_param_def: Definition<'db>, file_id: EditionedFileId, ) -> UsageSearchResult { let file_range = FileRange { file_id, range: fn_.syntax().text_range() }; diff --git a/crates/ide-assists/src/handlers/unnecessary_async.rs b/crates/ide-assists/src/handlers/unnecessary_async.rs index 5542180362e1..8bfc3439f496 100644 --- a/crates/ide-assists/src/handlers/unnecessary_async.rs +++ b/crates/ide-assists/src/handlers/unnecessary_async.rs @@ -90,9 +90,9 @@ pub(crate) fn unnecessary_async(acc: &mut Assists, ctx: &AssistContext<'_, '_>) ) } -fn find_all_references( - ctx: &AssistContext<'_, '_>, - def: &Definition, +fn find_all_references<'db>( + ctx: &AssistContext<'_, 'db>, + def: &Definition<'db>, ) -> impl Iterator { def.usages(&ctx.sema).all().into_iter().flat_map(|(file_id, references)| { references.into_iter().map(move |reference| (file_id, reference)) diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs index 20048ea97b2c..f1a34f15d0a5 100644 --- a/crates/ide-completion/src/completions.rs +++ b/crates/ide-completion/src/completions.rs @@ -222,12 +222,12 @@ impl Completions { }); } - pub(crate) fn add_path_resolution( + pub(crate) fn add_path_resolution<'db>( &mut self, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, - resolution: hir::ScopeDef, + resolution: hir::ScopeDef<'db>, doc_aliases: Vec, ) { let is_private_editable = match ctx.def_is_visible(&resolution) { @@ -244,12 +244,12 @@ impl Completions { .add_to(self, ctx.db); } - pub(crate) fn add_pattern_resolution( + pub(crate) fn add_pattern_resolution<'db>( &mut self, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, pattern_ctx: &PatternContext, local_name: hir::Name, - resolution: hir::ScopeDef, + resolution: hir::ScopeDef<'db>, ) { let is_private_editable = match ctx.def_is_visible(&resolution) { Visible::Yes => false, diff --git a/crates/ide-completion/src/completions/expr.rs b/crates/ide-completion/src/completions/expr.rs index 8d906064c024..889beeac081e 100644 --- a/crates/ide-completion/src/completions/expr.rs +++ b/crates/ide-completion/src/completions/expr.rs @@ -44,9 +44,9 @@ where } } -pub(crate) fn complete_expr_path( +pub(crate) fn complete_expr_path<'db>( acc: &mut Completions, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'_>, expr_ctx: &PathExprCtx<'_>, ) { @@ -87,7 +87,7 @@ pub(crate) fn complete_expr_path( false }; - let scope_def_applicable = |def| match def { + let scope_def_applicable = |def: ScopeDef<'db>| match def { ScopeDef::GenericParam(hir::GenericParam::LifetimeParam(_)) | ScopeDef::Label(_) => false, ScopeDef::ModuleDef(hir::ModuleDef::Macro(mac)) => mac.is_fn_like(ctx.db), _ => true, diff --git a/crates/ide-completion/src/completions/type.rs b/crates/ide-completion/src/completions/type.rs index 0b2b6682aaab..c07c02e28538 100644 --- a/crates/ide-completion/src/completions/type.rs +++ b/crates/ide-completion/src/completions/type.rs @@ -9,15 +9,15 @@ use crate::{ render::render_type_inference, }; -pub(crate) fn complete_type_path( +pub(crate) fn complete_type_path<'db>( acc: &mut Completions, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'_>, location: &TypeLocation, ) { let _p = tracing::info_span!("complete_type_path").entered(); - let scope_def_applicable = |def| { + let scope_def_applicable = |def: ScopeDef<'db>| { use hir::{GenericParam::*, ModuleDef::*}; match def { ScopeDef::GenericParam(LifetimeParam(_)) => location.complete_lifetimes(), diff --git a/crates/ide-completion/src/context.rs b/crates/ide-completion/src/context.rs index 507ecaff0dca..705305f557e9 100644 --- a/crates/ide-completion/src/context.rs +++ b/crates/ide-completion/src/context.rs @@ -273,7 +273,7 @@ pub(crate) enum Qualified<'db> { No, With { path: ast::Path, - resolution: Option, + resolution: Option>, /// How many `super` segments are present in the path /// /// This would be None, if path is not solely made of @@ -491,7 +491,7 @@ pub(crate) struct CompletionContext<'a, 'db> { pub(crate) qualifier_ctx: QualifierCtx, - pub(crate) locals: FxHashMap, + pub(crate) locals: FxHashMap>, /// The module depth of the current module of the cursor position. /// - crate-root @@ -545,7 +545,7 @@ impl<'db> CompletionContext<'_, 'db> { } /// Checks if an item is visible and not `doc(hidden)` at the completion site. - pub(crate) fn def_is_visible(&self, item: &ScopeDef) -> Visible { + pub(crate) fn def_is_visible(&self, item: &ScopeDef<'db>) -> Visible { match item { ScopeDef::ModuleDef(def) => match def { hir::ModuleDef::Module(it) => self.is_visible(it), @@ -664,7 +664,7 @@ impl<'db> CompletionContext<'_, 'db> { /// A version of [`SemanticsScope::process_all_names`] that filters out `#[doc(hidden)]` items and /// passes all doc-aliases along, to funnel it into `Completions::add_path_resolution`. - pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef, Vec)) { + pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef<'db>, Vec)) { let _p = tracing::info_span!("CompletionContext::process_all_names").entered(); self.scope.process_all_names(&mut |name, def| { if self.is_scope_def_hidden(def) { @@ -675,12 +675,12 @@ impl<'db> CompletionContext<'_, 'db> { }); } - pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef)) { + pub(crate) fn process_all_names_raw(&self, f: &mut dyn FnMut(Name, ScopeDef<'db>)) { let _p = tracing::info_span!("CompletionContext::process_all_names_raw").entered(); self.scope.process_all_names(f); } - fn is_scope_def_hidden(&self, scope_def: ScopeDef) -> bool { + fn is_scope_def_hidden(&self, scope_def: ScopeDef<'db>) -> bool { if let (Some(attrs), Some(krate)) = (scope_def.attrs(self.db), scope_def.krate(self.db)) { return self.is_doc_hidden(&attrs, krate); } @@ -722,7 +722,7 @@ impl<'db> CompletionContext<'_, 'db> { self.krate != defining_crate && attrs.is_doc_hidden() } - pub(crate) fn doc_aliases_in_scope(&self, scope_def: ScopeDef) -> Vec { + pub(crate) fn doc_aliases_in_scope(&self, scope_def: ScopeDef<'db>) -> Vec { if let Some(attrs) = scope_def.attrs(self.db) { attrs.doc_aliases(self.db).iter().map(|it| it.as_str().into()).collect() } else { diff --git a/crates/ide-completion/src/item.rs b/crates/ide-completion/src/item.rs index 61281f8cfb8f..2ff726c6d03e 100644 --- a/crates/ide-completion/src/item.rs +++ b/crates/ide-completion/src/item.rs @@ -551,11 +551,11 @@ pub(crate) struct Builder { } impl Builder { - pub(crate) fn from_resolution( - ctx: &CompletionContext<'_, '_>, + pub(crate) fn from_resolution<'db>( + ctx: &CompletionContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, - resolution: hir::ScopeDef, + resolution: hir::ScopeDef<'db>, ) -> Self { let doc_aliases = ctx.doc_aliases_in_scope(resolution); render_path_resolution( diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index e48847c983b4..5a40d1142e09 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -253,20 +253,20 @@ pub(crate) fn render_type_inference( builder.build(ctx.db) } -pub(crate) fn render_path_resolution( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_path_resolution<'db>( + ctx: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, - resolution: ScopeDef, + resolution: ScopeDef<'db>, ) -> Builder { render_resolution_path(ctx, path_ctx, local_name, None, resolution) } -pub(crate) fn render_pattern_resolution( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_pattern_resolution<'db>( + ctx: RenderContext<'_, 'db>, pattern_ctx: &PatternContext, local_name: hir::Name, - resolution: ScopeDef, + resolution: ScopeDef<'db>, ) -> Builder { render_resolution_pat(ctx, pattern_ctx, local_name, None, resolution) } @@ -356,9 +356,9 @@ pub(crate) fn render_expr<'db>( Some(item) } -fn get_import_name( - resolution: ScopeDef, - ctx: &RenderContext<'_, '_>, +fn get_import_name<'db>( + resolution: ScopeDef<'db>, + ctx: &RenderContext<'_, 'db>, import_edit: &LocatedImport, ) -> Option { // FIXME: Temporary workaround for handling aliased import. @@ -374,9 +374,9 @@ fn get_import_name( } } -fn scope_def_to_name( - resolution: ScopeDef, - ctx: &RenderContext<'_, '_>, +fn scope_def_to_name<'db>( + resolution: ScopeDef<'db>, + ctx: &RenderContext<'_, 'db>, import_edit: &LocatedImport, ) -> Option { Some(match resolution { @@ -387,12 +387,12 @@ fn scope_def_to_name( }) } -fn render_resolution_pat( - ctx: RenderContext<'_, '_>, +fn render_resolution_pat<'db>( + ctx: RenderContext<'_, 'db>, pattern_ctx: &PatternContext, local_name: hir::Name, import_to_add: Option, - resolution: ScopeDef, + resolution: ScopeDef<'db>, ) -> Builder { let _p = tracing::info_span!("render_resolution_pat").entered(); use hir::ModuleDef::*; @@ -410,7 +410,7 @@ fn render_resolution_path<'db>( path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, import_to_add: Option, - resolution: ScopeDef, + resolution: ScopeDef<'db>, ) -> Builder { let _p = tracing::info_span!("render_resolution_path").entered(); use hir::ModuleDef::*; @@ -528,11 +528,11 @@ fn render_resolution_path<'db>( item } -fn render_resolution_simple_( - ctx: RenderContext<'_, '_>, +fn render_resolution_simple_<'db>( + ctx: RenderContext<'_, 'db>, local_name: &hir::Name, import_to_add: Option, - resolution: ScopeDef, + resolution: ScopeDef<'db>, ) -> Builder { let _p = tracing::info_span!("render_resolution_simple_").entered(); @@ -558,7 +558,7 @@ fn render_resolution_simple_( item } -fn res_to_kind(resolution: ScopeDef) -> CompletionItemKind { +fn res_to_kind(resolution: ScopeDef<'_>) -> CompletionItemKind { use hir::ModuleDef::*; match resolution { ScopeDef::Unknown => CompletionItemKind::UnresolvedReference, @@ -589,7 +589,10 @@ fn res_to_kind(resolution: ScopeDef) -> CompletionItemKind { } } -fn scope_def_docs(db: &RootDatabase, resolution: ScopeDef) -> Option> { +fn scope_def_docs<'db>( + db: &'db RootDatabase, + resolution: ScopeDef<'db>, +) -> Option> { use hir::ModuleDef::*; match resolution { ScopeDef::ModuleDef(Module(it)) => it.docs(db), @@ -603,7 +606,7 @@ fn scope_def_docs(db: &RootDatabase, resolution: ScopeDef) -> Option, resolution: ScopeDef) -> bool { +fn scope_def_is_deprecated(ctx: &RenderContext<'_, '_>, resolution: ScopeDef<'_>) -> bool { let db = ctx.db(); match resolution { ScopeDef::ModuleDef(hir::ModuleDef::EnumVariant(it)) => ctx.is_variant_deprecated(it), diff --git a/crates/ide-db/src/defs.rs b/crates/ide-db/src/defs.rs index 82cff372963a..52cd66400007 100644 --- a/crates/ide-db/src/defs.rs +++ b/crates/ide-db/src/defs.rs @@ -22,7 +22,7 @@ use hir::{ Visibility, }; use span::Edition; -use stdx::{format_to, impl_from}; +use stdx::format_to; use syntax::{ SyntaxKind, SyntaxNode, SyntaxToken, ast::{self, AstNode}, @@ -31,10 +31,10 @@ use syntax::{ // FIXME: a more precise name would probably be `Symbol`? #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)] -pub enum Definition { +pub enum Definition<'db> { Macro(Macro), Field(Field), - TupleField(TupleField), + TupleField(TupleField<'db>), Module(Module), Crate(Crate), Function(Function), @@ -46,7 +46,7 @@ pub enum Definition { TypeAlias(TypeAlias), SelfType(Impl), GenericParam(GenericParam), - Local(Local), + Local(Local<'db>), Label(Label), DeriveHelper(DeriveHelper), BuiltinType(BuiltinType), @@ -58,7 +58,7 @@ pub enum Definition { InlineAsmOperand(InlineAsmOperand), } -impl Definition { +impl<'db> Definition<'db> { pub fn canonical_module_path(&self, db: &RootDatabase) -> Option> { self.module(db).map(|it| it.path_to_root(db).into_iter().rev()) } @@ -104,8 +104,8 @@ impl Definition { Some(module) } - pub fn enclosing_definition(&self, db: &RootDatabase) -> Option { - fn container_to_definition(container: ItemContainer) -> Option { + pub fn enclosing_definition(&self, db: &RootDatabase) -> Option> { + fn container_to_definition<'db>(container: ItemContainer) -> Option> { match container { ItemContainer::Trait(it) => Some(it.into()), ItemContainer::Impl(it) => Some(it.into()), @@ -202,12 +202,12 @@ impl Definition { Some(name) } - pub fn docs<'db>( + pub fn docs<'a>( &self, - db: &'db RootDatabase, + db: &'a RootDatabase, famous_defs: Option<&FamousDefs<'_, '_>>, display_target: DisplayTarget, - ) -> Option> { + ) -> Option> { self.docs_with_rangemap(db, famous_defs, display_target).map(|docs| match docs { Either::Left(Cow::Borrowed(docs)) => Documentation::new_borrowed(docs.docs()), Either::Left(Cow::Owned(docs)) => Documentation::new_owned(docs.into_docs()), @@ -215,12 +215,12 @@ impl Definition { }) } - pub fn docs_with_rangemap<'db>( + pub fn docs_with_rangemap<'a>( &self, - db: &'db RootDatabase, + db: &'a RootDatabase, famous_defs: Option<&FamousDefs<'_, '_>>, display_target: DisplayTarget, - ) -> Option, Documentation<'db>>> { + ) -> Option, Documentation<'a>>> { let docs = match self { Definition::Macro(it) => it.docs_with_rangemap(db), Definition::Field(it) => it.docs_with_rangemap(db), @@ -432,7 +432,7 @@ impl<'db> IdentClass<'db> { .or_else(|| NameClass::classify_lifetime(sema, lifetime).map(IdentClass::NameClass)) } - pub fn definitions(self) -> ArrayVec<(Definition, Option>), 2> { + pub fn definitions(self) -> ArrayVec<(Definition<'db>, Option>), 2> { let mut res = ArrayVec::new(); match self { IdentClass::NameClass(NameClass::Definition(it) | NameClass::ConstReference(it)) => { @@ -473,7 +473,7 @@ impl<'db> IdentClass<'db> { res } - pub fn definitions_no_ops(self) -> ArrayVec { + pub fn definitions_no_ops(self) -> ArrayVec, 2> { let mut res = ArrayVec::new(); match self { IdentClass::NameClass(NameClass::Definition(it) | NameClass::ConstReference(it)) => { @@ -517,14 +517,14 @@ impl<'db> IdentClass<'db> { /// A model special case is `None` constant in pattern. #[derive(Debug)] pub enum NameClass<'db> { - Definition(Definition), + Definition(Definition<'db>), /// `None` in `if let None = Some(82) {}`. /// Syntactically, it is a name, but semantically it is a reference. - ConstReference(Definition), + ConstReference(Definition<'db>), /// `field` in `if let Foo { field } = foo`. Here, `ast::Name` both introduces /// a definition into a local scope, and refers to an existing definition. PatFieldShorthand { - local_def: Local, + local_def: Local<'db>, field_ref: Field, adt_subst: GenericSubstitution<'db>, }, @@ -532,7 +532,7 @@ pub enum NameClass<'db> { impl<'db> NameClass<'db> { /// `Definition` defined by this name. - pub fn defined(self) -> Option { + pub fn defined(self) -> Option> { let res = match self { NameClass::Definition(it) => it, NameClass::ConstReference(_) => return None, @@ -566,10 +566,10 @@ impl<'db> NameClass<'db> { }; return Some(NameClass::Definition(definition)); - fn classify_item( - sema: &Semantics<'_, RootDatabase>, + fn classify_item<'db>( + sema: &Semantics<'db, RootDatabase>, item: ast::Item, - ) -> Option { + ) -> Option> { let definition = match item { ast::Item::MacroRules(it) => { Definition::Macro(sema.to_def(&ast::Macro::MacroRules(it))?) @@ -621,10 +621,10 @@ impl<'db> NameClass<'db> { Some(NameClass::Definition(Definition::Local(local))) } - fn classify_rename( - sema: &Semantics<'_, RootDatabase>, + fn classify_rename<'db>( + sema: &Semantics<'db, RootDatabase>, rename: ast::Rename, - ) -> Option { + ) -> Option> { if let Some(use_tree) = rename.syntax().parent().and_then(ast::UseTree::cast) { let path = use_tree.path()?; sema.resolve_path(&path).map(Definition::from) @@ -722,9 +722,9 @@ impl OperatorClass { /// reference to point to two different defs. #[derive(Debug)] pub enum NameRefClass<'db> { - Definition(Definition, Option>), + Definition(Definition<'db>, Option>), FieldShorthand { - local_ref: Local, + local_ref: Local<'db>, field_ref: Field, adt_subst: GenericSubstitution<'db>, }, @@ -891,31 +891,54 @@ impl<'db> NameRefClass<'db> { } } -impl_from!( - Field, Module, Function, Adt, EnumVariant, Const, Static, Trait, TypeAlias, BuiltinType, Local, - GenericParam, Label, Macro, ExternCrateDecl - for Definition +macro_rules! impl_from_definition { + ($($variant:ident: $ty:ty),* $(,)?) => {$( + impl<'db> From<$ty> for Definition<'db> { + fn from(it: $ty) -> Self { + Definition::$variant(it) + } + } + )*}; +} + +impl_from_definition!( + Field: Field, + TupleField: TupleField<'db>, + Module: Module, + Function: Function, + Adt: Adt, + EnumVariant: EnumVariant, + Const: Const, + Static: Static, + Trait: Trait, + TypeAlias: TypeAlias, + BuiltinType: BuiltinType, + Local: Local<'db>, + GenericParam: GenericParam, + Label: Label, + Macro: Macro, + ExternCrateDecl: ExternCrateDecl, ); -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(impl_: Impl) -> Self { Definition::SelfType(impl_) } } -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(value: InlineAsmOperand) -> Self { Definition::InlineAsmOperand(value) } } -impl From> for Definition { - fn from(value: Either) -> Self { +impl<'db> From, InlineAsmOperand>> for Definition<'db> { + fn from(value: Either, InlineAsmOperand>) -> Self { value.either(Definition::from, Definition::from) } } -impl AsAssocItem for Definition { +impl AsAssocItem for Definition<'_> { fn as_assoc_item(self, db: &dyn hir::db::HirDatabase) -> Option { match self { Definition::Function(it) => it.as_assoc_item(db), @@ -926,7 +949,7 @@ impl AsAssocItem for Definition { } } -impl AsExternAssocItem for Definition { +impl AsExternAssocItem for Definition<'_> { fn as_extern_assoc_item(self, db: &dyn hir::db::HirDatabase) -> Option { match self { Definition::Function(it) => it.as_extern_assoc_item(db), @@ -937,7 +960,7 @@ impl AsExternAssocItem for Definition { } } -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(assoc_item: AssocItem) -> Self { match assoc_item { AssocItem::Function(it) => Definition::Function(it), @@ -947,8 +970,8 @@ impl From for Definition { } } -impl From for Definition { - fn from(path_resolution: PathResolution) -> Self { +impl<'db> From> for Definition<'db> { + fn from(path_resolution: PathResolution<'db>) -> Self { match path_resolution { PathResolution::Def(def) => def.into(), PathResolution::Local(local) => Definition::Local(local), @@ -962,7 +985,7 @@ impl From for Definition { } } -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(def: ModuleDef) -> Self { match def { ModuleDef::Module(it) => Definition::Module(it), @@ -979,7 +1002,7 @@ impl From for Definition { } } -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(def: DocLinkDef) -> Self { match def { DocLinkDef::ModuleDef(it) => it.into(), @@ -989,13 +1012,13 @@ impl From for Definition { } } -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(def: Variant) -> Self { ModuleDef::from(def).into() } } -impl TryFrom for Definition { +impl<'db> TryFrom for Definition<'db> { type Error = (); fn try_from(def: DefWithBody) -> Result { match def { @@ -1007,7 +1030,7 @@ impl TryFrom for Definition { } } -impl From for Definition { +impl<'db> From for Definition<'db> { fn from(def: GenericDef) -> Self { match def { GenericDef::Function(it) => it.into(), @@ -1021,7 +1044,7 @@ impl From for Definition { } } -impl TryFrom for Definition { +impl<'db> TryFrom for Definition<'db> { type Error = (); fn try_from(def: ExpressionStoreOwner) -> Result { match def { @@ -1032,9 +1055,9 @@ impl TryFrom for Definition { } } -impl TryFrom for GenericDef { +impl TryFrom> for GenericDef { type Error = (); - fn try_from(def: Definition) -> Result { + fn try_from(def: Definition<'_>) -> Result { match def { Definition::Function(it) => Ok(it.into()), Definition::Adt(it) => Ok(it.into()), diff --git a/crates/ide-db/src/famous_defs.rs b/crates/ide-db/src/famous_defs.rs index f28ce53e91c0..b5f62c8fd736 100644 --- a/crates/ide-db/src/famous_defs.rs +++ b/crates/ide-db/src/famous_defs.rs @@ -222,7 +222,7 @@ impl FamousDefs<'_, '_> { Some(res) } - fn find_def(&self, path: &str) -> Option { + fn find_def(&self, path: &str) -> Option> { let db = self.0.db; let mut path = path.split(':'); let trait_ = path.next_back()?; diff --git a/crates/ide-db/src/helpers.rs b/crates/ide-db/src/helpers.rs index 838aac2283f1..00e81b3ef430 100644 --- a/crates/ide-db/src/helpers.rs +++ b/crates/ide-db/src/helpers.rs @@ -83,10 +83,10 @@ pub fn mod_path_to_ast_with_factory( } /// Iterates all `ModuleDef`s and `Impl` blocks of the given file. -pub fn visit_file_defs( - sema: &Semantics<'_, RootDatabase>, +pub fn visit_file_defs<'db>( + sema: &Semantics<'db, RootDatabase>, file_id: FileId, - cb: &mut dyn FnMut(Definition), + cb: &mut dyn FnMut(Definition<'db>), ) { let db = sema.db; let module = match sema.file_to_module_def(file_id) { @@ -139,10 +139,10 @@ pub fn is_editable_crate(krate: Crate, db: &RootDatabase) -> bool { } // FIXME: This is a weird function -pub fn get_definition( - sema: &Semantics<'_, RootDatabase>, +pub fn get_definition<'db>( + sema: &Semantics<'db, RootDatabase>, token: SyntaxToken, -) -> Option { +) -> Option> { for token in sema.descend_into_macros_exact(token) { let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions_no_ops); if let Some(&[x]) = def.as_deref() { diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs index 6edc550b331a..f5dff47acf9a 100644 --- a/crates/ide-db/src/imports/import_assets.rs +++ b/crates/ide-db/src/imports/import_assets.rs @@ -461,7 +461,7 @@ impl<'db> ImportAssets<'db> { .into_iter() } - fn scope_definitions(&self, sema: &Semantics<'_, RootDatabase>) -> FxHashSet { + fn scope_definitions<'a>(&self, sema: &Semantics<'a, RootDatabase>) -> FxHashSet> { let _p = tracing::info_span!("ImportAssets::scope_definitions").entered(); let mut scope_definitions = FxHashSet::default(); if let Some(scope) = sema.scope(&self.candidate_node) { diff --git a/crates/ide-db/src/rename.rs b/crates/ide-db/src/rename.rs index ff4d5a28866c..b89c2fdf4ad8 100644 --- a/crates/ide-db/src/rename.rs +++ b/crates/ide-db/src/rename.rs @@ -82,10 +82,10 @@ pub enum RenameDefinition { No, } -impl Definition { +impl<'db> Definition<'db> { pub fn rename( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, new_name: &str, rename_definition: RenameDefinition, config: &RenameConfig, @@ -345,9 +345,9 @@ fn rename_mod( Ok(source_change) } -fn rename_reference( - sema: &Semantics<'_, RootDatabase>, - def: Definition, +fn rename_reference<'db>( + sema: &Semantics<'db, RootDatabase>, + def: Definition<'db>, new_name: &str, rename_definition: RenameDefinition, edition: Edition, @@ -523,7 +523,7 @@ fn rename_field_constructors( pub fn source_edit_from_references( db: &RootDatabase, references: &[FileReference], - def: Definition, + def: Definition<'_>, new_name: &Name, edition: Edition, ) -> TextEdit { @@ -579,7 +579,7 @@ fn source_edit_from_name_ref( edit: &mut TextEditBuilder, name_ref: &ast::NameRef, new_name: &dyn Display, - def: Definition, + def: Definition<'_>, ) -> bool { if name_ref.super_token().is_some() { return true; @@ -670,10 +670,10 @@ fn source_edit_from_name_ref( false } -fn source_edit_from_def( - sema: &Semantics<'_, RootDatabase>, +fn source_edit_from_def<'db>( + sema: &Semantics<'db, RootDatabase>, config: &RenameConfig, - def: Definition, + def: Definition<'db>, new_name: &Name, source_change: &mut SourceChange, ) -> Result<(FileId, TextEdit)> { diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs index d59df3601fbb..b688cb188d58 100644 --- a/crates/ide-db/src/search.rs +++ b/crates/ide-db/src/search.rs @@ -286,7 +286,7 @@ impl IntoIterator for SearchScope { } } -impl Definition { +impl<'db> Definition<'db> { fn search_scope(&self, db: &RootDatabase) -> SearchScope { let _p = tracing::info_span!("search_scope").entered(); @@ -440,7 +440,7 @@ impl Definition { } } - pub fn usages<'a, 'db>(self, sema: &'a Semantics<'db, RootDatabase>) -> FindUsages<'a, 'db> { + pub fn usages<'a>(self, sema: &'a Semantics<'db, RootDatabase>) -> FindUsages<'a, 'db> { FindUsages { def: self, rename: None, @@ -457,7 +457,7 @@ impl Definition { #[derive(Clone)] pub struct FindUsages<'a, 'db> { - def: Definition, + def: Definition<'db>, rename: Option<&'a Rename>, sema: &'a Semantics<'db, RootDatabase>, scope: Option<&'a SearchScope>, @@ -678,7 +678,7 @@ impl<'a, 'db> FindUsages<'a, 'db> { db: &RootDatabase, to_process: &mut Vec<(SmolStr, SearchScope)>, alias_name: &str, - def: Definition, + def: Definition<'_>, ) { let alias = alias_name.trim_start_matches("r#").to_smolstr(); tracing::debug!("found alias: {alias}"); @@ -1211,7 +1211,7 @@ impl<'a, 'db> FindUsages<'a, 'db> { file_id: EditionedFileId, range: TextRange, token: ast::String, - res: Either, + res: Either, InlineAsmOperand>, sink: &mut dyn FnMut(EditionedFileId, FileReference) -> bool, ) -> bool { let def = res.either(Definition::from, Definition::from); @@ -1393,7 +1393,10 @@ impl<'a, 'db> FindUsages<'a, 'db> { } } -fn def_to_ty<'db>(sema: &Semantics<'db, RootDatabase>, def: &Definition) -> Option> { +fn def_to_ty<'db>( + sema: &Semantics<'db, RootDatabase>, + def: &Definition<'db>, +) -> Option> { match def { Definition::Adt(adt) => Some(adt.ty(sema.db)), Definition::TypeAlias(it) => Some(it.ty(sema.db)), @@ -1406,7 +1409,7 @@ fn def_to_ty<'db>(sema: &Semantics<'db, RootDatabase>, def: &Definition) -> Opti impl ReferenceCategory { fn new( sema: &Semantics<'_, RootDatabase>, - def: &Definition, + def: &Definition<'_>, r: &ast::NameRef, ) -> ReferenceCategory { let mut result = ReferenceCategory::empty(); diff --git a/crates/ide-db/src/traits.rs b/crates/ide-db/src/traits.rs index 994427ac76f8..4a560d30ba3c 100644 --- a/crates/ide-db/src/traits.rs +++ b/crates/ide-db/src/traits.rs @@ -86,7 +86,10 @@ pub fn get_missing_assoc_items( } /// Converts associated trait impl items to their trait definition counterpart -pub(crate) fn convert_to_def_in_trait(db: &dyn HirDatabase, def: Definition) -> Definition { +pub(crate) fn convert_to_def_in_trait<'db>( + db: &'db dyn HirDatabase, + def: Definition<'db>, +) -> Definition<'db> { (|| { let assoc = def.as_assoc_item(db)?; let trait_ = assoc.implemented_trait(db)?; @@ -96,7 +99,10 @@ pub(crate) fn convert_to_def_in_trait(db: &dyn HirDatabase, def: Definition) -> } /// If this is an trait (impl) assoc item, returns the assoc item of the corresponding trait definition. -pub(crate) fn as_trait_assoc_def(db: &dyn HirDatabase, def: Definition) -> Option { +pub(crate) fn as_trait_assoc_def<'db>( + db: &dyn HirDatabase, + def: Definition<'db>, +) -> Option> { let assoc = def.as_assoc_item(db)?; let trait_ = match assoc.container(db) { hir::AssocItemContainer::Trait(_) => return Some(def), @@ -105,11 +111,11 @@ pub(crate) fn as_trait_assoc_def(db: &dyn HirDatabase, def: Definition) -> Optio assoc_item_of_trait(db, assoc, trait_) } -fn assoc_item_of_trait( +fn assoc_item_of_trait<'db>( db: &dyn HirDatabase, assoc: hir::AssocItem, trait_: hir::Trait, -) -> Option { +) -> Option> { use hir::AssocItem::*; let name = match assoc { Function(it) => it.name(db), diff --git a/crates/ide-diagnostics/src/handlers/mutability_errors.rs b/crates/ide-diagnostics/src/handlers/mutability_errors.rs index 49aa6d7bd946..0e61571da635 100644 --- a/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -8,7 +8,10 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext, fix}; // Diagnostic: need-mut // // This diagnostic is triggered on mutating an immutable variable. -pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_, '_>, d: &hir::NeedMut) -> Option { +pub(crate) fn need_mut( + ctx: &DiagnosticsContext<'_, '_>, + d: &hir::NeedMut<'_>, +) -> Option { let root = ctx.sema.db.parse_or_expand(d.span.file_id); let node = d.span.value.to_node(&root); let mut span = d.span; @@ -65,7 +68,7 @@ pub(crate) fn need_mut(ctx: &DiagnosticsContext<'_, '_>, d: &hir::NeedMut) -> Op // This diagnostic is triggered when a mutable variable isn't actually mutated. pub(crate) fn unused_mut( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::UnusedMut, + d: &hir::UnusedMut<'_>, ) -> Option { let ast = d.local.primary_source(ctx.sema.db).syntax_ptr(); let fixes = (|| { diff --git a/crates/ide-diagnostics/src/handlers/unused_variables.rs b/crates/ide-diagnostics/src/handlers/unused_variables.rs index afc74445f429..4129bd57796c 100644 --- a/crates/ide-diagnostics/src/handlers/unused_variables.rs +++ b/crates/ide-diagnostics/src/handlers/unused_variables.rs @@ -15,7 +15,7 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; // This diagnostic is triggered when a local variable is not used. pub(crate) fn unused_variables( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::UnusedVariable, + d: &hir::UnusedVariable<'_>, ) -> Option { let ast = d.local.primary_source(ctx.sema.db).syntax_ptr(); if ast.file_id.macro_file().is_some() { diff --git a/crates/ide-ssr/src/resolving.rs b/crates/ide-ssr/src/resolving.rs index 461de4092e30..3dbba0ff2dab 100644 --- a/crates/ide-ssr/src/resolving.rs +++ b/crates/ide-ssr/src/resolving.rs @@ -25,13 +25,13 @@ pub(crate) struct ResolvedPattern<'db> { pub(crate) placeholders_by_stand_in: FxHashMap, pub(crate) node: SyntaxNode, // Paths in `node` that we've resolved. - pub(crate) resolved_paths: FxHashMap, + pub(crate) resolved_paths: FxHashMap>, pub(crate) ufcs_function_calls: FxHashMap>, pub(crate) contains_self: bool, } -pub(crate) struct ResolvedPath { - pub(crate) resolution: hir::PathResolution, +pub(crate) struct ResolvedPath<'db> { + pub(crate) resolution: hir::PathResolution<'db>, /// The depth of the ast::Path that was resolved within the pattern. pub(crate) depth: u32, } @@ -120,7 +120,7 @@ impl<'db> Resolver<'_, 'db> { &self, node: SyntaxNode, depth: u32, - resolved_paths: &mut FxHashMap, + resolved_paths: &mut FxHashMap>, ) -> Result<(), SsrError> { use syntax::ast::AstNode; if let Some(path) = ast::Path::cast(node.clone()) { @@ -165,7 +165,7 @@ impl<'db> Resolver<'_, 'db> { false } - fn ok_to_use_path_resolution(&self, resolution: &hir::PathResolution) -> bool { + fn ok_to_use_path_resolution(&self, resolution: &hir::PathResolution<'db>) -> bool { match resolution { hir::PathResolution::Def(hir::ModuleDef::Function(function)) if function.as_assoc_item(self.resolution_scope.scope.db).is_some() => @@ -215,7 +215,7 @@ impl<'db> ResolutionScope<'db> { self.node.ancestors().find(|node| node.kind() == SyntaxKind::FN) } - fn resolve_path(&self, path: &ast::Path) -> Option { + fn resolve_path(&self, path: &ast::Path) -> Option> { // First try resolving the whole path. This will work for things like // `std::collections::HashMap`, but will fail for things like // `std::collections::HashMap::new`. diff --git a/crates/ide-ssr/src/search.rs b/crates/ide-ssr/src/search.rs index 51e4951cf662..c6a1d6967211 100644 --- a/crates/ide-ssr/src/search.rs +++ b/crates/ide-ssr/src/search.rs @@ -17,8 +17,8 @@ use syntax::{AstNode, SyntaxKind, SyntaxNode, ast}; /// and as a pattern. In each, the usages of `foo::Bar` are the same and we'd like to avoid finding /// them more than once. #[derive(Default)] -pub(crate) struct UsageCache { - usages: Vec<(Definition, UsageSearchResult)>, +pub(crate) struct UsageCache<'db> { + usages: Vec<(Definition<'db>, UsageSearchResult)>, } impl<'db> MatchFinder<'db> { @@ -28,7 +28,7 @@ impl<'db> MatchFinder<'db> { pub(crate) fn find_matches_for_rule( &self, rule: &ResolvedRule<'db>, - usage_cache: &mut UsageCache, + usage_cache: &mut UsageCache<'db>, matches_out: &mut Vec, ) { if rule.pattern.contains_self { @@ -51,11 +51,11 @@ impl<'db> MatchFinder<'db> { &self, rule: &ResolvedRule<'db>, pattern: &ResolvedPattern<'db>, - usage_cache: &mut UsageCache, + usage_cache: &mut UsageCache<'db>, matches_out: &mut Vec, ) { if let Some(resolved_path) = pick_path_for_usages(pattern) { - let definition: Definition = resolved_path.resolution.into(); + let definition: Definition<'db> = resolved_path.resolution.into(); for file_range in self.find_usages(usage_cache, definition).file_ranges() { for node_to_match in self.find_nodes_to_match(resolved_path, file_range) { if !is_search_permitted_ancestors(&node_to_match) { @@ -70,7 +70,7 @@ impl<'db> MatchFinder<'db> { fn find_nodes_to_match( &self, - resolved_path: &ResolvedPath, + resolved_path: &ResolvedPath<'db>, file_range: FileRange, ) -> Vec { let file = self.sema.parse(file_range.file_id); @@ -112,8 +112,8 @@ impl<'db> MatchFinder<'db> { fn find_usages<'a>( &self, - usage_cache: &'a mut UsageCache, - definition: Definition, + usage_cache: &'a mut UsageCache<'db>, + definition: Definition<'db>, ) -> &'a UsageSearchResult { // Logically if a lookup succeeds we should just return it. Unfortunately returning it would // extend the lifetime of the borrow, then we wouldn't be able to do the insertion on a @@ -252,8 +252,8 @@ fn is_search_permitted(node: &SyntaxNode) -> bool { node.kind() != SyntaxKind::USE } -impl UsageCache { - fn find(&mut self, definition: &Definition) -> Option<&UsageSearchResult> { +impl<'db> UsageCache<'db> { + fn find(&mut self, definition: &Definition<'db>) -> Option<&UsageSearchResult> { // We expect a very small number of cache entries (generally 1), so a linear scan should be // fast enough and avoids the need to implement Hash for Definition. for (d, refs) in &self.usages { @@ -268,7 +268,9 @@ impl UsageCache { /// Returns a path that's suitable for path resolution. We exclude builtin types, since they aren't /// something that we can find references to. We then somewhat arbitrarily pick the path that is the /// longest as this is hopefully more likely to be less common, making it faster to find. -fn pick_path_for_usages<'a>(pattern: &'a ResolvedPattern<'_>) -> Option<&'a ResolvedPath> { +fn pick_path_for_usages<'a, 'db>( + pattern: &'a ResolvedPattern<'db>, +) -> Option<&'a ResolvedPath<'db>> { // FIXME: Take the scope of the resolved path into account. e.g. if there are any paths that are // private to the current module, then we definitely would want to pick them over say a path // from std. Possibly we should go further than this and intersect the search scopes for all diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index fd462d003d7d..70d05cd3b5dc 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -53,7 +53,7 @@ const MARKDOWN_OPTIONS: Options = pub(crate) fn rewrite_links( db: &RootDatabase, markdown: &str, - definition: Definition, + definition: Definition<'_>, range_map: Option<&hir::Docs>, ) -> String { let mut cb = broken_link_clone_cb; @@ -207,13 +207,13 @@ pub(crate) fn extract_definitions_from_docs( .collect() } -pub(crate) fn resolve_doc_path_for_def( +pub(crate) fn resolve_doc_path_for_def<'db>( db: &dyn HirDatabase, - def: Definition, + def: Definition<'db>, link: &str, ns: Option, is_inner_doc: hir::IsInnerDoc, -) -> Option { +) -> Option> { match def { Definition::Module(it) => it.resolve_doc_path(db, link, ns, is_inner_doc), Definition::Crate(it) => it.resolve_doc_path(db, link, ns, is_inner_doc), @@ -243,10 +243,10 @@ pub(crate) fn resolve_doc_path_for_def( .map(Definition::from) } -pub(crate) fn doc_attributes( - sema: &Semantics<'_, RootDatabase>, +pub(crate) fn doc_attributes<'db>( + sema: &Semantics<'db, RootDatabase>, node: &SyntaxNode, -) -> Option<(hir::AttrsWithOwner, Definition)> { +) -> Option<(hir::AttrsWithOwner, Definition<'db>)> { match_ast! { match node { ast::SourceFile(it) => sema.to_def(&it).map(|def| (def.attrs(sema.db), Definition::from(def))), @@ -293,12 +293,12 @@ pub(crate) fn token_as_doc_comment(doc_token: &SyntaxToken) -> Option( + pub(crate) fn get_definition_with_descend_at<'db, T>( self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, offset: TextSize, // Definition, CommentOwner, range of intra doc link in original file - mut cb: impl FnMut(Definition, SyntaxNode, TextRange) -> Option, + mut cb: impl FnMut(Definition<'db>, SyntaxNode, TextRange) -> Option, ) -> Option { let DocCommentToken { prefix_len, doc_token } = self; // offset relative to the comments contents @@ -346,11 +346,11 @@ impl DocCommentToken { /// //! [`S$0`] /// } /// ``` - fn doc_attributes( - sema: &Semantics<'_, RootDatabase>, + fn doc_attributes<'db>( + sema: &Semantics<'db, RootDatabase>, node: &SyntaxNode, is_inner_doc: bool, - ) -> Option<(AttrsWithOwner, Definition)> { + ) -> Option<(AttrsWithOwner, Definition<'db>)> { if is_inner_doc && node.kind() != SOURCE_FILE { let parent = node.parent()?; doc_attributes(sema, &parent).or(doc_attributes(sema, &parent.parent()?)) @@ -373,7 +373,7 @@ fn broken_link_clone_cb(link: BrokenLink<'_>) -> Option<(CowStr<'_>, CowStr<'_>) // https://github.com/rust-lang/rfcs/pull/2988 fn get_doc_links( db: &RootDatabase, - def: Definition, + def: Definition<'_>, target_dir: Option<&str>, sysroot: Option<&str>, ) -> DocumentationLinks { @@ -411,7 +411,7 @@ fn get_doc_links( fn rewrite_intra_doc_link( db: &RootDatabase, - def: Definition, + def: Definition<'_>, target: &str, title: &str, is_inner_doc: hir::IsInnerDoc, @@ -455,7 +455,7 @@ fn rewrite_intra_doc_link( } /// Try to resolve path to local documentation via path-based links (i.e. `../gateway/struct.Shard.html`). -fn rewrite_url_link(db: &RootDatabase, def: Definition, target: &str) -> Option { +fn rewrite_url_link(db: &RootDatabase, def: Definition<'_>, target: &str) -> Option { if !(target.contains('#') || target.contains(".html")) { return None; } @@ -472,7 +472,7 @@ fn rewrite_url_link(db: &RootDatabase, def: Definition, target: &str) -> Option< url.join(target).ok().map(Into::into) } -fn mod_path_of_def(db: &RootDatabase, def: Definition) -> Option { +fn mod_path_of_def(db: &RootDatabase, def: Definition<'_>) -> Option { def.canonical_module_path(db).map(|it| { let mut path = String::new(); it.flat_map(|it| it.name(db)).for_each(|name| format_to!(path, "{}/", name.as_str())); @@ -540,7 +540,7 @@ fn map_links<'e>( /// ``` fn get_doc_base_urls( db: &RootDatabase, - def: Definition, + def: Definition<'_>, target_dir: Option<&str>, sysroot: Option<&str>, ) -> (Option, Option) { @@ -632,10 +632,10 @@ fn get_doc_base_urls( /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next /// ^^^^^^^^^^^^^^^^^^^ /// ``` -fn filename_and_frag_for_def( +fn filename_and_frag_for_def<'db>( db: &dyn HirDatabase, - def: Definition, -) -> Option<(Definition, String, Option)> { + def: Definition<'db>, +) -> Option<(Definition<'db>, String, Option)> { if let Some(assoc_item) = def.as_assoc_item(db) { let def = match assoc_item.container(db) { AssocItemContainer::Trait(t) => t.into(), diff --git a/crates/ide/src/doc_links/tests.rs b/crates/ide/src/doc_links/tests.rs index 509c55a31e58..720528d0b52f 100644 --- a/crates/ide/src/doc_links/tests.rs +++ b/crates/ide/src/doc_links/tests.rs @@ -86,7 +86,7 @@ fn check_doc_links(#[rust_analyzer::rust_fixture] ra_fixture: &str) { fn def_under_cursor<'db>( sema: &Semantics<'db, RootDatabase>, position: &FilePosition, -) -> (Definition, Cow<'db, hir::Docs>) { +) -> (Definition<'db>, Cow<'db, hir::Docs>) { let (docs, def) = sema .parse_guess_edition(position.file_id) .syntax() @@ -104,7 +104,7 @@ fn def_under_cursor<'db>( fn node_to_def<'db>( sema: &Semantics<'db, RootDatabase>, node: &SyntaxNode, -) -> Option>, Definition)>> { +) -> Option>, Definition<'db>)>> { Some(match_ast! { match node { ast::SourceFile(it) => sema.to_def(&it).map(|def| (def.docs_with_rangemap(sema.db), Definition::Module(def))), diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index 991a0b6bee22..70fcadba36b5 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs @@ -385,7 +385,7 @@ fn try_lookup_macro_def_in_macro_use( /// ``` fn try_filter_trait_item_definition( sema: &Semantics<'_, RootDatabase>, - def: &Definition, + def: &Definition<'_>, ) -> Option> { let db = sema.db; let assoc = def.as_assoc_item(db)?; @@ -639,7 +639,7 @@ fn nav_for_break_points( Some(navs) } -fn def_to_nav(sema: &Semantics<'_, RootDatabase>, def: Definition) -> Vec { +fn def_to_nav(sema: &Semantics<'_, RootDatabase>, def: Definition<'_>) -> Vec { def.try_to_nav(sema).map(|it| it.collect()).unwrap_or_default() } diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs index ffd144a827e3..9de956be5ed1 100644 --- a/crates/ide/src/goto_type_definition.rs +++ b/crates/ide/src/goto_type_definition.rs @@ -29,7 +29,7 @@ pub(crate) fn goto_type_definition( })?; let mut res = Vec::new(); - let mut push = |def: Definition| { + let mut push = |def: Definition<'_>| { if let Some(navs) = def.try_to_nav(&sema) { for nav in navs { if !res.contains(&nav) { diff --git a/crates/ide/src/highlight_related.rs b/crates/ide/src/highlight_related.rs index 12ce457ea6ba..a4912bbeb528 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -667,7 +667,10 @@ fn cover_range(r0: Option, r1: Option) -> Option, token: SyntaxToken) -> FxHashSet { +fn find_defs<'db>( + sema: &Semantics<'db, RootDatabase>, + token: SyntaxToken, +) -> FxHashSet> { sema.descend_into_macros_exact(token) .into_iter() .filter_map(|token| IdentClass::classify_token(sema, &token)) diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index c3a8e0362fee..9ceeeffd719a 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -450,7 +450,7 @@ fn hover_ranged( pub(crate) fn hover_for_definition( sema: &Semantics<'_, RootDatabase>, file_id: FileId, - def: Definition, + def: Definition<'_>, subst: Option>, scope_node: &SyntaxNode, macro_arm: Option, @@ -542,7 +542,7 @@ fn notable_traits<'db>( fn show_implementations_action( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, ) -> Option { fn to_action(nav_target: NavigationTarget) -> HoverAction { HoverAction::Implementation(FilePosition { @@ -564,7 +564,7 @@ fn show_implementations_action( fn show_fn_references_action( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, ) -> Option { match def { Definition::Function(it) => { @@ -581,7 +581,7 @@ fn show_fn_references_action( fn runnable_action( sema: &hir::Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, file_id: FileId, ) -> Option { match def { @@ -602,7 +602,7 @@ fn runnable_action( fn goto_type_action_for_def( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, notable_traits: &[(hir::Trait, Vec<(Option>, hir::Name)>)], subst_types: Option)>>, edition: Edition, diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index da4f185d7564..aa8375b0e8df 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -345,7 +345,7 @@ pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option, markup: &Markup, markup_range_map: Option, config: &HoverConfig<'_>, @@ -359,7 +359,11 @@ pub(super) fn process_markup( Markup::from(markup) } -fn definition_owner_name(db: &RootDatabase, def: Definition, edition: Edition) -> Option { +fn definition_owner_name( + db: &RootDatabase, + def: Definition<'_>, + edition: Edition, +) -> Option { match def { Definition::Field(f) => { let parent = f.parent_def(db); @@ -452,7 +456,7 @@ pub(super) fn path( pub(super) fn definition( db: &RootDatabase, - def: Definition, + def: Definition<'_>, famous_defs: Option<&FamousDefs<'_, '_>>, notable_traits: &[(Trait, Vec<(Option>, Name)>)], macro_arm: Option, @@ -1071,7 +1075,7 @@ fn closure_ty( Some(res) } -fn definition_path(db: &RootDatabase, &def: &Definition, edition: Edition) -> Option { +fn definition_path(db: &RootDatabase, &def: &Definition<'_>, edition: Edition) -> Option { if matches!( def, Definition::TupleField(_) diff --git a/crates/ide/src/interpret.rs b/crates/ide/src/interpret.rs index 994d325cccde..f8e8d874492c 100644 --- a/crates/ide/src/interpret.rs +++ b/crates/ide/src/interpret.rs @@ -60,7 +60,7 @@ fn find_and_interpret(db: &RootDatabase, position: FilePosition) -> Option<(Dura pub(crate) fn render_const_eval_error( db: &RootDatabase, - e: ConstEvalError, + e: ConstEvalError<'_>, display_target: DisplayTarget, ) -> String { let span_formatter = |file_id, text_range: TextRange| { diff --git a/crates/ide/src/moniker.rs b/crates/ide/src/moniker.rs index 335e1b5b13ca..c92f2bbace84 100644 --- a/crates/ide/src/moniker.rs +++ b/crates/ide/src/moniker.rs @@ -118,7 +118,7 @@ pub enum MonikerResult { } impl MonikerResult { - pub fn from_def(db: &RootDatabase, def: Definition, from_crate: Crate) -> Option { + pub fn from_def(db: &RootDatabase, def: Definition<'_>, from_crate: Crate) -> Option { def_to_moniker(db, def, from_crate) } } @@ -178,7 +178,7 @@ pub(crate) fn moniker( Some(RangeInfo::new(original_token.text_range(), navs)) } -pub(crate) fn def_to_kind(db: &RootDatabase, def: Definition) -> SymbolInformationKind { +pub(crate) fn def_to_kind(db: &RootDatabase, def: Definition<'_>) -> SymbolInformationKind { use SymbolInformationKind::*; match def { @@ -250,7 +250,7 @@ pub(crate) fn def_to_kind(db: &RootDatabase, def: Definition) -> SymbolInformati /// definitions. pub(crate) fn def_to_moniker( db: &RootDatabase, - definition: Definition, + definition: Definition<'_>, from_crate: Crate, ) -> Option { match definition { @@ -266,7 +266,7 @@ pub(crate) fn def_to_moniker( fn enclosing_def_to_moniker( db: &RootDatabase, - mut def: Definition, + mut def: Definition<'_>, from_crate: Crate, ) -> Option { loop { @@ -280,7 +280,7 @@ fn enclosing_def_to_moniker( fn def_to_non_local_moniker( db: &RootDatabase, - definition: Definition, + definition: Definition<'_>, from_crate: Crate, ) -> Option { let module = match definition { diff --git a/crates/ide/src/navigation_target.rs b/crates/ide/src/navigation_target.rs index b8c14dc09f9a..f15f6c3b70b9 100644 --- a/crates/ide/src/navigation_target.rs +++ b/crates/ide/src/navigation_target.rs @@ -302,7 +302,7 @@ impl<'db> TryToNav for FileSymbol<'db> { } } -impl TryToNav for Definition { +impl TryToNav for Definition<'_> { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -655,7 +655,7 @@ impl TryToNav for hir::GenericParam { } } -impl ToNav for LocalSource { +impl ToNav for LocalSource<'_> { fn to_nav(&self, db: &RootDatabase) -> UpmappingResult { let InFile { file_id, value } = &self.source; let file_id = *file_id; @@ -691,7 +691,7 @@ impl ToNav for LocalSource { } } -impl ToNav for hir::Local { +impl ToNav for hir::Local<'_> { fn to_nav(&self, db: &RootDatabase) -> UpmappingResult { self.primary_source(db).to_nav(db) } diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 3eb7867a3ab3..ad6c4adc53a7 100644 --- a/crates/ide/src/references.rs +++ b/crates/ide/src/references.rs @@ -121,8 +121,8 @@ pub struct FindAllRefsConfig<'a> { /// - `;` after unit struct: Shows unit literal initializations /// - Type name in definition: Shows all initialization usages /// In these cases, other kinds of references (like type references) are filtered out. -pub(crate) fn find_all_refs( - sema: &Semantics<'_, RootDatabase>, +pub(crate) fn find_all_refs<'db>( + sema: &Semantics<'db, RootDatabase>, position: FilePosition, config: &FindAllRefsConfig<'_>, ) -> Option> { @@ -130,7 +130,7 @@ pub(crate) fn find_all_refs( let syntax = sema.parse_guess_edition(position.file_id).syntax().clone(); let exclude_library_refs = !is_library_file(sema.db, position.file_id); let make_searcher = |literal_search: bool| { - move |def: Definition| { + move |def: Definition<'db>| { let mut included_categories = ReferenceCategory::all(); if config.exclude_imports { included_categories.remove(ReferenceCategory::IMPORT); @@ -228,11 +228,11 @@ fn is_library_file(db: &RootDatabase, file_id: FileId) -> bool { db.source_root(source_root).source_root(db).is_library } -pub(crate) fn find_defs( - sema: &Semantics<'_, RootDatabase>, +pub(crate) fn find_defs<'db>( + sema: &Semantics<'db, RootDatabase>, syntax: &SyntaxNode, offset: TextSize, -) -> Option> { +) -> Option>> { if let Some(token) = syntax.token_at_offset(offset).left_biased() && let Some(doc_comment) = token_as_doc_comment(&token) { @@ -304,7 +304,7 @@ pub(crate) fn find_defs( /// Filter out all non-literal usages for adt-defs fn retain_adt_literal_usages( usages: &mut UsageSearchResult, - def: Definition, + def: Definition<'_>, sema: &Semantics<'_, RootDatabase>, ) { let refs = usages.references.values_mut(); diff --git a/crates/ide/src/rename.rs b/crates/ide/src/rename.rs index 26c677610784..bd98e1f1ec19 100644 --- a/crates/ide/src/rename.rs +++ b/crates/ide/src/rename.rs @@ -263,13 +263,14 @@ fn alias_fallback( Some(builder.finish()) } -fn find_definitions( - sema: &Semantics<'_, RootDatabase>, +fn find_definitions<'db>( + sema: &Semantics<'db, RootDatabase>, syntax: &SyntaxNode, FilePosition { file_id, offset }: FilePosition, new_name: &Name, -) -> RenameResult> -{ +) -> RenameResult< + impl Iterator, Name, RenameDefinition)>, +> { let maybe_format_args = syntax.token_at_offset(offset).find(|t| matches!(t.kind(), SyntaxKind::STRING)); @@ -481,9 +482,9 @@ fn transform_assoc_fn_into_method_call( } } -fn rename_to_self( - sema: &Semantics<'_, RootDatabase>, - local: hir::Local, +fn rename_to_self<'db>( + sema: &Semantics<'db, RootDatabase>, + local: hir::Local<'db>, ) -> RenameResult { if never!(local.is_self(sema.db)) { bail!("rename_to_self invoked on self"); @@ -738,9 +739,9 @@ fn transform_method_call_into_assoc_fn( } } -fn rename_self_to_param( - sema: &Semantics<'_, RootDatabase>, - local: hir::Local, +fn rename_self_to_param<'db>( + sema: &Semantics<'db, RootDatabase>, + local: hir::Local<'db>, self_param: hir::SelfParam, new_name: &Name, identifier_kind: IdentifierKind, diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 60750608a5b4..a56a93293f76 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs @@ -487,7 +487,7 @@ fn runnable_mod_outline_definition( }) } -fn module_def_doctest(sema: &Semantics<'_, RootDatabase>, def: Definition) -> Option { +fn module_def_doctest(sema: &Semantics<'_, RootDatabase>, def: Definition<'_>) -> Option { let db = sema.db; let attrs = match def { Definition::Module(it) => it.attrs(db), diff --git a/crates/ide/src/static_index.rs b/crates/ide/src/static_index.rs index 4b2c9ceef9ff..0d8b9d2d94e2 100644 --- a/crates/ide/src/static_index.rs +++ b/crates/ide/src/static_index.rs @@ -31,7 +31,7 @@ pub struct StaticIndex<'a> { pub tokens: TokenStore, analysis: &'a Analysis, db: &'a RootDatabase, - def_map: FxHashMap, + def_map: FxHashMap, TokenId>, } #[derive(Debug)] @@ -116,7 +116,7 @@ fn all_modules(db: &dyn HirDatabase) -> Vec { fn documentation_for_definition( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, scope_node: &SyntaxNode, ) -> Option> { let famous_defs = match &def { @@ -132,7 +132,7 @@ fn documentation_for_definition( fn get_definitions<'db>( sema: &Semantics<'db, RootDatabase>, token: SyntaxToken, -) -> Option>), 2>> { +) -> Option, Option>), 2>> { for token in sema.descend_into_macros_exact(token) { let def = IdentClass::classify_token(sema, &token).map(IdentClass::definitions); if let Some(defs) = def @@ -149,7 +149,7 @@ pub enum VendoredLibrariesConfig<'a> { Excluded, } -impl StaticIndex<'_> { +impl<'a> StaticIndex<'a> { fn add_file(&mut self, file_id: FileId) { let current_crate = crates_for(self.db, file_id).pop().map(Into::into); let folds = self.analysis.folding_ranges(file_id, true).unwrap(); @@ -223,7 +223,7 @@ impl StaticIndex<'_> { }; let mut result = StaticIndexedFile { file_id, inlay_hints, folds, tokens: vec![] }; - let mut add_token = |def: Definition, range: TextRange, scope_node: &SyntaxNode| { + let mut add_token = |def: Definition<'a>, range: TextRange, scope_node: &SyntaxNode| { let id = if let Some(it) = self.def_map.get(&def) { *it } else { @@ -291,7 +291,7 @@ impl StaticIndex<'_> { self.files.push(result); } - pub fn compute<'a>( + pub fn compute( analysis: &'a Analysis, vendored_libs_config: VendoredLibrariesConfig<'_>, ) -> StaticIndex<'a> { diff --git a/crates/ide/src/syntax_highlighting/highlight.rs b/crates/ide/src/syntax_highlighting/highlight.rs index 6823736d1273..92daacd6d314 100644 --- a/crates/ide/src/syntax_highlighting/highlight.rs +++ b/crates/ide/src/syntax_highlighting/highlight.rs @@ -457,7 +457,7 @@ fn highlight_name( pub(super) fn highlight_def( sema: &Semantics<'_, RootDatabase>, krate: Option, - def: Definition, + def: Definition<'_>, edition: Edition, is_ref: bool, ) -> Highlight { @@ -864,7 +864,7 @@ fn highlight_name_ref_by_syntax( } } -fn is_consumed_lvalue(node: &SyntaxNode, local: &hir::Local, db: &RootDatabase) -> bool { +fn is_consumed_lvalue(node: &SyntaxNode, local: &hir::Local<'_>, db: &RootDatabase) -> bool { // When lvalues are passed as arguments and they're not Copy, then mark them as Consuming. parents_match(node.clone().into(), &[PATH_SEGMENT, PATH, PATH_EXPR, ARG_LIST]) && !local.ty(db).is_copy(db) diff --git a/crates/ide/src/syntax_highlighting/inject.rs b/crates/ide/src/syntax_highlighting/inject.rs index 9af6d67b5980..56020b401780 100644 --- a/crates/ide/src/syntax_highlighting/inject.rs +++ b/crates/ide/src/syntax_highlighting/inject.rs @@ -211,7 +211,7 @@ pub(super) fn doc_comment( } } -fn module_def_to_hl_tag(db: &dyn HirDatabase, def: Definition) -> HlTag { +fn module_def_to_hl_tag(db: &dyn HirDatabase, def: Definition<'_>) -> HlTag { let symbol = match def { Definition::Crate(_) | Definition::ExternCrateDecl(_) => SymbolKind::CrateRoot, Definition::Module(m) if m.is_crate_root(db) => SymbolKind::CrateRoot,