Unnamed repository; edit this file 'description' to name the repository.
Unleash more lifetimes
125 files changed, 1862 insertions, 1464 deletions
diff --git a/Cargo.lock b/Cargo.lock index b2dc4ceedd..aa3fe4b100 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -825,6 +825,7 @@ dependencies = [ "la-arena 0.3.1 (registry+https://github.com/rust-lang/crates.io-index)", "ra-ap-rustc_type_ir", "rustc-hash 2.1.2", + "salsa", "serde_json", "smallvec", "span", @@ -2484,6 +2485,7 @@ dependencies = [ "smallvec", "thin-vec", "tracing", + "triomphe", "typeid", ] @@ -3089,6 +3091,10 @@ name = "triomphe" version = "0.1.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd69c5aa8f924c7519d6372789a74eac5b94fb0f8fcf0d4a97eb0bfc3e785f39" +dependencies = [ + "serde", + "stable_deref_trait", +] [[package]] name = "tt" diff --git a/Cargo.toml b/Cargo.toml index 96ddbbb5ca..2a219c3ea4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -131,6 +131,7 @@ salsa = { version = "0.27.0", default-features = false, features = [ "salsa_unstable", "macros", "inventory", + "triomphe" ] } salsa-macros = "0.27.0" semver = "1.0.26" diff --git a/crates/base-db/src/editioned_file_id.rs b/crates/base-db/src/editioned_file_id.rs index a77b45f8ae..f674c5df95 100644 --- a/crates/base-db/src/editioned_file_id.rs +++ b/crates/base-db/src/editioned_file_id.rs @@ -16,57 +16,24 @@ pub struct EditionedFileId { field: span::EditionedFileId, } -// Currently does not work due to a salsa bug -// #[salsa::tracked] -// impl EditionedFileId { -// #[salsa::tracked(lru = 128)] -// pub fn parse(self, db: &dyn SourceDatabase) -> syntax::Parse<ast::SourceFile> { -// let _p = tracing::info_span!("parse", ?self).entered(); -// let (file_id, edition) = self.unpack(db); -// let text = db.file_text(file_id).text(db); -// ast::SourceFile::parse(text, edition) -// } - -// // firewall query -// #[salsa::tracked(returns(as_deref))] -// pub fn parse_errors(self, db: &dyn SourceDatabase) -> Option<Box<[SyntaxError]>> { -// let errors = self.parse(db).errors(); -// match &*errors { -// [] => None, -// [..] => Some(errors.into()), -// } -// } -// } - +#[salsa::tracked] impl EditionedFileId { + #[salsa::tracked(lru = 128)] pub fn parse(self, db: &dyn SourceDatabase) -> syntax::Parse<ast::SourceFile> { - #[salsa::tracked(lru = 128)] - pub fn parse( - db: &dyn SourceDatabase, - file_id: EditionedFileId, - ) -> syntax::Parse<ast::SourceFile> { - let _p = tracing::info_span!("parse", ?file_id).entered(); - let (file_id, edition) = file_id.unpack(db); - let text = db.file_text(file_id).text(db); - ast::SourceFile::parse(text, edition) - } - parse(db, self) + let _p = tracing::info_span!("parse", ?self).entered(); + let (file_id, edition) = self.unpack(db); + let text = db.file_text(file_id).text(db); + ast::SourceFile::parse(text, edition) } // firewall query - pub fn parse_errors(self, db: &dyn SourceDatabase) -> Option<&[SyntaxError]> { - #[salsa::tracked(returns(as_deref))] - pub fn parse_errors( - db: &dyn SourceDatabase, - file_id: EditionedFileId, - ) -> Option<Box<[SyntaxError]>> { - let errors = file_id.parse(db).errors(); - match &*errors { - [] => None, - [..] => Some(errors.into()), - } + #[salsa::tracked(returns(as_deref))] + pub fn parse_errors(self, db: &dyn SourceDatabase) -> Option<Box<[SyntaxError]>> { + let errors = self.parse(db).errors(); + match &*errors { + [] => None, + [..] => Some(errors.into()), } - parse_errors(db, self) } } diff --git a/crates/base-db/src/lib.rs b/crates/base-db/src/lib.rs index 94d9d08e50..b3c7f84249 100644 --- a/crates/base-db/src/lib.rs +++ b/crates/base-db/src/lib.rs @@ -1,15 +1,48 @@ //! base_db defines basic database traits. The concrete DB is defined by ide. +// FIXME: Rename this crate, base db is non descriptive #![cfg_attr(feature = "in-rust-tree", feature(rustc_private))] #[cfg(feature = "in-rust-tree")] extern crate rustc_driver as _; -pub use salsa; +pub mod salsa { + pub use salsa::*; + + // Adjusted from `salsa::update_fallback` to work with database owned T + /// "Fallback" for maybe-update that is suitable for database owned T + /// that implement `Eq`. In this version, we update only if the new value + /// is not `Eq` to the old one. Note that given `Eq` impls that are not just + /// structurally comparing fields, this may cause us not to update even if + /// the value has changed (presumably because this change is not semantically + /// significant). + /// + /// # Safety + /// + /// See `Update::maybe_update`, additionally, `'db` is required to be `'static` or the lifetime + /// of the database `T` belongs to. + pub unsafe fn update_fallback_db<'db, T>(old_pointer: *mut T, new_value: T) -> bool + where + T: 'db + PartialEq, + { + // SAFETY: Because everything is owned, this ref is simply a valid `&mut` + let old_ref: &mut T = unsafe { &mut *old_pointer }; + + if *old_ref != new_value { + *old_ref = new_value; + true + } else { + // Subtle but important: Eq impls can be buggy or define equality + // in surprising ways. If it says that the value has not changed, + // we do not modify the existing value, and thus do not have to + // update the revision, as downstream code will not see the new value. + false + } + } +} pub use salsa_macros; use span::TextSize; -// FIXME: Rename this crate, base db is non descriptive mod change; mod editioned_file_id; mod input; @@ -65,28 +98,6 @@ macro_rules! impl_intern_key { }; } -/// # SAFETY -/// -/// `old_pointer` must be valid for unique writes -pub unsafe fn unsafe_update_eq<T>(old_pointer: *mut T, new_value: T) -> bool -where - T: PartialEq, -{ - // SAFETY: Caller obligation - let old_ref: &mut T = unsafe { &mut *old_pointer }; - - if *old_ref != new_value { - *old_ref = new_value; - true - } else { - // Subtle but important: Eq impls can be buggy or define equality - // in surprising ways. If it says that the value has not changed, - // we do not modify the existing value, and thus do not have to - // update the revision, as downstream code will not see the new value. - false - } -} - pub const DEFAULT_FILE_TEXT_LRU_CAP: u16 = 16; pub const DEFAULT_PARSE_LRU_CAP: u16 = 128; pub const DEFAULT_BORROWCK_LRU_CAP: u16 = 2024; diff --git a/crates/hir-def/src/nameres/tests/incremental.rs b/crates/hir-def/src/nameres/tests/incremental.rs index 49d94b969d..5cd70955ab 100644 --- a/crates/hir-def/src/nameres/tests/incremental.rs +++ b/crates/hir-def/src/nameres/tests/incremental.rs @@ -167,22 +167,22 @@ fn no() {} "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "EnumVariants::of_", ] "#]], expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -225,16 +225,16 @@ pub struct S {} "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "AstId < ast :: Macro >::decl_macro_expander_", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "MacroId::definition_", "file_item_tree_query", @@ -245,7 +245,7 @@ pub struct S {} "#]], expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -283,21 +283,21 @@ fn f() { foo } "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "crate_local_def_map", "ProcMacros::get_for_crate_", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "MacroId::definition_", "file_item_tree_query", @@ -310,7 +310,7 @@ fn f() { foo } "#]], expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -407,22 +407,22 @@ pub struct S {} "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "crate_local_def_map", "ProcMacros::get_for_crate_", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "AstId < ast :: Macro >::decl_macro_expander_", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "MacroId::definition_", "file_item_tree_query", @@ -446,7 +446,7 @@ pub struct S {} "#]], expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -524,16 +524,16 @@ m!(Z); "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "AstId < ast :: Macro >::decl_macro_expander_", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "MacroId::definition_", "file_item_tree_query", @@ -571,7 +571,7 @@ m!(Z); &[("file_item_tree_query", 1), ("parse_macro_expansion", 0)], expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -611,7 +611,7 @@ pub type Ty = (); [ "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", ] "#]], @@ -629,7 +629,7 @@ pub type Ty = (); &[("file_item_tree_query", 1), ("parse", 1)], expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", diff --git a/crates/hir-ty/src/autoderef.rs b/crates/hir-ty/src/autoderef.rs index c9d3a87e96..4fab468dfd 100644 --- a/crates/hir-ty/src/autoderef.rs +++ b/crates/hir-ty/src/autoderef.rs @@ -130,8 +130,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 @@ -162,8 +162,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 @@ -240,10 +240,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 { @@ -251,7 +251,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 e58a22332c..15dd530312 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<MirLowerError> for ConstEvalError { - fn from(value: MirLowerError) -> Self { +impl<'db> From<MirLowerError<'db>> for ConstEvalError<'db> { + fn from(value: MirLowerError<'db>) -> Self { match value { MirLowerError::ConstEvalError(_, e) => *e, _ => ConstEvalError::MirLowerError(value), @@ -69,8 +70,8 @@ impl From<MirLowerError> for ConstEvalError { } } -impl From<MirEvalError> for ConstEvalError { - fn from(value: MirEvalError) -> Self { +impl<'db> From<MirEvalError<'db>> for ConstEvalError<'db> { + fn from(value: MirEvalError<'db>) -> Self { ConstEvalError::MirEvalError(value) } } @@ -414,10 +415,10 @@ pub(crate) fn create_anon_const<'a, 'db>( } #[salsa::tracked(cycle_result = const_eval_discriminant_cycle_result)] -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<i128, ConstEvalError> { +) -> Result<i128, ConstEvalError<'db>> { let interner = DbInterner::new_no_crate(db); let def = variant_id.into(); let body = Body::of(db, def); @@ -450,11 +451,11 @@ pub(crate) fn const_eval_discriminant_variant( Ok(c) } -fn const_eval_discriminant_cycle_result( - _: &dyn HirDatabase, +fn const_eval_discriminant_cycle_result<'db>( + _: &'db dyn HirDatabase, _: salsa::Id, _: EnumVariantId, -) -> Result<i128, ConstEvalError> { +) -> Result<i128, ConstEvalError<'db>> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } @@ -463,58 +464,58 @@ pub(crate) fn const_eval<'db>( def: ConstId, subst: GenericArgs<'db>, trait_env: Option<ParamEnvAndCrate<'db>>, -) -> Result<Allocation<'db>, ConstEvalError> { +) -> Result<Allocation<'db>, 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<StoredParamEnvAndCrate>, - ) -> Result<StoredAllocation, ConstEvalError> { + ) -> Result<StoredAllocation, ConstEvalError<'db>> { 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<StoredParamEnvAndCrate>, - ) -> Result<StoredAllocation, ConstEvalError> { + ) -> Result<StoredAllocation, ConstEvalError<'db>> { 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<ParamEnvAndCrate<'db>>, -) -> Result<Allocation<'db>, ConstEvalError> { +) -> Result<Allocation<'db>, 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<StoredParamEnvAndCrate>, - ) -> Result<StoredAllocation, ConstEvalError> { + ) -> Result<StoredAllocation, ConstEvalError<'db>> { let body = db.monomorphized_mir_body( def.into(), subst, @@ -524,17 +525,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<StoredParamEnvAndCrate>, - ) -> Result<StoredAllocation, ConstEvalError> { + ) -> Result<StoredAllocation, ConstEvalError<'db>> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } } @@ -542,17 +543,17 @@ pub(crate) fn anon_const_eval<'db>( pub(crate) fn const_eval_static<'db>( db: &'db dyn HirDatabase, def: StaticId, -) -> Result<Allocation<'db>, ConstEvalError> { +) -> Result<Allocation<'db>, 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<StoredAllocation, ConstEvalError> { + ) -> Result<StoredAllocation, ConstEvalError<'db>> { let interner = DbInterner::new_no_crate(db); let body = db.monomorphized_mir_body( def.into(), @@ -564,11 +565,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<StoredAllocation, ConstEvalError> { + ) -> Result<StoredAllocation, ConstEvalError<'db>> { Err(ConstEvalError::MirLowerError(MirLowerError::Loop)) } } diff --git a/crates/hir-ty/src/consteval/tests.rs b/crates/hir-ty/src/consteval/tests.rs index 546238f9bb..95ebdbd409 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<Allocation<'_>, ConstEvalError> { +fn eval_goal(db: &TestDB, file_id: EditionedFileId) -> Result<Allocation<'_>, 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 c74ac51b61..73b1183cb2 100644 --- a/crates/hir-ty/src/db.rs +++ b/crates/hir-ty/src/db.rs @@ -16,8 +16,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::{ @@ -43,32 +43,38 @@ pub trait HirDatabase: SourceDatabase + std::fmt::Debug { // FIXME: 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).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).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).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) .map_err(|err| err.clone()) } @@ -80,24 +86,30 @@ pub trait HirDatabase: SourceDatabase + std::fmt::Debug { def: ConstId, subst: GenericArgs<'db>, trait_env: Option<ParamEnvAndCrate<'db>>, - ) -> Result<Allocation<'db>, ConstEvalError>; + ) -> Result<Allocation<'db>, 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<ParamEnvAndCrate<'db>>, - ) -> Result<Allocation<'db>, ConstEvalError>; + ) -> Result<Allocation<'db>, ConstEvalError<'db>>; #[salsa::invoke(crate::consteval::const_eval_static)] #[salsa::transparent] - fn const_eval_static<'db>(&'db self, def: StaticId) -> Result<Allocation<'db>, ConstEvalError>; + fn const_eval_static<'db>( + &'db self, + def: StaticId, + ) -> Result<Allocation<'db>, ConstEvalError<'db>>; #[salsa::invoke(crate::consteval::const_eval_discriminant_variant)] #[salsa::transparent] - fn const_eval_discriminant(&self, def: EnumVariantId) -> Result<i128, ConstEvalError>; + fn const_eval_discriminant<'db>( + &'db self, + def: EnumVariantId, + ) -> Result<i128, ConstEvalError<'db>>; #[salsa::invoke(crate::method_resolution::lookup_impl_method_query)] #[salsa::transparent] @@ -141,10 +153,10 @@ pub trait HirDatabase: SourceDatabase + 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<StoredEarlyBinder<StoredTy>>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder<StoredTy>>; /// Returns the type of the value of the given constant, or `None` if the `ValueTyDefId` is /// a `StructId` or `EnumVariantId` with a record constructor. @@ -158,10 +170,10 @@ pub trait HirDatabase: SourceDatabase + 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<StoredEarlyBinder<StoredTy>>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder<StoredTy>>; #[salsa::invoke(crate::lower::type_for_static)] #[salsa::transparent] @@ -169,17 +181,17 @@ pub trait HirDatabase: SourceDatabase + 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<StoredEarlyBinder<StoredTy>>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder<StoredTy>>; #[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<StoredEarlyBinder<StoredTy>>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder<StoredTy>>; #[salsa::invoke(crate::lower::impl_self_ty_query)] #[salsa::transparent] @@ -187,10 +199,10 @@ pub trait HirDatabase: SourceDatabase + 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<ArenaMap<LocalTypeOrConstParamId, StoredTy>>; + ) -> &'db TyLoweringResult<'db, ArenaMap<LocalTypeOrConstParamId, StoredTy>>; #[salsa::invoke(crate::lower::const_param_types)] #[salsa::transparent] @@ -202,10 +214,10 @@ pub trait HirDatabase: SourceDatabase + 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<TyLoweringResult<StoredEarlyBinder<StoredTraitRef>>>; + ) -> &'db Option<TyLoweringResult<'db, StoredEarlyBinder<StoredTraitRef>>>; #[salsa::invoke(crate::lower::impl_trait_query)] #[salsa::transparent] @@ -213,10 +225,10 @@ pub trait HirDatabase: SourceDatabase + 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<ArenaMap<LocalFieldId, FieldType>>; + ) -> &'db TyLoweringResult<'db, ArenaMap<LocalFieldId, FieldType>>; #[salsa::invoke(crate::lower::field_types_query)] #[salsa::transparent] @@ -231,10 +243,10 @@ pub trait HirDatabase: SourceDatabase + 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<StoredEarlyBinder<StoredPolyFnSig>>; + ) -> &'db TyLoweringResult<'db, StoredEarlyBinder<StoredPolyFnSig>>; #[salsa::invoke(crate::lower::trait_environment)] #[salsa::transparent] @@ -242,10 +254,10 @@ pub trait HirDatabase: SourceDatabase + 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<GenericDefaults>; + ) -> &'db TyLoweringResult<'db, GenericDefaults>; /// This returns an empty list if no parameter has default. /// @@ -256,10 +268,10 @@ pub trait HirDatabase: SourceDatabase + 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<TypeAliasBounds<StoredEarlyBinder<StoredClauses>>>; + ) -> &'db TyLoweringResult<'db, TypeAliasBounds<StoredEarlyBinder<StoredClauses>>>; #[salsa::invoke(crate::lower::type_alias_bounds)] #[salsa::transparent] @@ -291,22 +303,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]; @@ -326,15 +338,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]; @@ -355,15 +367,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]; @@ -399,16 +411,16 @@ 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 { +impl<'db> AnonConstId<'db> { pub(crate) fn new( - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, loc: AnonConstLoc, token: TrackedStructToken, ) -> Self { @@ -417,23 +429,23 @@ impl AnonConstId { } } -impl HasModule for AnonConstId { +impl HasModule for AnonConstId<'_> { fn module(&self, db: &dyn SourceDatabase) -> ModuleId { self.loc(db).owner.module(db) } } -impl HasResolver for AnonConstId { +impl HasResolver for AnonConstId<'_> { fn resolver(self, db: &dyn SourceDatabase) -> 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: @@ -470,16 +482,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<ConstId> for GeneralConstId<'db> { + fn from(it: ConstId) -> GeneralConstId<'db> { + GeneralConstId::ConstId(it) + } +} +impl<'db> From<StaticId> for GeneralConstId<'db> { + fn from(it: StaticId) -> GeneralConstId<'db> { + GeneralConstId::StaticId(it) + } +} +impl<'db> From<AnonConstId<'db>> for GeneralConstId<'db> { + fn from(it: AnonConstId<'db>) -> GeneralConstId<'db> { + GeneralConstId::AnonConstId(it) + } +} -impl GeneralConstId { - pub fn generic_def(self, db: &dyn HirDatabase) -> Option<GenericDefId> { +impl<'db> GeneralConstId<'db> { + pub fn generic_def(self, db: &'db dyn HirDatabase) -> Option<GenericDefId> { match self { GeneralConstId::ConstId(it) => Some(it.into()), GeneralConstId::StaticId(it) => Some(it.into()), @@ -487,7 +513,7 @@ impl GeneralConstId { } } - pub fn name(self, db: &dyn SourceDatabase) -> String { + pub fn name(self, db: &'db dyn SourceDatabase) -> 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 d04419c5e5..fd8d7e02a5 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<BodyValidationDiagnostic<'db>>, validate_lints: bool, @@ -633,9 +633,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<LocalFieldId>)> { @@ -676,9 +676,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<LocalFieldId>)> { @@ -713,8 +713,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 14bff65220..613912e090 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<PatternError>, } @@ -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 88a44d2e6a..3021de68f3 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 64d0e2a864..6b551775d5 100644 --- a/crates/hir-ty/src/infer.rs +++ b/crates/hir-ty/src/infer.rs @@ -65,6 +65,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; @@ -118,7 +119,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) } @@ -127,7 +128,7 @@ pub fn infer_query_with_inspect<'db>( def: DefWithBodyId, inspect: Option<ObligationInspector<'db>>, 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); @@ -185,7 +186,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)) @@ -193,7 +198,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; @@ -221,18 +229,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(); @@ -736,8 +744,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<ExprId, (FunctionId, StoredGenericArgs)>, /// For each field access expr, records the field it resolves to. @@ -801,7 +809,7 @@ pub struct InferenceResult { pub closures_data: FxHashMap<ExprId, ClosureData>, - defined_anon_consts: ThinVec<AnonConstId>, + defined_anon_consts: ThinVec<AnonConstId<'db>>, } #[derive(Clone, PartialEq, Eq, Debug, Default)] @@ -1022,24 +1030,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<InferBodyId>) -> &InferenceResult { + pub fn of( + db: &'db dyn HirDatabase, + def: impl Into<InferBodyId<'db>>, + ) -> &'db InferenceResult<'db> { match def.into() { InferBodyId::DefWithBodyId(it) => InferenceResult::for_body(db, it), InferBodyId::AnonConstId(it) => InferenceResult::for_anon_const(db, it), @@ -1047,7 +1063,7 @@ impl InferenceResult { } } -impl InferenceResult { +impl<'db> InferenceResult<'db> { fn new(error_ty: Ty<'_>) -> Self { Self { method_resolutions: Default::default(), @@ -1074,7 +1090,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<Either<FieldId, TupleFieldId>> { @@ -1092,22 +1108,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), @@ -1130,19 +1146,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<Item = (TypeRefId, Ty<'db>)> { + pub fn placeholder_types<'a>(&self) -> impl Iterator<Item = (TypeRefId, Ty<'a>)> { 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<Ty<'db>> { + pub fn type_of_type_placeholder<'a>(&self, type_ref: TypeRefId) -> Option<Ty<'a>> { 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<Ty<'db>> { + pub fn type_of_expr_or_pat<'a>(&self, id: ExprOrPatId) -> Option<Ty<'a>> { 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<Ty<'db>> { + pub fn type_of_expr_with_adjust<'a>(&self, id: ExprId) -> Option<Ty<'a>> { 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 @@ -1159,7 +1175,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), @@ -1173,7 +1189,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() } @@ -1190,25 +1206,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<Item = (ExprId, Ty<'db>)> { + pub fn expression_types<'a>(&self) -> impl Iterator<Item = (ExprId, Ty<'a>)> { 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<Item = (PatId, Ty<'db>)> { + pub fn pattern_types<'a>(&self) -> impl Iterator<Item = (PatId, Ty<'a>)> { 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<Item = (BindingId, Ty<'db>)> { + pub fn binding_types<'a>(&self) -> impl Iterator<Item = (BindingId, Ty<'a>)> { 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<Item = (ImplTraitIdx, Ty<'db>)> { + pub fn return_position_impl_trait_types<'a>( + &'a self, + db: &'a dyn HirDatabase, + ) -> impl Iterator<Item = (ImplTraitIdx, Ty<'a>)> { self.type_of_opaque.iter().filter_map(move |(&id, ty)| { let ImplTraitId::ReturnTypeImplTrait(_, rpit_idx) = id.loc(db) else { return None; @@ -1217,24 +1233,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<Item = Ty<'db>> { + pub fn closure_captures_tys<'a>(&self, closure: ExprId) -> impl Iterator<Item = Ty<'a>> { self.closures_data[&closure] .min_captures .values() @@ -1242,11 +1258,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<Item = Ty<'db>> { + ) -> impl Iterator<Item = Ty<'a>> { self.closures_data[&closure] .min_captures .values() @@ -1266,12 +1282,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. @@ -1286,7 +1302,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<TraitId>, - pub(crate) result: InferenceResult, + pub(crate) result: InferenceResult<'db>, tuple_field_accesses_rev: IndexSet<Tys<'db>, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>, /// The return type of the function being inferred, the closure or async block if we're @@ -1316,7 +1332,7 @@ pub(crate) struct InferenceContext<'body, 'db> { diagnostics: Diagnostics, vars_emitted_type_must_be_known_for: FxHashSet<Term<'db>>, - defined_anon_consts: RefCell<ThinVec<AnonConstId>>, + defined_anon_consts: RefCell<ThinVec<AnonConstId<'db>>>, } #[derive(Clone, Debug)] @@ -1363,13 +1379,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, @@ -1411,7 +1427,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, @@ -1566,7 +1582,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, @@ -1699,7 +1715,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, @@ -1711,7 +1727,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, @@ -1920,7 +1936,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { fn with_ty_lowering<R>( &mut self, - store: &ExpressionStore, + store: &'db ExpressionStore, types_source: InferenceTyDiagnosticSource, store_owner: ExpressionStoreOwnerId, lifetime_elision: LifetimeElisionKind<'db>, @@ -1967,7 +1983,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>, @@ -2555,7 +2571,7 @@ impl<'body, 'db> InferenceContext<'body, 'db> { }; fn forbid_unresolved_segments<'db>( - ctx: &InferenceContext<'_, 'db>, + ctx: &InferenceContext<'db>, result: (Ty<'db>, Option<VariantId>), unresolved: Option<usize>, ) -> (Ty<'db>, Option<VariantId>) { @@ -2725,7 +2741,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 e5304582ca..7331f7a8a4 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<CallStep<'db>> { let final_ty = autoderef.final_ty(); @@ -540,8 +540,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 da996ccbea..dc08139081 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<Option<PointerKind<'db>>, ()> { 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 2a5567dfae..e2948a81ac 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 5ea43bc03c..e6c449cfe3 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 d8a8cceee6..7f4b112b68 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<Ty<'db>>) -> Result<Ty<'db>> { match ty { Some(ty) => { diff --git a/crates/hir-ty/src/infer/coerce.rs b/crates/hir-ty/src/infer/coerce.rs index 343919f5ba..85d8142335 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 e871edd265..676317ffba 100644 --- a/crates/hir-ty/src/infer/diagnostics.rs +++ b/crates/hir-ty/src/infer/diagnostics.rs @@ -90,7 +90,7 @@ pub(super) struct InferenceTyLoweringContext<'db, 'a> { ctx: TyLoweringContext<'db, 'a>, diagnostics: &'a Diagnostics, source: InferenceTyDiagnosticSource, - defined_anon_consts: &'a RefCell<ThinVec<AnonConstId>>, + defined_anon_consts: &'a RefCell<ThinVec<AnonConstId<'db>>>, } impl<'db, 'a> InferenceTyLoweringContext<'db, 'a> { @@ -98,7 +98,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, @@ -107,7 +107,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<ThinVec<AnonConstId>>, + defined_anon_consts: &'a RefCell<ThinVec<AnonConstId<'db>>>, lifetime_lowering_mode: LifetimeLoweringMode, ) -> Self { let mut ctx = TyLoweringContext::new( diff --git a/crates/hir-ty/src/infer/expr.rs b/crates/hir-ty/src/infer/expr.rs index 40465e3952..b730c9552d 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, @@ -2097,7 +2097,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 3744a434d2..0498ea8fd0 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 4fa1b71ad4..9ec297f5f5 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 85801358d4..5fd4e830fb 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 <op>= 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 63149deb82..2d64f9567b 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 1e539d24c1..bab4e79700 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 ecc81f9de0..56a503f2d2 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 bbf047b8ba..b226e5ca85 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 4c808714d9..6157f51500 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 adba047042..db1f7b874e 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/lib.rs b/crates/hir-ty/src/lib.rs index 120c265fdc..d217024b56 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<Ty<'db>, MirEvalError> { + pub fn vtable_ty(&self, id: usize) -> Result<Ty<'db>, 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<usize, MirEvalError>, - ) -> Result<FxHashMap<usize, usize>, MirEvalError> { + mut f: impl FnMut(&[u8], usize) -> Result<usize, MirEvalError<'db>>, + ) -> Result<FxHashMap<usize, usize>, 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) }; @@ -553,19 +554,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<EnumVariantId> for InferBodyId { +impl<'db> From<DefWithBodyId> for InferBodyId<'db> { + fn from(it: DefWithBodyId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it) + } +} +impl<'db> From<FunctionId> for InferBodyId<'db> { + fn from(it: FunctionId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it.into()) + } +} +impl<'db> From<ConstId> for InferBodyId<'db> { + fn from(it: ConstId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it.into()) + } +} +impl<'db> From<StaticId> for InferBodyId<'db> { + fn from(it: StaticId) -> InferBodyId<'db> { + InferBodyId::DefWithBodyId(it.into()) + } +} +impl<'db> From<AnonConstId<'db>> for InferBodyId<'db> { + fn from(it: AnonConstId<'db>) -> InferBodyId<'db> { + InferBodyId::AnonConstId(it) + } +} +impl<'db> From<EnumVariantId> 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 SourceDatabase) -> ModuleId { match self { InferBodyId::DefWithBodyId(id) => id.module(db), @@ -574,7 +599,7 @@ impl HasModule for InferBodyId { } } -impl HasResolver for InferBodyId { +impl HasResolver for InferBodyId<'_> { fn resolver(self, db: &dyn SourceDatabase) -> Resolver<'_> { match self { InferBodyId::DefWithBodyId(id) => id.resolver(db), @@ -583,7 +608,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 ccc3356686..7450a0d293 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -10,6 +10,7 @@ pub(crate) mod path; use std::{cell::OnceCell, iter, mem, sync::OnceLock}; +use base_db::salsa::update_fallback_db; use either::Either; use hir_def::{ AdtId, AssocItemId, CallableDefId, ConstId, ConstParamId, EnumId, EnumVariantId, @@ -50,6 +51,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; @@ -210,7 +212,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<Generics<'db>>, @@ -223,7 +225,7 @@ pub struct TyLoweringContext<'db, 'a> { lifetime_elision: LifetimeElisionKind<'db>, forbid_params_after: Option<u32>, forbid_params_after_reason: ForbidParamsAfterReason, - pub(crate) defined_anon_consts: ThinVec<AnonConstId>, + pub(crate) defined_anon_consts: ThinVec<AnonConstId<'db>>, infer_vars: Option<&'a mut dyn TyLoweringInferVarsCtx<'db>>, is_lowering_impl_trait_bounds: bool, bound_vars: Vec<BoundVarKinds<'db>>, // FIXME: HRTB and other for lifetime doesn't change it now @@ -234,7 +236,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<Generics<'db>>, @@ -1295,13 +1297,21 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> { } } -#[derive(Clone, PartialEq, Eq)] -pub struct TyLoweringResult<T> { +#[derive(Clone, PartialEq, Eq, Update)] +pub struct TyLoweringResult<'db, T> { + #[update(fallback)] pub value: T, - info: Option<Box<(ThinVec<TyLoweringDiagnostic>, ThinVec<AnonConstId>)>>, + #[update(bounds(TyLoweringResultInfo<'db>: Update), unsafe(with(update_fallback_db::<'db, _>)))] + info: Option<Box<TyLoweringResultInfo<'db>>>, } -impl<T: std::fmt::Debug> std::fmt::Debug for TyLoweringResult<T> { +#[derive(Clone, PartialEq, Eq, Update)] +struct TyLoweringResultInfo<'db> { + diagnostics: ThinVec<TyLoweringDiagnostic>, + anon_consts: ThinVec<AnonConstId<'db>>, +} + +impl<T: std::fmt::Debug> 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); @@ -1317,23 +1327,23 @@ impl<T: std::fmt::Debug> std::fmt::Debug for TyLoweringResult<T> { } } -impl<T> TyLoweringResult<T> { +impl<'db, T> TyLoweringResult<'db, T> { fn new( value: T, mut diagnostics: ThinVec<TyLoweringDiagnostic>, - mut defined_anon_consts: ThinVec<AnonConstId>, + mut defined_anon_consts: ThinVec<AnonConstId<'db>>, ) -> 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) } @@ -1344,15 +1354,15 @@ impl<T> TyLoweringResult<T> { #[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 => &[], } } @@ -1390,10 +1400,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<TyLoweringResult<StoredEarlyBinder<StoredTraitRef>>> { +) -> Option<TyLoweringResult<'db, StoredEarlyBinder<StoredTraitRef>>> { let impl_data = ImplSignature::of(db, impl_id); let resolver = impl_id.resolver(db); let generics = OnceCell::new(); @@ -1608,10 +1618,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<StoredEarlyBinder<StoredTy>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> { let resolver = def.resolver(db); let data = ConstSignature::of(db, def); let parent = def.loc(db).container; @@ -1640,10 +1650,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<StoredEarlyBinder<StoredTy>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> { let resolver = def.resolver(db); let data = StaticSignature::of(db, def); let generics = OnceCell::new(); @@ -1719,10 +1729,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<StoredEarlyBinder<StoredTy>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> { let type_alias_data = TypeAliasSignature::of(db, t); let interner = DbInterner::new_no_crate(db); if type_alias_data.flags.contains(TypeAliasFlags::IS_EXTERN) { @@ -1754,11 +1764,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<StoredEarlyBinder<StoredTy>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> { TyLoweringResult::empty(StoredEarlyBinder::bind( Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed).store(), )) @@ -1772,10 +1782,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<StoredEarlyBinder<StoredTy>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> { let resolver = impl_id.resolver(db); let generics = OnceCell::new(); let impl_data = ImplSignature::of(db, impl_id); @@ -1794,11 +1804,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<StoredEarlyBinder<StoredTy>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredTy>> { TyLoweringResult::empty(StoredEarlyBinder::bind( Ty::new_error(DbInterner::new_no_crate(db), ErrorGuaranteed).store(), )) @@ -1820,10 +1830,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<ArenaMap<LocalTypeOrConstParamId, StoredTy>> { +) -> TyLoweringResult<'db, ArenaMap<LocalTypeOrConstParamId, StoredTy>> { let mut result = ArenaMap::new(); let (data, store) = GenericParams::with_store(db, def); let resolver = def.resolver(db); @@ -1848,11 +1858,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<ArenaMap<LocalTypeOrConstParamId, StoredTy>> { +) -> TyLoweringResult<'db, ArenaMap<LocalTypeOrConstParamId, StoredTy>> { TyLoweringResult::empty(ArenaMap::default()) } @@ -1883,10 +1893,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<ArenaMap<LocalFieldId, FieldType>> { +) -> TyLoweringResult<'db, ArenaMap<LocalFieldId, FieldType>> { let var_data = variant_id.fields(db); let fields = var_data.fields(); if fields.is_empty() { @@ -2215,10 +2225,10 @@ pub struct TypeAliasBounds<T> { } #[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<TypeAliasBounds<StoredEarlyBinder<StoredClauses>>> { +) -> TyLoweringResult<'db, TypeAliasBounds<StoredEarlyBinder<StoredClauses>>> { let type_alias_data = TypeAliasSignature::of(db, type_alias); let resolver = type_alias.resolver(db); let generics = OnceCell::new(); @@ -2302,17 +2312,17 @@ impl<'db> GenericPredicates { pub fn query_with_diagnostics( db: &'db dyn HirDatabase, def: GenericDefId, - ) -> TyLoweringResult<GenericPredicates> { + ) -> 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<GenericPredicates> { +) -> TyLoweringResult<'db, GenericPredicates> { TyLoweringResult::empty(GenericPredicates::from_explicit_own_predicates( StoredEarlyBinder::bind(Clauses::empty(DbInterner::new_no_crate(db)).store()), )) @@ -2452,10 +2462,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<GenericPredicates> { +) -> TyLoweringResult<'db, GenericPredicates> { let generics = generics(db, def); let store = generics.store(); let generics = &OnceCell::from(generics); @@ -2667,10 +2677,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<GenericDefaults> { +) -> TyLoweringResult<'db, GenericDefaults> { let generics = generics(db, def); if generics.has_no_params() { return TyLoweringResult::empty(GenericDefaults(ThinVec::new())); @@ -2731,11 +2741,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<GenericDefaults> { +) -> TyLoweringResult<'db, GenericDefaults> { TyLoweringResult::empty(GenericDefaults(ThinVec::new())) } @@ -2748,10 +2758,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<StoredEarlyBinder<StoredPolyFnSig>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredPolyFnSig>> { match def { CallableDefId::FunctionId(f) => fn_sig_for_fn(db, f), CallableDefId::StructId(s) => TyLoweringResult::empty(fn_sig_for_struct_constructor(db, s)), @@ -2761,10 +2771,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<StoredEarlyBinder<StoredPolyFnSig>> { +) -> TyLoweringResult<'db, StoredEarlyBinder<StoredPolyFnSig>> { 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 c5868ab6b5..e8702bf2c9 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -11,10 +11,11 @@ mod probe; use either::Either; use hir_expand::name::Name; +use salsa::Update; use span::Edition; use tracing::{debug, instrument}; -use base_db::Crate; +use base_db::{Crate, salsa::update_fallback_db}; use hir_def::{ AssocItemId, BlockIdLt, BuiltinDeriveImplId, ConstId, FunctionId, GenericParamId, HasModule, ImplId, ItemContainerId, ModuleId, TraitId, @@ -125,7 +126,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). @@ -522,10 +523,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() { @@ -547,7 +548,7 @@ pub fn with_incoherent_inherent_impls( } } -pub fn simplified_type_module(db: &dyn HirDatabase, ty: &SimplifiedType) -> Option<ModuleId> { +pub fn simplified_type_module(db: &dyn HirDatabase, ty: &SimplifiedType<'_>) -> Option<ModuleId> { match ty.def()? { SolverDefId::AdtId(id) => Some(id.module(db)), SolverDefId::TypeAliasId(id) => Some(id.module(db)), @@ -556,15 +557,16 @@ pub fn simplified_type_module(db: &dyn HirDatabase, ty: &SimplifiedType) -> Opti } } -#[derive(Debug, PartialEq, Eq)] -pub struct InherentImpls { - map: FxHashMap<SimplifiedType, Box<[ImplId]>>, +#[derive(Debug, PartialEq, Eq, Update)] +pub struct InherentImpls<'db> { + #[update(bounds(SolverDefId<'db>: Update), unsafe(with(update_fallback_db::<'db, _>)))] + map: FxHashMap<SimplifiedType<'db>, Box<[ImplId]>>, } #[salsa::tracked] -impl<'db> InherentImpls { +impl<'db> InherentImpls<'db> { #[salsa::tracked(returns(ref))] - pub fn for_crate(db: &'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); @@ -573,7 +575,10 @@ impl<'db> InherentImpls { } #[salsa::tracked(returns(ref))] - pub fn for_block(db: &'db dyn HirDatabase, block: BlockIdLt<'db>) -> Option<Box<Self>> { + pub fn for_block( + db: &'db dyn HirDatabase, + block: BlockIdLt<'db>, + ) -> Option<Box<InherentImpls<'db>>> { let _p = tracing::info_span!("inherent_impls_in_block_query").entered(); let block_def_map = block_def_map(db, block); @@ -582,8 +587,8 @@ impl<'db> 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 @@ -593,10 +598,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<SimplifiedType, Vec<ImplId>>, + map: &mut FxHashMap<SimplifiedType<'db>, Vec<ImplId>>, ) { for (_module_id, module_data) in def_map.modules() { for impl_id in module_data.scope.inherent_impls() { @@ -622,15 +627,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>( + pub fn for_each_crate_and_block( db: &'db dyn HirDatabase, krate: Crate, block: Option<BlockIdLt<'db>>, - for_each: &mut dyn FnMut(&InherentImpls), + for_each: &mut dyn FnMut(&InherentImpls<'db>), ) { let blocks = std::iter::successors(block, |block| block.module(db).block(db)); blocks.filter_map(|block| Self::for_block(db, block).as_deref()).for_each(&mut *for_each); @@ -638,20 +643,21 @@ impl InherentImpls { } } -#[derive(Debug, PartialEq)] -struct OneTraitImpls { - non_blanket_impls: FxHashMap<SimplifiedType, (Box<[ImplId]>, Box<[BuiltinDeriveImplId]>)>, +#[derive(Debug, PartialEq, Update)] +struct OneTraitImpls<'db> { + #[update(bounds(SolverDefId<'db>: Update), unsafe(with(update_fallback_db::<'db, _>)))] + non_blanket_impls: FxHashMap<SimplifiedType<'db>, (Box<[ImplId]>, Box<[BuiltinDeriveImplId]>)>, blanket_impls: Box<[ImplId]>, } #[derive(Default)] -struct OneTraitImplsBuilder { - non_blanket_impls: FxHashMap<SimplifiedType, (Vec<ImplId>, Vec<BuiltinDeriveImplId>)>, +struct OneTraitImplsBuilder<'db> { + non_blanket_impls: FxHashMap<SimplifiedType<'db>, (Vec<ImplId>, Vec<BuiltinDeriveImplId>)>, blanket_impls: Vec<ImplId>, } -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() @@ -665,15 +671,15 @@ impl OneTraitImplsBuilder { } } -#[derive(Debug, PartialEq)] -pub struct TraitImpls { - map: FxHashMap<TraitId, OneTraitImpls>, +#[derive(Debug, PartialEq, Update)] +pub struct TraitImpls<'db> { + map: FxHashMap<TraitId, OneTraitImpls<'db>>, } #[salsa::tracked] -impl<'db> TraitImpls { +impl<'db> TraitImpls<'db> { #[salsa::tracked(returns(ref))] - pub fn for_crate(db: &'db dyn HirDatabase, krate: Crate) -> Arc<Self> { + pub fn for_crate(db: &'db dyn HirDatabase, krate: Crate) -> Arc<TraitImpls<'db>> { let _p = tracing::info_span!("inherent_impls_in_crate_query", ?krate).entered(); let crate_def_map = crate_def_map(db, krate); @@ -682,7 +688,10 @@ impl<'db> TraitImpls { } #[salsa::tracked(returns(as_deref))] - pub fn for_block(db: &'db dyn HirDatabase, block: BlockIdLt<'db>) -> Option<Box<Self>> { + pub fn for_block( + db: &'db dyn HirDatabase, + block: BlockIdLt<'db>, + ) -> Option<Box<TraitImpls<'db>>> { let _p = tracing::info_span!("inherent_impls_in_block_query").entered(); let block_def_map = block_def_map(db, block); @@ -696,8 +705,8 @@ impl<'db> 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); @@ -708,11 +717,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<TraitId, OneTraitImplsBuilder>, + map: &mut FxHashMap<TraitId, OneTraitImplsBuilder<'db>>, ) { for (_module_id, module_data) in def_map.modules() { for impl_id in module_data.scope.trait_impls() { @@ -779,7 +788,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) @@ -788,10 +797,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)) @@ -815,7 +824,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() { @@ -826,11 +835,11 @@ impl TraitImpls { } } - pub fn for_each_crate_and_block<'db>( + pub fn for_each_crate_and_block( db: &'db dyn HirDatabase, krate: Crate, block: Option<BlockIdLt<'db>>, - for_each: &mut dyn FnMut(&TraitImpls), + for_each: &mut dyn FnMut(&TraitImpls<'db>), ) { let blocks = std::iter::successors(block, |block| block.module(db).block(db)); blocks.filter_map(|block| Self::for_block(db, block)).for_each(&mut *for_each); @@ -838,12 +847,12 @@ 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>( + pub fn for_each_crate_and_block_trait_and_type( db: &'db dyn HirDatabase, krate: Crate, type_block: Option<BlockIdLt<'db>>, trait_block: Option<BlockIdLt<'db>>, - 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 d960a6547d..6d948464b1 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<R, F>(&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 3be9afdf45..0a47e031b7 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 2fa3f5e797..976f88601e 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<BasicBlock>, pub locals: Arena<Local>, pub start_block: BasicBlockId, - pub owner: InferBodyId, + pub owner: InferBodyId<'db>, pub binding_locals: ArenaMap<BindingId, LocalId>, pub upvar_locals: FxHashMap<BindingId, Vec<(LocalId, crate::closure_analysis::Place)>>, pub param_locals: Vec<LocalId>, /// This field stores the closures directly owned by this body. It is used /// in traversing every mir body. - pub closures: Vec<InternedClosureId>, + pub closures: Vec<InternedClosureId<'db>>, } -impl MirBody { +impl MirBody<'_> { pub fn local_to_binding_map(&self) -> ArenaMap<LocalId, BindingId> { 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 a9271675a0..c568209541 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<MirSpan>, } -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct BorrowckResult { - owner: Either<InferBodyId, InternedClosureId>, +#[derive(Debug, Clone, PartialEq, Eq, Update)] +pub struct BorrowckResult<'db> { + owner: Either<InferBodyId<'db>, InternedClosureId<'db>>, pub mutability_of_locals: ArenaMap<LocalId, MutabilityReason>, pub moved_out_of_ref: Vec<MovedOutOfRef>, pub partially_moved: Vec<PartiallyMoved>, pub borrow_regions: Vec<BorrowRegion>, } -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<InferBodyId, InternedClosureId>) -> BorrowckResult, + def: InferBodyId<'db>, + mut cb: impl FnMut( + &'db MirBody<'db>, + Either<InferBodyId<'db>, 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<Box<[BorrowckResult]>, MirLowerError> { +) -> Result<Box<[BorrowckResult<'db>]>, 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<InferBodyId, InternedClosureId>) -> BorrowckResult, + c: InternedClosureId<'db>, + results: &mut Vec<(BorrowckResult<'db>, &'db MirBody<'db>)>, + cb: &mut impl FnMut( + &'db MirBody<'db>, + Either<InferBodyId<'db>, 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); @@ -133,15 +143,18 @@ fn all_mir_bodies<'db>( } } -impl InferBodyId { - pub fn borrowck(self, db: &dyn HirDatabase) -> Result<&[BorrowckResult], MirLowerError> { +impl<'db> InferBodyId<'db> { + pub fn borrowck( + self, + db: &'db dyn HirDatabase, + ) -> Result<&'db [BorrowckResult<'db>], MirLowerError<'db>> { return borrowck_query(db, self).map_err(|e| e.clone()); #[salsa::tracked(returns(as_deref), lru = 2024)] - fn borrowck_query( - db: &dyn HirDatabase, - def: InferBodyId, - ) -> Result<Box<[BorrowckResult]>, MirLowerError> { + fn borrowck_query<'db>( + db: &'db dyn HirDatabase, + def: InferBodyId<'db>, + ) -> Result<Box<[BorrowckResult<'db>]>, MirLowerError<'db>> { let _p = tracing::info_span!("InferBodyId::borrowck").entered(); let module = def.module(db); let interner = DbInterner::new_with(db, module.krate(db)); @@ -198,7 +211,7 @@ impl InferBodyId { fn moved_out_of_ref<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, ) -> Vec<MovedOutOfRef> { let db = infcx.interner.db; let mut result = vec![]; @@ -293,7 +306,7 @@ fn moved_out_of_ref<'db>( fn partially_moved<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, ) -> Vec<PartiallyMoved> { let db = infcx.interner.db; let mut result = vec![]; @@ -375,7 +388,7 @@ fn partially_moved<'db>( result } -fn borrow_regions(db: &dyn HirDatabase, body: &MirBody) -> Vec<BorrowRegion> { +fn borrow_regions<'db>(db: &'db dyn HirDatabase, body: &MirBody<'db>) -> Vec<BorrowRegion> { let mut borrows = FxHashMap::default(); for (_, block) in body.basic_blocks.iter() { db.unwind_if_revision_cancelled(); @@ -428,7 +441,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; @@ -455,13 +468,13 @@ fn place_case<'db>( /// `Uninit` and `drop` and similar after initialization. fn ever_initialized_map( db: &dyn HirDatabase, - body: &MirBody, + body: &MirBody<'_>, ) -> ArenaMap<BasicBlockId, ArenaMap<LocalId, bool>> { let mut result: ArenaMap<BasicBlockId, ArenaMap<LocalId, bool>> = 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<BasicBlockId>, result: &mut ArenaMap<BasicBlockId, ArenaMap<LocalId, bool>>, @@ -574,7 +587,7 @@ fn record_usage_for_operand(arg: &Operand, result: &mut ArenaMap<LocalId, Mutabi fn mutability_of_locals<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, - body: &MirBody, + body: &MirBody<'db>, ) -> ArenaMap<LocalId, MutabilityReason> { let db = infcx.interner.db; let mut result: ArenaMap<LocalId, MutabilityReason> = diff --git a/crates/hir-ty/src/mir/eval.rs b/crates/hir-ty/src/mir/eval.rs index b968f33e81..ab60e81646 100644 --- a/crates/hir-ty/src/mir/eval.rs +++ b/crates/hir-ty/src/mir/eval.rs @@ -2,7 +2,7 @@ use std::{borrow::Cow, cell::RefCell, fmt::Write, iter, mem, ops::Range}; -use base_db::{Crate, target::TargetLoadError}; +use base_db::{Crate, salsa::update_fallback_db, target::TargetLoadError}; use either::Either; use hir_def::{ AdtId, DefWithBodyId, EnumVariantId, FunctionId, HasModule, ItemContainerId, Lookup, StaticId, @@ -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<BasicBlockId>, 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<u8>, heap: Vec<u8>, - code_stack: Vec<StackFrame<'a>>, + code_stack: Vec<StackFrame<'a, 'db>>, /// 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<StaticId, Address>, @@ -189,11 +190,11 @@ pub struct Evaluator<'a, 'db> { layout_cache: RefCell<FxHashMap<Ty<'db>, Arc<Layout>>>, projected_ty_cache: RefCell<FxHashMap<(PlaceTy<'db>, PlaceElem), PlaceTy<'db>>>, not_special_fn_cache: RefCell<FxHashSet<FunctionId>>, - mir_or_dyn_index_cache: RefCell<FxHashMap<(FunctionId, GenericArgs<'db>), MirOrDynIndex<'a>>>, + mir_or_dyn_index_cache: RefCell<FxHashMap<(FunctionId, GenericArgs<'db>), 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<FxHashMap<InferBodyId, Vec<Locals<'a>>>>, + unused_locals_store: RefCell<FxHashMap<InferBodyId<'db>, Vec<Locals<'a, 'db>>>>, cached_ptr_size: usize, cached_fn_trait_func: Option<FunctionId>, cached_fn_mut_trait_func: Option<FunctionId>, @@ -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<Interval> 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<ConstEvalError>), +#[derive(Clone, PartialEq, Eq, Update)] +pub enum MirEvalError<'db> { + ConstEvalError(String, Box<ConstEvalError<'db>>), 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<MirEvalError>, - Vec<(Either<FunctionId, InternedClosureId>, MirSpan, InferBodyId)>, + Box<MirEvalError<'db>>, + #[update(bounds(InternedClosureId<'db>: Update), unsafe(with(update_fallback_db::<'db, _>)))] + Vec<(Either<FunctionId, InternedClosureId<'db>>, MirSpan, InferBodyId<'db>)>, ), ExecutionLimitExceeded, StackOverflow, @@ -383,7 +379,7 @@ pub enum MirEvalError { InternalError(Box<str>), } -impl MirEvalError { +impl MirEvalError<'_> { pub fn pretty_print( &self, f: &mut String, @@ -420,18 +416,18 @@ impl MirEvalError { (store, None) } }; - let span: InFile<SyntaxNodePtr> = match span { - MirSpan::ExprId(e) => match source_map.expr_syntax(*e) { + let span: InFile<SyntaxNodePtr> = 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<T, MirEvalError>; +type Result<'db, T> = std::result::Result<T, MirEvalError<'db>>; #[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<LocalId, Interval>, - 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<ParamEnvAndCrate<'db>>, ) -> 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, @@ -738,7 +734,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { self.cached_ptr_size } - fn caller_location_fields(&self, owner: InferBodyId, span: MirSpan) -> (String, u32, u32) { + fn caller_location_fields(&self, owner: InferBodyId<'db>, span: MirSpan) -> (String, u32, u32) { let Some((file_id, text_range)) = self.resolve_mir_span(owner, span) else { return (String::new(), 0, 0); }; @@ -749,7 +745,11 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { (path.unwrap_or_default(), line + 1, col + 1) } - fn resolve_mir_span(&self, owner: InferBodyId, span: MirSpan) -> Option<(FileId, TextRange)> { + fn resolve_mir_span( + &self, + owner: InferBodyId<'db>, + span: MirSpan, + ) -> Option<(FileId, TextRange)> { let (source_map, self_param_syntax) = match owner { InferBodyId::DefWithBodyId(def) => { let body = &Body::with_source_map(self.db, def).1; @@ -788,7 +788,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<IntervalOrOwned>)> { let mut addr = locals.ptr[p.local].addr; let mut ty = PlaceTy::from_ty(locals.body.locals[p.local].ty.as_ref()); @@ -909,11 +909,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(), @@ -934,7 +934,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)?, @@ -944,7 +944,7 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn interpret_mir( &mut self, - body: &'a MirBody, + body: &'db MirBody<'db>, args: impl Iterator<Item = IntervalOrOwned>, ) -> Result<'db, Interval> { if let Some(it) = self.stack_depth_limit.checked_sub(1) { @@ -1106,8 +1106,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<Item = IntervalOrOwned>, ) -> Result<'db, ()> { let mut remain_args = body.param_locals.len(); @@ -1130,9 +1130,9 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { fn create_locals_for_body( &mut self, - body: &'a MirBody, + body: &'db MirBody<'db>, destination: Option<Interval>, - ) -> 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() }, @@ -1175,7 +1175,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)?), @@ -1840,7 +1844,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<Layout>, Option<(usize, usize, i128)>)> { let adt = it.adt_id(self.db); if let Some(f) = locals.body.owner.as_variant() @@ -1933,7 +1937,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()); @@ -2096,7 +2104,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() { @@ -2138,7 +2146,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; @@ -2177,7 +2185,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, @@ -2280,7 +2288,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 @@ -2310,7 +2318,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)? { @@ -2324,7 +2332,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)? { @@ -2365,13 +2373,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, ()> { @@ -2546,7 +2554,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)?; @@ -2678,10 +2686,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<BasicBlockId>, span: MirSpan, - ) -> Result<'db, Option<StackFrame<'a>>> { + ) -> Result<'db, Option<StackFrame<'a, 'db>>> { let id = from_bytes!(usize, bytes.get(self)?); let next_ty = self.vtable_map.ty(id)?; use rustc_type_ir::TyKind; @@ -2704,14 +2712,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<StackFrame<'a>>> { + ) -> Result<'db, Option<StackFrame<'a, 'db>>> { let mir_body = self .db .monomorphized_mir_body_for_closure( @@ -2747,10 +2755,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<BasicBlockId>, span: MirSpan, - ) -> Result<'db, Option<StackFrame<'a>>> { + ) -> Result<'db, Option<StackFrame<'a, 'db>>> { match def { CallableDefId::FunctionId(def) => { if self.detect_fn_trait(def).is_some() { @@ -2805,9 +2813,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()); @@ -2847,11 +2855,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<BasicBlockId>, span: MirSpan, - ) -> Result<'db, Option<StackFrame<'a>>> { + ) -> Result<'db, Option<StackFrame<'a, 'db>>> { if self.detect_and_exec_special_function( def, args, @@ -2913,20 +2921,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<Item = IntervalOrOwned>, span: MirSpan, destination: Interval, target_bb: Option<BasicBlockId>, - ) -> Result<'db, Option<StackFrame<'a>>> { - Ok(if let Some(target_bb) = target_bb { + ) -> Result<'db, Option<StackFrame<'a, 'db>>> { + 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( @@ -2935,8 +2943,8 @@ impl<'a, 'db: 'a> Evaluator<'a, 'db> { ) })?; destination.write_from_interval(self, result)?; - None - }) + Ok(None) + } } fn exec_fn_trait( @@ -2944,11 +2952,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<BasicBlockId>, span: MirSpan, - ) -> Result<'db, Option<StackFrame<'a>>> { + ) -> Result<'db, Option<StackFrame<'a, 'db>>> { let func = args .first() .ok_or_else(|| MirEvalError::InternalError("fn trait with no arg".into()))?; @@ -3013,7 +3021,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); }; @@ -3063,7 +3071,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)?; @@ -3080,7 +3088,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, @@ -3199,7 +3207,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 d2a74f20a5..9db6b36588 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<Layout>, 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<u8>> { 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> { @@ -1425,7 +1425,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), @@ -1485,7 +1485,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 a9d0bee623..ff16ea6870 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 622519445c..68d19769d4 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 8cc59ecd0c..b105cc7ba2 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<LoopBlocks>, labeled_loop_blocks: FxHashMap<LabelId, LoopBlocks>, discr_temp: Option<Place>, 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<DropScope>, @@ -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<str>, Box<ConstEvalError>), +#[derive(Debug, Clone, PartialEq, Eq, Update)] +pub enum MirLowerError<'db> { + ConstEvalError(Box<str>, Box<ConstEvalError<'db>>), 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<LayoutError> for MirLowerError { +impl From<LayoutError> 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<T, MirLowerError>; +type Result<'db, T> = std::result::Result<T, MirLowerError<'db>>; 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 { @@ -1525,7 +1526,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>, @@ -1539,7 +1540,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(), @@ -2126,8 +2127,8 @@ fn cast_kind<'db>( #[salsa_macros::tracked(returns(as_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); @@ -2283,7 +2284,10 @@ pub fn mir_body_for_closure_query<'db>( } #[salsa_macros::tracked(returns(as_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 { @@ -2326,16 +2330,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) } @@ -2343,13 +2347,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<BindingId>, params: &[Param<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 = { @@ -2383,13 +2387,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<Item = (PatId, Ty<'db>)> + 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 bcc86ba4bf..042dd076be 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<DbInterner<'db>> 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(as_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<MirBody, MirLowerError> { - let mut filler = Filler::new(db, trait_env.as_ref(), subst.as_ref()); +) -> Result<MirBody<'db>, 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<MirBody, MirLowerError> { +) -> Result<MirBody<'db>, MirLowerError<'db>> { Err(MirLowerError::Loop) } #[salsa_macros::tracked(returns(as_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<MirBody, MirLowerError> { - let mut filler = Filler::new(db, trait_env.as_ref(), subst.as_ref()); +) -> Result<MirBody<'db>, 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<MirBody, MirLowerError> { +) -> Result<MirBody<'db>, MirLowerError<'db>> { Err(MirLowerError::Loop) } diff --git a/crates/hir-ty/src/mir/pretty.rs b/crates/hir-ty/src/mir/pretty.rs index 3e41454424..8893069f0c 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 f0d33ad2dd..42fd31f259 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<DefaultAny<'static>> = 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 95f437165d..9585cced6b 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>(T); impl<T> StoredEarlyBinder<T> { @@ -102,7 +103,7 @@ impl StoredPolyFnSig { } } -#[derive(Debug, Clone, PartialEq, Eq, Hash, TypeVisitable, TypeFoldable)] +#[derive(Debug, Clone, PartialEq, Eq, Hash, TypeVisitable, TypeFoldable, Update)] pub struct StoredTraitRef { #[type_visitable(ignore)] def_id: TraitId, diff --git a/crates/hir-ty/src/next_solver/def_id.rs b/crates/hir-ty/src/next_solver/def_id.rs index ce66dbc77c..09b999ae5f 100644 --- a/crates/hir-ty/src/next_solver/def_id.rs +++ b/crates/hir-ty/src/next_solver/def_id.rs @@ -10,6 +10,7 @@ use hir_def::{ }, }; use rustc_type_ir::inherent; +use salsa::Update; use stdx::impl_from; use crate::{ @@ -28,26 +29,26 @@ pub enum Ctor { Enum(EnumVariantId), } -#[derive(PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash)] -pub enum SolverDefId { +#[derive(PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, Update)] +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 +122,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<GenericDefId> for SolverDefId { +impl<'db> From<AdtId> for SolverDefId<'db> { + fn from(it: AdtId) -> SolverDefId<'db> { + SolverDefId::AdtId(it) + } +} +impl<'db> From<StructId> for SolverDefId<'db> { + fn from(it: StructId) -> SolverDefId<'db> { + SolverDefId::AdtId(AdtId::StructId(it)) + } +} +impl<'db> From<EnumId> for SolverDefId<'db> { + fn from(it: EnumId) -> SolverDefId<'db> { + SolverDefId::AdtId(AdtId::EnumId(it)) + } +} +impl<'db> From<UnionId> for SolverDefId<'db> { + fn from(it: UnionId) -> SolverDefId<'db> { + SolverDefId::AdtId(AdtId::UnionId(it)) + } +} +impl<'db> From<ConstId> for SolverDefId<'db> { + fn from(it: ConstId) -> SolverDefId<'db> { + SolverDefId::ConstId(it) + } +} +impl<'db> From<FunctionId> for SolverDefId<'db> { + fn from(it: FunctionId) -> SolverDefId<'db> { + SolverDefId::FunctionId(it) + } +} +impl<'db> From<ImplId> for SolverDefId<'db> { + fn from(it: ImplId) -> SolverDefId<'db> { + SolverDefId::ImplId(it) + } +} +impl<'db> From<BuiltinDeriveImplId> for SolverDefId<'db> { + fn from(it: BuiltinDeriveImplId) -> SolverDefId<'db> { + SolverDefId::BuiltinDeriveImplId(it) + } +} +impl<'db> From<StaticId> for SolverDefId<'db> { + fn from(it: StaticId) -> SolverDefId<'db> { + SolverDefId::StaticId(it) + } +} +impl<'db> From<AnonConstId<'db>> for SolverDefId<'db> { + fn from(it: AnonConstId<'db>) -> SolverDefId<'db> { + SolverDefId::AnonConstId(it) + } +} +impl<'db> From<TraitId> for SolverDefId<'db> { + fn from(it: TraitId) -> SolverDefId<'db> { + SolverDefId::TraitId(it) + } +} +impl<'db> From<TypeAliasId> for SolverDefId<'db> { + fn from(it: TypeAliasId) -> SolverDefId<'db> { + SolverDefId::TypeAliasId(it) + } +} +impl<'db> From<InternedClosureId<'db>> for SolverDefId<'db> { + fn from(it: InternedClosureId<'db>) -> SolverDefId<'db> { + SolverDefId::InternedClosureId(it) + } +} +impl<'db> From<InternedCoroutineId<'db>> for SolverDefId<'db> { + fn from(it: InternedCoroutineId<'db>) -> SolverDefId<'db> { + SolverDefId::InternedCoroutineId(it) + } +} +impl<'db> From<InternedCoroutineClosureId<'db>> for SolverDefId<'db> { + fn from(it: InternedCoroutineClosureId<'db>) -> SolverDefId<'db> { + SolverDefId::InternedCoroutineClosureId(it) + } +} +impl<'db> From<InternedOpaqueTyId> for SolverDefId<'db> { + fn from(it: InternedOpaqueTyId) -> SolverDefId<'db> { + SolverDefId::InternedOpaqueTyId(it) + } +} +impl<'db> From<EnumVariantId> for SolverDefId<'db> { + fn from(it: EnumVariantId) -> SolverDefId<'db> { + SolverDefId::EnumVariantId(it) + } +} +impl<'db> From<Ctor> for SolverDefId<'db> { + fn from(it: Ctor) -> SolverDefId<'db> { + SolverDefId::Ctor(it) + } +} + +impl<'db> From<GenericDefId> for SolverDefId<'db> { fn from(value: GenericDefId) -> Self { match value { GenericDefId::AdtId(adt_id) => SolverDefId::AdtId(adt_id), @@ -154,9 +227,9 @@ impl From<GenericDefId> for SolverDefId { } } -impl From<GeneralConstId> for SolverDefId { +impl<'db> From<GeneralConstId<'db>> 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 +238,7 @@ impl From<GeneralConstId> for SolverDefId { } } -impl From<CallableDefId> for SolverDefId { +impl<'db> From<CallableDefId> for SolverDefId<'db> { #[inline] fn from(value: CallableDefId) -> Self { match value { @@ -176,7 +249,7 @@ impl From<CallableDefId> for SolverDefId { } } -impl From<DefWithBodyId> for SolverDefId { +impl<'db> From<DefWithBodyId> for SolverDefId<'db> { #[inline] fn from(value: DefWithBodyId) -> Self { match value { @@ -188,9 +261,9 @@ impl From<DefWithBodyId> for SolverDefId { } } -impl From<InferBodyId> for SolverDefId { +impl<'db> From<InferBodyId<'db>> 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(), @@ -198,7 +271,7 @@ impl From<InferBodyId> for SolverDefId { } } -impl From<VariantId> for SolverDefId { +impl<'db> From<VariantId> for SolverDefId<'db> { #[inline] fn from(value: VariantId) -> Self { match value { @@ -209,7 +282,7 @@ impl From<VariantId> for SolverDefId { } } -impl From<ExpressionStoreOwnerId> for SolverDefId { +impl<'db> From<ExpressionStoreOwnerId> for SolverDefId<'db> { #[inline] fn from(value: ExpressionStoreOwnerId) -> Self { match value { @@ -220,10 +293,10 @@ impl From<ExpressionStoreOwnerId> for SolverDefId { } } -impl TryFrom<SolverDefId> for AttrDefId { +impl TryFrom<SolverDefId<'_>> for AttrDefId { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { match value { SolverDefId::AdtId(it) => Ok(it.into()), SolverDefId::ConstId(it) => Ok(it.into()), @@ -245,11 +318,11 @@ impl TryFrom<SolverDefId> for AttrDefId { } } -impl TryFrom<SolverDefId> for DefWithBodyId { +impl TryFrom<SolverDefId<'_>> for DefWithBodyId { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { let id = match value { SolverDefId::ConstId(id) => id.into(), SolverDefId::FunctionId(id) => id.into(), @@ -271,11 +344,11 @@ impl TryFrom<SolverDefId> for DefWithBodyId { } } -impl TryFrom<SolverDefId> for InferBodyId { +impl<'db> TryFrom<SolverDefId<'db>> for InferBodyId<'db> { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'db>) -> Result<Self, Self::Error> { let id = match value { SolverDefId::ConstId(id) => id.into(), SolverDefId::FunctionId(id) => id.into(), @@ -297,10 +370,10 @@ impl TryFrom<SolverDefId> for InferBodyId { } } -impl TryFrom<SolverDefId> for GenericDefId { +impl TryFrom<SolverDefId<'_>> for GenericDefId { type Error = (); - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { Ok(match value { SolverDefId::AdtId(adt_id) => GenericDefId::AdtId(adt_id), SolverDefId::ConstId(const_id) => GenericDefId::ConstId(const_id), @@ -321,8 +394,8 @@ impl TryFrom<SolverDefId> for GenericDefId { } } -impl<'db> inherent::DefId<DbInterner<'db>> for SolverDefId { - fn as_local(self) -> Option<SolverDefId> { +impl<'db> inherent::DefId<DbInterner<'db>> for SolverDefId<'db> { + fn as_local(self) -> Option<SolverDefId<'db>> { Some(self) } fn is_local(self) -> bool { @@ -332,17 +405,17 @@ impl<'db> inherent::DefId<DbInterner<'db>> 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<SolverDefId> for $name { + impl TryFrom<SolverDefId<'_>> for $name { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { match value { SolverDefId::$wraps(it) => Ok(Self(it)), _ => Err(()), @@ -351,7 +424,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); @@ -375,9 +448,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() } } @@ -395,9 +468,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<ClosureIdWrapper<'db>> for InternedClosureId<'db> { + #[inline] + fn from(value: ClosureIdWrapper<'db>) -> InternedClosureId<'db> { + value.0 + } +} + +impl<'db> From<InternedClosureId<'db>> for ClosureIdWrapper<'db> { + #[inline] + fn from(value: InternedClosureId<'db>) -> ClosureIdWrapper<'db> { + Self(value) + } +} + +impl<'db> From<ClosureIdWrapper<'db>> for SolverDefId<'db> { + #[inline] + fn from(value: ClosureIdWrapper<'db>) -> SolverDefId<'db> { + value.0.into() + } +} + +impl<'db> TryFrom<SolverDefId<'db>> for ClosureIdWrapper<'db> { + type Error = (); + + #[inline] + fn try_from(value: SolverDefId<'db>) -> Result<Self, Self::Error> { + match value { + SolverDefId::InternedClosureId(it) => Ok(Self(it)), + _ => Err(()), + } + } +} + +impl<'db> inherent::DefId<DbInterner<'db>, SolverDefId<'db>> for ClosureIdWrapper<'db> { + fn as_local(self) -> Option<SolverDefId<'db>> { + 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<CoroutineIdWrapper<'db>> for InternedCoroutineId<'db> { + #[inline] + fn from(value: CoroutineIdWrapper<'db>) -> InternedCoroutineId<'db> { + value.0 + } +} + +impl<'db> From<InternedCoroutineId<'db>> for CoroutineIdWrapper<'db> { + #[inline] + fn from(value: InternedCoroutineId<'db>) -> CoroutineIdWrapper<'db> { + Self(value) + } +} + +impl<'db> From<CoroutineIdWrapper<'db>> for SolverDefId<'db> { + #[inline] + fn from(value: CoroutineIdWrapper<'db>) -> SolverDefId<'db> { + value.0.into() + } +} + +impl<'db> TryFrom<SolverDefId<'db>> for CoroutineIdWrapper<'db> { + type Error = (); + + #[inline] + fn try_from(value: SolverDefId<'db>) -> Result<Self, Self::Error> { + match value { + SolverDefId::InternedCoroutineId(it) => Ok(Self(it)), + _ => Err(()), + } + } +} + +impl<'db> inherent::DefId<DbInterner<'db>, SolverDefId<'db>> for CoroutineIdWrapper<'db> { + fn as_local(self) -> Option<SolverDefId<'db>> { + 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<CoroutineClosureIdWrapper<'db>> for InternedCoroutineClosureId<'db> { + #[inline] + fn from(value: CoroutineClosureIdWrapper<'db>) -> InternedCoroutineClosureId<'db> { + value.0 + } +} + +impl<'db> From<InternedCoroutineClosureId<'db>> for CoroutineClosureIdWrapper<'db> { + #[inline] + fn from(value: InternedCoroutineClosureId<'db>) -> CoroutineClosureIdWrapper<'db> { + Self(value) + } +} + +impl<'db> From<CoroutineClosureIdWrapper<'db>> for SolverDefId<'db> { + #[inline] + fn from(value: CoroutineClosureIdWrapper<'db>) -> SolverDefId<'db> { + value.0.into() + } +} + +impl<'db> TryFrom<SolverDefId<'db>> for CoroutineClosureIdWrapper<'db> { + type Error = (); + + #[inline] + fn try_from(value: SolverDefId<'db>) -> Result<Self, Self::Error> { + match value { + SolverDefId::InternedCoroutineClosureId(it) => Ok(Self(it)), + _ => Err(()), + } + } +} + +impl<'db> inherent::DefId<DbInterner<'db>, SolverDefId<'db>> for CoroutineClosureIdWrapper<'db> { + fn as_local(self) -> Option<SolverDefId<'db>> { + Some(self.into()) + } + fn is_local(self) -> bool { + true + } +} declare_id_wrapper!(AdtIdWrapper, AdtId); declare_id_wrapper!(OpaqueTyIdWrapper, InternedOpaqueTyId, OpaqueTyIdWrapper); @@ -405,13 +627,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<SolverDefId> for $term_id_name { + impl TryFrom<SolverDefId<'_>> for $term_id_name { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { match value { SolverDefId::TypeAliasId(it) => Ok(Self(TermId::TypeAliasId(it))), SolverDefId::ConstId(it) => Ok(Self(TermId::ConstId(it))), @@ -454,7 +676,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)) } @@ -474,7 +696,7 @@ pub enum TermId { } impl_from!(TypeAliasId, ConstId for TermId); -impl From<TermId> for SolverDefId { +impl<'db> From<TermId> for SolverDefId<'db> { fn from(value: TermId) -> Self { match value { TermId::TypeAliasId(id) => id.into(), @@ -484,28 +706,28 @@ impl From<TermId> 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<GeneralConstIdWrapper> for GeneralConstId { +impl<'db> From<GeneralConstIdWrapper<'db>> for GeneralConstId<'db> { #[inline] - fn from(value: GeneralConstIdWrapper) -> GeneralConstId { + fn from(value: GeneralConstIdWrapper<'db>) -> GeneralConstId<'db> { value.0 } } -impl From<GeneralConstId> for GeneralConstIdWrapper { +impl<'db> From<GeneralConstId<'db>> for GeneralConstIdWrapper<'db> { #[inline] - fn from(value: GeneralConstId) -> GeneralConstIdWrapper { + fn from(value: GeneralConstId<'db>) -> GeneralConstIdWrapper<'db> { Self(value) } } -impl From<GeneralConstIdWrapper> for SolverDefId { +impl<'db> From<GeneralConstIdWrapper<'db>> 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), @@ -513,10 +735,10 @@ impl From<GeneralConstIdWrapper> for SolverDefId { } } } -impl TryFrom<SolverDefId> for GeneralConstIdWrapper { +impl<'db> TryFrom<SolverDefId<'db>> for GeneralConstIdWrapper<'db> { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'db>) -> Result<Self, Self::Error> { match value { SolverDefId::ConstId(it) => Ok(Self(it.into())), SolverDefId::StaticId(it) => Ok(Self(it.into())), @@ -525,8 +747,8 @@ impl TryFrom<SolverDefId> for GeneralConstIdWrapper { } } } -impl<'db> inherent::DefId<DbInterner<'db>> for GeneralConstIdWrapper { - fn as_local(self) -> Option<SolverDefId> { +impl<'db> inherent::DefId<DbInterner<'db>> for GeneralConstIdWrapper<'db> { + fn as_local(self) -> Option<SolverDefId<'db>> { Some(self.into()) } fn is_local(self) -> bool { @@ -554,9 +776,9 @@ impl From<CallableDefId> for CallableIdWrapper { Self(value) } } -impl From<CallableIdWrapper> for SolverDefId { +impl<'db> From<CallableIdWrapper> 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(), @@ -564,10 +786,10 @@ impl From<CallableIdWrapper> for SolverDefId { } } } -impl TryFrom<SolverDefId> for CallableIdWrapper { +impl TryFrom<SolverDefId<'_>> for CallableIdWrapper { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { match value { SolverDefId::FunctionId(it) => Ok(Self(it.into())), SolverDefId::Ctor(Ctor::Struct(it)) => Ok(Self(it.into())), @@ -577,7 +799,7 @@ impl TryFrom<SolverDefId> for CallableIdWrapper { } } impl<'db> inherent::DefId<DbInterner<'db>> for CallableIdWrapper { - fn as_local(self) -> Option<SolverDefId> { + fn as_local(self) -> Option<SolverDefId<'db>> { Some(self.into()) } fn is_local(self) -> bool { @@ -593,19 +815,19 @@ pub enum AnyImplId { impl_from!(ImplId, BuiltinDeriveImplId for AnyImplId); -impl From<AnyImplId> for SolverDefId { +impl<'db> From<AnyImplId> 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<SolverDefId> for AnyImplId { +impl TryFrom<SolverDefId<'_>> for AnyImplId { type Error = (); #[inline] - fn try_from(value: SolverDefId) -> Result<Self, Self::Error> { + fn try_from(value: SolverDefId<'_>) -> Result<Self, Self::Error> { match value { SolverDefId::ImplId(it) => Ok(it.into()), SolverDefId::BuiltinDeriveImplId(it) => Ok(it.into()), @@ -614,7 +836,7 @@ impl TryFrom<SolverDefId> for AnyImplId { } } impl<'db> inherent::DefId<DbInterner<'db>> for AnyImplId { - fn as_local(self) -> Option<SolverDefId> { + fn as_local(self) -> Option<SolverDefId<'db>> { Some(self.into()) } fn is_local(self) -> bool { diff --git a/crates/hir-ty/src/next_solver/fold.rs b/crates/hir-ty/src/next_solver/fold.rs index 0a41874374..826f234bf6 100644 --- a/crates/hir-ty/src/next_solver/fold.rs +++ b/crates/hir-ty/src/next_solver/fold.rs @@ -225,7 +225,7 @@ impl<'db> DbInterner<'db> { /// free variants attached to `all_outlive_scope`. pub fn liberate_late_bound_regions<T>( self, - all_outlive_scope: SolverDefId, + all_outlive_scope: SolverDefId<'db>, value: Binder<'db, T>, ) -> T where diff --git a/crates/hir-ty/src/next_solver/fulfill.rs b/crates/hir-ty/src/next_solver/fulfill.rs index 33dd33cb1d..e422f75a02 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<Ty<'db>>, } diff --git a/crates/hir-ty/src/next_solver/generic_arg.rs b/crates/hir-ty/src/next_solver/generic_arg.rs index 4e5f3c8c49..22b34b379d 100644 --- a/crates/hir-ty/src/next_solver/generic_arg.rs +++ b/crates/hir-ty/src/next_solver/generic_arg.rs @@ -553,7 +553,7 @@ impl<'db> GenericArgs<'db> { /// replace defaults of generic parameters. pub fn for_item<F>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, mk_kind: F, ) -> GenericArgs<'db> where @@ -579,7 +579,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) }) @@ -606,7 +606,7 @@ impl<'db> GenericArgs<'db> { /// Like `for_item()`, but calls first uses the args from `first`. pub fn fill_rest<F>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, first: impl IntoIterator<Item = GenericArg<'db>>, 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 9ae9a66674..e0a69a6602 100644 --- a/crates/hir-ty/src/next_solver/generics.rs +++ b/crates/hir-ty/src/next_solver/generics.rs @@ -9,7 +9,7 @@ use crate::db::HirDatabase; use super::{Ctor, DbInterner, SolverDefId}; -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, consider_late_bound) = match (def.try_into(), def) { (Ok(def), _) => (def, false), diff --git a/crates/hir-ty/src/next_solver/infer/context.rs b/crates/hir-ty/src/next_solver/infer/context.rs index 1e2a3ff0c2..270bc73d5f 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 3fdf0480eb..7c419147d2 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) }) @@ -849,7 +849,7 @@ impl<'db> InferCtxt<'db> { pub fn fill_rest_fresh_args( &self, span: Span, - def_id: SolverDefId, + def_id: SolverDefId<'db>, first: impl IntoIterator<Item = GenericArg<'db>>, ) -> GenericArgs<'db> { GenericArgs::fill_rest(self.interner, def_id, first, |_index, kind, _| { @@ -903,7 +903,7 @@ impl<'db> InferCtxt<'db> { } #[inline(always)] - pub fn can_define_opaque_ty(&self, id: impl Into<SolverDefId>) -> bool { + pub fn can_define_opaque_ty(&self, id: impl Into<SolverDefId<'db>>) -> bool { match self.typing_mode_raw().assert_not_erased() { TypingMode::Analysis { defining_opaque_types_and_generators } => { defining_opaque_types_and_generators.contains(&id.into()) @@ -1102,7 +1102,7 @@ impl<'db> InferCtxt<'db> { pub fn instantiate_binder_with_fresh_vars<T>( &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 e55e43a4cd..3b957c9c72 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<DbInterner<'db>> 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 f3af697feb..f34afead74 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<DbInterner<'db>> 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 3e8fab9313..ab6ce31256 100644 --- a/crates/hir-ty/src/next_solver/interner.rs +++ b/crates/hir-ty/src/next_solver/interner.rs @@ -201,6 +201,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() }; @@ -212,7 +213,7 @@ macro_rules! impl_stored_interned_slice { unsafe impl salsa::Update for $stored_name { unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool { // SAFETY: Comparing by (pointer) equality is safe. - unsafe { crate::utils::unsafe_update_eq(old_pointer, new_value) } + unsafe { salsa::update_fallback(old_pointer, new_value) } } } @@ -285,7 +286,7 @@ macro_rules! impl_stored_interned { unsafe impl salsa::Update for $stored_name { unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool { - unsafe { crate::utils::unsafe_update_eq(old_pointer, new_value) } + unsafe { salsa::update_fallback(old_pointer, new_value) } } } @@ -378,7 +379,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) } @@ -878,18 +879,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; @@ -1105,7 +1106,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() } @@ -1608,7 +1609,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), @@ -1973,14 +1974,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<SolverDefId>, + struct CoroutinesVisitor<'a, 'db> { + db: &'db dyn HirDatabase, + owner: InferBodyId<'db>, + store: &'db ExpressionStore, + coroutines: &'a mut Vec<SolverDefId<'db>>, } - 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: @@ -2266,7 +2267,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) => { @@ -2321,13 +2325,13 @@ macro_rules! TrivialTypeTraversalImpls { } TrivialTypeTraversalImpls! { - SolverDefId, + SolverDefId<'_>, TraitIdWrapper, TypeAliasIdWrapper, CallableIdWrapper, - ClosureIdWrapper, - CoroutineIdWrapper, - CoroutineClosureIdWrapper, + ClosureIdWrapper<'_>, + CoroutineIdWrapper<'_>, + CoroutineClosureIdWrapper<'_>, AdtIdWrapper, TraitAssocTyId, TraitAssocConstId, @@ -2343,7 +2347,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 bdb3f30871..dd5f729795 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 dc753a1b47..a6facff762 100644 --- a/crates/hir-ty/src/next_solver/region.rs +++ b/crates/hir-ty/src/next_solver/region.rs @@ -77,7 +77,7 @@ impl<'db> Region<'db> { pub fn new_late_param( interner: DbInterner<'db>, - scope: SolverDefId, + scope: SolverDefId<'db>, bound_region: BoundRegion<'db>, ) -> Region<'db> { let late_bound_region = LateParamRegion { scope, bound_region }; @@ -169,7 +169,7 @@ pub struct EarlyParamRegion { /// This denotes some region at least as big as `scope`. It is similar to a placeholder region /// created when entering a binder, except it always lives in the root universe. pub struct LateParamRegion<'db> { - pub scope: SolverDefId, + pub scope: SolverDefId<'db>, pub bound_region: BoundRegion<'db>, } diff --git a/crates/hir-ty/src/next_solver/ty.rs b/crates/hir-ty/src/next_solver/ty.rs index d57d824e32..397db9375b 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<SolverDefId>; +pub type SimplifiedType<'db> = rustc_type_ir::fast_reject::SimplifiedType<SolverDefId<'db>>; pub type TyKind<'db> = rustc_type_ir::TyKind<DbInterner<'db>>; pub type FnHeader<'db> = rustc_type_ir::FnHeader<DbInterner<'db>>; pub type AliasTyKind<'db> = rustc_type_ir::AliasTyKind<DbInterner<'db>>; @@ -1186,7 +1186,7 @@ impl<'db> rustc_type_ir::inherent::Ty<DbInterner<'db>> for Ty<'db> { fn new_coroutine( interner: DbInterner<'db>, - def_id: CoroutineIdWrapper, + def_id: CoroutineIdWrapper<'db>, args: <DbInterner<'db> as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::Coroutine(def_id, args)) @@ -1194,7 +1194,7 @@ impl<'db> rustc_type_ir::inherent::Ty<DbInterner<'db>> for Ty<'db> { fn new_coroutine_closure( interner: DbInterner<'db>, - def_id: CoroutineClosureIdWrapper, + def_id: CoroutineClosureIdWrapper<'db>, args: <DbInterner<'db> as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::CoroutineClosure(def_id, args)) @@ -1202,7 +1202,7 @@ impl<'db> rustc_type_ir::inherent::Ty<DbInterner<'db>> for Ty<'db> { fn new_closure( interner: DbInterner<'db>, - def_id: ClosureIdWrapper, + def_id: ClosureIdWrapper<'db>, args: <DbInterner<'db> as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::Closure(def_id, args)) @@ -1210,7 +1210,7 @@ impl<'db> rustc_type_ir::inherent::Ty<DbInterner<'db>> for Ty<'db> { fn new_coroutine_witness( interner: DbInterner<'db>, - def_id: CoroutineIdWrapper, + def_id: CoroutineIdWrapper<'db>, args: <DbInterner<'db> as Interner>::GenericArgs, ) -> Self { Ty::new(interner, TyKind::CoroutineWitness(def_id, args)) @@ -1218,7 +1218,7 @@ impl<'db> rustc_type_ir::inherent::Ty<DbInterner<'db>> for Ty<'db> { fn new_coroutine_witness_for_coroutine( interner: DbInterner<'db>, - def_id: CoroutineIdWrapper, + def_id: CoroutineIdWrapper<'db>, coroutine_args: <DbInterner<'db> 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 fb3bd18bf4..7e40e3c17d 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<DbInterner<'db>>>( pub fn explicit_item_bounds<'db>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, ) -> EarlyBinder<'db, impl DoubleEndedIterator<Item = Clause<'db>> + 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<Item = Clause<'db>> + 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 dfd1fd96c6..1d7cd1b05d 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<SolverDefId>, + def_id: InferBodyId<'_>, + result: &mut Vec<SolverDefId<'_>>, ) { 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<Box<StoredEarlyBinder<ImplTraits>>>, mut make_impl_trait: impl FnMut(ImplTraitIdx) -> ImplTraitId, - result: &mut Vec<SolverDefId>, + result: &mut Vec<SolverDefId<'_>>, ) { 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 febd2a833a..5aed9227c0 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/tests/incremental.rs b/crates/hir-ty/src/tests/incremental.rs index 3432d47b2f..08efef10ee 100644 --- a/crates/hir-ty/src/tests/incremental.rs +++ b/crates/hir-ty/src/tests/incremental.rs @@ -28,16 +28,16 @@ fn foo() -> i32 { } }); }, - &[("InferenceResult::for_body_", 1)], + &[("InferenceResult < 'db >::for_body_", 1)], expect_test::expect![[r#" [ "source_root_crates", "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "FunctionSignature::of_", "FunctionSignature::with_source_map_", "AttrFlags::query_", @@ -74,10 +74,10 @@ fn foo() -> i32 { } }); }, - &[("InferenceResult::for_body_", 0)], + &[("InferenceResult < 'db >::for_body_", 0)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -117,16 +117,16 @@ fn baz() -> i32 { } }); }, - &[("InferenceResult::for_body_", 3)], + &[("InferenceResult < 'db >::for_body_", 3)], expect_test::expect![[r#" [ "source_root_crates", "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "FunctionSignature::of_", "FunctionSignature::with_source_map_", "AttrFlags::query_", @@ -139,7 +139,7 @@ fn baz() -> i32 { "ImplTraits::return_type_impl_traits_", "ExprScopes::body_expr_scopes_", "body_upvars_mentioned", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "FunctionSignature::of_", "FunctionSignature::with_source_map_", "AttrFlags::query_", @@ -150,7 +150,7 @@ fn baz() -> i32 { "ImplTraits::return_type_impl_traits_", "ExprScopes::body_expr_scopes_", "body_upvars_mentioned", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "FunctionSignature::of_", "FunctionSignature::with_source_map_", "AttrFlags::query_", @@ -190,10 +190,10 @@ fn baz() -> i32 { } }); }, - &[("InferenceResult::for_body_", 1)], + &[("InferenceResult < 'db >::for_body_", 1)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -207,7 +207,7 @@ fn baz() -> i32 { "FunctionSignature::of_", "Body::with_source_map_", "Body::of_", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "ExprScopes::body_expr_scopes_", "body_upvars_mentioned", "AttrFlags::query_", @@ -241,16 +241,16 @@ $0", let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ "source_root_crates", "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "lang_items", "crate_lang_items", ] @@ -280,15 +280,15 @@ pub struct NewStruct { let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", "crate_local_def_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "crate_lang_items", ] "#]], @@ -316,16 +316,16 @@ $0", let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ "source_root_crates", "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "lang_items", "crate_lang_items", ] @@ -356,15 +356,15 @@ pub enum SomeEnum { let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", "crate_local_def_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "crate_lang_items", ] "#]], @@ -392,16 +392,16 @@ $0", let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ "source_root_crates", "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "lang_items", "crate_lang_items", ] @@ -429,15 +429,15 @@ fn bar() -> f32 { let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", "crate_local_def_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "crate_lang_items", ] "#]], @@ -469,16 +469,16 @@ $0", let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ "source_root_crates", "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "lang_items", "crate_lang_items", ] @@ -514,15 +514,15 @@ impl SomeStruct { let _crate_def_map = module.def_map(&db); TraitImpls::for_crate(&db, module.krate(&db)); }, - &[("TraitImpls::for_crate_", 1)], + &[("TraitImpls < 'db >::for_crate_", 1)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", "crate_local_def_map", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "crate_lang_items", ] "#]], @@ -570,6 +570,7 @@ fn main() { let _inference_result = InferenceResult::of(&db, def); } }, + // FIXME: What does this test check for now? trait_solve_shim is no longer a query &[("trait_solve_shim", 0)], expect_test::expect![[r#" [ @@ -577,14 +578,14 @@ fn main() { "crate_local_def_map", "file_item_tree_query", "HirFileId::ast_id_map_", - "parse", + "EditionedFileId::parse_", "real_span_map", "TraitItems::query_with_diagnostics_", "Body::of_", "Body::with_source_map_", "AttrFlags::query_", "ImplItems::of_", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "TraitSignature::of_", "TraitSignature::with_source_map_", "AttrFlags::query_", @@ -600,7 +601,7 @@ fn main() { "GenericPredicates::query_with_diagnostics_", "ImplTraits::return_type_impl_traits_", "body_upvars_mentioned", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "FunctionSignature::of_", "FunctionSignature::with_source_map_", "trait_environment_query", @@ -611,10 +612,10 @@ fn main() { "StructSignature::with_source_map_", "AttrFlags::query_", "GenericPredicates::query_with_diagnostics_", - "InherentImpls::for_crate_", + "InherentImpls < 'db >::for_crate_", "callable_item_signature_with_diagnostics", - "TraitImpls::for_crate_and_deps_", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_and_deps_", + "TraitImpls < 'db >::for_crate_", "impl_trait_with_diagnostics", "ImplSignature::of_", "ImplSignature::with_source_map_", @@ -670,7 +671,7 @@ fn main() { &[("trait_solve_shim", 0)], expect_test::expect![[r#" [ - "parse", + "EditionedFileId::parse_", "HirFileId::ast_id_map_", "file_item_tree_query", "real_span_map", @@ -680,7 +681,7 @@ fn main() { "AttrFlags::query_", "Body::of_", "ImplItems::of_", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "AttrFlags::query_", "TraitSignature::with_source_map_", "AttrFlags::query_", @@ -693,7 +694,7 @@ fn main() { "GenericPredicates::query_with_diagnostics_", "ImplTraits::return_type_impl_traits_", "body_upvars_mentioned", - "InferenceResult::for_body_", + "InferenceResult < 'db >::for_body_", "FunctionSignature::with_source_map_", "GenericPredicates::query_with_diagnostics_", "ImplTraits::return_type_impl_traits_", @@ -701,9 +702,9 @@ fn main() { "StructSignature::with_source_map_", "AttrFlags::query_", "GenericPredicates::query_with_diagnostics_", - "InherentImpls::for_crate_", + "InherentImpls < 'db >::for_crate_", "callable_item_signature_with_diagnostics", - "TraitImpls::for_crate_", + "TraitImpls < 'db >::for_crate_", "ImplSignature::with_source_map_", "ImplSignature::of_", "impl_trait_with_diagnostics", diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index 935f541841..108e3e07a6 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 } } } @@ -175,7 +175,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-ty/src/utils.rs b/crates/hir-ty/src/utils.rs index 764d02ccf1..53d7231562 100644 --- a/crates/hir-ty/src/utils.rs +++ b/crates/hir-ty/src/utils.rs @@ -19,26 +19,6 @@ use crate::{ mir::pad16, }; -/// SAFETY: `old_pointer` must be valid for unique writes -pub(crate) unsafe fn unsafe_update_eq<T>(old_pointer: *mut T, new_value: T) -> bool -where - T: PartialEq, -{ - // SAFETY: Caller obligation - let old_ref: &mut T = unsafe { &mut *old_pointer }; - - if *old_ref != new_value { - *old_ref = new_value; - true - } else { - // Subtle but important: Eq impls can be buggy or define equality - // in surprising ways. If it says that the value has not changed, - // we do not modify the existing value, and thus do not have to - // update the revision, as downstream code will not see the new value. - false - } -} - pub(crate) fn fn_traits(lang_items: &LangItems) -> impl Iterator<Item = TraitId> + '_ { [lang_items.Fn, lang_items.FnMut, lang_items.FnOnce].into_iter().flatten() } diff --git a/crates/hir/Cargo.toml b/crates/hir/Cargo.toml index 8902144189..a9575a93db 100644 --- a/crates/hir/Cargo.toml +++ b/crates/hir/Cargo.toml @@ -22,6 +22,7 @@ smallvec.workspace = true tracing = { workspace = true, features = ["attributes"] } triomphe.workspace = true la-arena.workspace = true +salsa.workspace = true ra-ap-rustc_type_ir.workspace = true diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs index b921a5eef1..e2a9c46a83 100644 --- a/crates/hir/src/diagnostics.rs +++ b/crates/hir/src/diagnostics.rs @@ -137,7 +137,7 @@ diagnostics![AnyDiagnostic<'db> -> MovedOutOfRef<'db>, MutRefInImmRefPat, MutableRefBinding, - NeedMut, + NeedMut<'db>, NonExhaustiveLet, NonExhaustiveRecordExpr, NonExhaustiveRecordPat, @@ -168,8 +168,8 @@ diagnostics![AnyDiagnostic<'db> -> UnresolvedMethodCall<'db>, UnresolvedModule, UnresolvedIdent, - UnusedMut, - UnusedVariable, + UnusedMut<'db>, + UnusedVariable<'db>, GenericArgsProhibited, ParenthesizedGenericArgsWithoutFnTrait, BadRtn, @@ -474,19 +474,19 @@ pub struct TypeMismatch<'db> { } #[derive(Debug)] -pub struct NeedMut { - pub local: Local, +pub struct NeedMut<'db> { + pub local: Local<'db>, pub span: InFile<SyntaxNodePtr>, } #[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)] @@ -835,7 +835,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<AnyDiagnostic<'db>> { let expr_syntax = |expr| Self::expr_syntax(expr, source_map); let pat_syntax = |pat| Self::pat_syntax(pat, source_map); @@ -1148,7 +1148,7 @@ impl<'db> AnyDiagnostic<'db> { db: &'db dyn HirDatabase, d: &'db SolverDiagnosticKind, span: SpanSyntax, - type_owner: TypeOwnerId, + type_owner: TypeOwnerId<'db>, ) -> Option<AnyDiagnostic<'db>> { 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 06fa91804d..6f7615ed18 100644 --- a/crates/hir/src/display.rs +++ b/crates/hir/src/display.rs @@ -532,7 +532,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 219eb9c3b9..e94279bc45 100644 --- a/crates/hir/src/from_id.rs +++ b/crates/hir/src/from_id.rs @@ -254,7 +254,7 @@ impl TryFrom<AssocItem> 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 9248aaec02..3a6e19636a 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<ast::IdentPat, ast::SelfParam>; fn source(self, _: &dyn HirDatabase) -> Option<InFile<Self::Ast>> { diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 1ba73c180c..fd00480c0a 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -706,7 +706,7 @@ impl Module { self, db: &dyn HirDatabase, visible_from: Option<Module>, - ) -> 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<i128, ConstEvalError> { + pub fn eval(self, db: &dyn HirDatabase) -> Result<i128, ConstEvalError<'_>> { 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<EvaluatedConst<'_>, ConstEvalError> { + pub fn eval( + self, + db: &'db dyn HirDatabase, + ) -> Result<EvaluatedConst<'db>, 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!(); @@ -2383,7 +2386,7 @@ impl Function { (fn_ptr.owner, sig_tys.with(hdr)) } - fn erased_fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId, FnSig<'db>) { + fn erased_fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId<'db>, FnSig<'db>) { let (owner, sig) = self.fn_sig(db); let sig = DbInterner::new_no_crate(db).instantiate_bound_regions_with_erased(sig); (owner, sig) @@ -2646,7 +2649,7 @@ impl Function { self, db: &dyn HirDatabase, span_formatter: impl Fn(FileId, TextRange) -> String, - ) -> Result<String, ConstEvalError> { + ) -> Result<String, ConstEvalError<'_>> { let AnyFunctionId::FunctionId(id) = self.id else { return Err(ConstEvalError::MirEvalError(MirEvalError::NotSupported( "evaluation of builtin derive impl methods is not supported".to_owned(), @@ -2739,7 +2742,7 @@ impl<'db> Param<'db> { Some(self.as_local(db)?.name(db)) } - pub fn as_local(&self, db: &dyn HirDatabase) -> Option<Local> { + pub fn as_local(&self, db: &'db dyn HirDatabase) -> Option<Local<'db>> { match self.func { Callee::Def(CallableDefId::FunctionId(it)) => { let parent = DefWithBodyId::FunctionId(it); @@ -2926,7 +2929,7 @@ impl Const { } /// Evaluate the constant. - pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst<'_>, ConstEvalError> { + pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst<'_>, 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 { @@ -2944,7 +2947,7 @@ impl HasVisibility for Const { } pub struct EvaluatedConst<'db> { - def: InferBodyId, + def: InferBodyId<'db>, allocation: hir_ty::next_solver::Allocation<'db>, ty: Ty<'db>, } @@ -2954,7 +2957,7 @@ impl<'db> EvaluatedConst<'db> { format!("{}", self.allocation.display(db, display_target)) } - pub fn render_debug(&self, db: &'db dyn HirDatabase) -> Result<String, MirEvalError> { + pub fn render_debug(&self, db: &'db dyn HirDatabase) -> Result<String, MirEvalError<'db>> { let ty = self.allocation.ty.kind(); if let TyKind::Int(_) | TyKind::Uint(_) = ty { let b = &self.allocation.memory; @@ -3007,7 +3010,7 @@ impl Static { } /// Evaluate the static initializer. - pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst<'_>, ConstEvalError> { + pub fn eval(self, db: &dyn HirDatabase) -> Result<EvaluatedConst<'_>, 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, @@ -4011,17 +4014,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<Self> { + fn new_from_fn( + def: Function, + subst: GenericArgs<'db>, + owner: TypeOwnerId<'db>, + ) -> Option<Self> { match def.id { AnyFunctionId::FunctionId(def) => Some(Self::new(def.into(), subst, owner)), AnyFunctionId::BuiltinDeriveImplMethod { .. } => None, @@ -4082,18 +4089,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<Either<ast::IdentPat, ast::SelfParam>>, } -impl LocalSource { +impl<'db> LocalSource<'db> { pub fn as_ident_pat(&self) -> Option<&ast::IdentPat> { match &self.source.value { Either::Left(it) => Some(it), @@ -4129,7 +4136,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); @@ -4184,7 +4191,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); @@ -4192,7 +4199,7 @@ impl Local { } /// All definitions for this local. Example: `let (a$0, _) | (_, a$0) = it;` - pub fn sources(self, db: &dyn HirDatabase) -> Vec<LocalSource> { + pub fn sources(self, db: &dyn HirDatabase) -> Vec<LocalSource<'db>> { let b; let (_, source_map) = match self.parent { ExpressionStoreOwnerId::Signature(generic_def_id) => { @@ -4233,7 +4240,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) => { @@ -4274,13 +4281,13 @@ impl Local { } } -impl PartialOrd for Local { +impl PartialOrd for Local<'_> { fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> { 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) } @@ -4743,7 +4750,7 @@ impl Impl { pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec<Impl> { 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)), @@ -4867,7 +4874,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>, } @@ -4898,15 +4905,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>, } @@ -4961,20 +4968,20 @@ impl<'db> Closure<'db> { /// A coroutine expression, including async, generator, and async-generator coroutines. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub struct Coroutine { - id: InternedCoroutineId, +pub struct Coroutine<'db> { + id: InternedCoroutineId<'db>, } -impl Coroutine { +impl<'db> Coroutine<'db> { /// Returns the values captured by this coroutine. - pub fn captured_items<'db>(&self, db: &'db dyn HirDatabase) -> Vec<ClosureCapture<'db>> { + pub fn captured_items(&self, db: &'db dyn HirDatabase) -> Vec<ClosureCapture<'db>> { captured_items(db, self.id.loc(db)) } } fn captured_items<'db>( db: &'db dyn HirDatabase, - closure: InternedClosure, + closure: InternedClosure<'db>, ) -> Vec<ClosureCapture<'db>> { let InternedClosure { owner: infer_owner, expr: closure, .. } = closure; let infer = InferenceResult::of(db, infer_owner); @@ -5055,13 +5062,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, @@ -5249,16 +5256,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<GenericDefId> for TypeOwnerId<'db> { + fn from(it: GenericDefId) -> TypeOwnerId<'db> { + TypeOwnerId::GenericDefId(it) + } +} + +impl<'db> From<BuiltinDeriveImplId> for TypeOwnerId<'db> { + fn from(it: BuiltinDeriveImplId) -> TypeOwnerId<'db> { + TypeOwnerId::BuiltinDeriveImplId(it) + } +} + +impl<'db> From<AnonConstId<'db>> for TypeOwnerId<'db> { + fn from(it: AnonConstId<'db>) -> TypeOwnerId<'db> { + TypeOwnerId::AnonConstId(it) + } +} + +impl TypeOwnerId<'_> { fn unify(self, other: Self) -> Option<Self> { match (self, other) { (TypeOwnerId::NoParams(_), owner) => Some(owner), @@ -5324,7 +5348,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>>, } @@ -5519,7 +5543,7 @@ impl<'db> Type<'db> { tys: impl IntoIterator<Item: Borrow<Type<'db>>>, ) -> Self { let interner = DbInterner::new_no_crate(db); - let mut owner = None::<TypeOwnerId>; + let mut owner = None::<TypeOwnerId<'db>>; let ty = EarlyBinder::bind(Ty::new_tup_from_iter( interner, tys.into_iter().map(|ty| { @@ -5976,7 +6000,7 @@ impl<'db> Type<'db> { } /// Returns this type as a coroutine. - pub fn as_coroutine(&self) -> Option<Coroutine> { + pub fn as_coroutine(&self) -> Option<Coroutine<'db>> { match self.ty.skip_binder().kind() { TyKind::Coroutine(id, _) => Some(Coroutine { id: id.0 }), _ => None, @@ -6070,7 +6094,10 @@ impl<'db> Type<'db> { } // FIXME: We should probably remove this. - pub fn fingerprint_for_trait_impl(&self, db: &'db dyn HirDatabase) -> Option<SimplifiedType> { + pub fn fingerprint_for_trait_impl( + &self, + db: &'db dyn HirDatabase, + ) -> Option<SimplifiedType<'db>> { fast_reject::simplify_type( DbInterner::new_no_crate(db), self.ty.skip_binder(), @@ -6573,7 +6600,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<Ty<'db>>, } @@ -6706,8 +6733,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 }, @@ -6915,17 +6942,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<Self, 3> { let mut items = ArrayVec::new(); @@ -6982,7 +7009,7 @@ impl ScopeDef { } } -impl From<ItemInNs> for ScopeDef { +impl From<ItemInNs> for ScopeDef<'_> { fn from(item: ItemInNs) -> Self { match item { ItemInNs::Types(id) => ScopeDef::ModuleDef(id), @@ -7040,7 +7067,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> { @@ -7163,7 +7190,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() } @@ -7285,7 +7312,6 @@ impl_has_name!( Macro, ExternAssocItem, AssocItem, - Local, DeriveHelper, ToolModule, Label, @@ -7309,7 +7335,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<Name> { + (*self).name(db).into() + } +} + +impl HasName for TupleField<'_> { + fn name(&self, _db: &dyn HirDatabase) -> Option<Name> { + (*self).name().into() + } +} impl HasName for Param<'_> { fn name(&self, db: &dyn HirDatabase) -> Option<Name> { @@ -7445,10 +7483,10 @@ fn as_name_opt(name: Option<impl AsName>) -> Name { #[track_caller] fn generic_args_from_tys<'db>( interner: DbInterner<'db>, - def_id: SolverDefId, + def_id: SolverDefId<'db>, args: impl IntoIterator<Item: Borrow<Type<'db>>>, -) -> (GenericArgs<'db>, TypeOwnerId) { - let mut owner = None::<TypeOwnerId>; +) -> (GenericArgs<'db>, TypeOwnerId<'db>) { + let mut owner = None::<TypeOwnerId<'db>>; 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 e9e6ec3a01..fee6ae3d49 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs @@ -67,11 +67,11 @@ use crate::{ const CONTINUE_NO_BREAKS: ControlFlow<Infallible, ()> = 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 @@ -82,7 +82,7 @@ pub enum PathResolution { DeriveHelper(DeriveHelper), } -impl PathResolution { +impl<'db> PathResolution<'db> { pub(crate) fn in_type_ns(&self) -> Option<TypeNs> { match self { PathResolution::Def(ModuleDef::Adt(adt)) => Some(TypeNs::AdtId((*adt).into())), @@ -116,21 +116,21 @@ impl PathResolution { } #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct PathResolutionPerNs { - pub type_ns: Option<PathResolution>, - pub value_ns: Option<PathResolution>, - pub macro_ns: Option<PathResolution>, +pub struct PathResolutionPerNs<'db> { + pub type_ns: Option<PathResolution<'db>>, + pub value_ns: Option<PathResolution<'db>>, + pub macro_ns: Option<PathResolution<'db>>, } -impl PathResolutionPerNs { +impl<'db> PathResolutionPerNs<'db> { pub fn new( - type_ns: Option<PathResolution>, - value_ns: Option<PathResolution>, - macro_ns: Option<PathResolution>, + type_ns: Option<PathResolution<'db>>, + value_ns: Option<PathResolution<'db>>, + macro_ns: Option<PathResolution<'db>>, ) -> Self { PathResolutionPerNs { type_ns, value_ns, macro_ns } } - pub fn any(&self) -> Option<PathResolution> { + pub fn any(&self) -> Option<PathResolution<'db>> { self.type_ns.or(self.value_ns).or(self.macro_ns) } } @@ -165,8 +165,8 @@ pub struct Semantics<'db, DB: ?Sized> { } type DefWithoutBodyWithAnonConsts = Either<GenericDefId, VariantId>; -type ExprToAnonConst = FxHashMap<ExprId, AnonConstId>; -type DefAnonConstsMap = FxHashMap<DefWithoutBodyWithAnonConsts, ExprToAnonConst>; +type ExprToAnonConst<'db> = FxHashMap<ExprId, AnonConstId<'db>>; +type DefAnonConstsMap<'db> = FxHashMap<DefWithoutBodyWithAnonConsts, ExprToAnonConst<'db>>; pub struct SemanticsImpl<'db> { pub db: &'db dyn HirDatabase, @@ -174,7 +174,7 @@ pub struct SemanticsImpl<'db> { /// MacroCall to its expansion's MacroCallId cache macro_call_cache: RefCell<FxHashMap<InFile<ast::MacroCall>, MacroCallId>>, /// All anon consts defined by a *signature* (not a body). - signature_anon_consts_cache: RefCell<DefAnonConstsMap>, + signature_anon_consts_cache: RefCell<DefAnonConstsMap<'db>>, } impl<DB: ?Sized> fmt::Debug for Semantics<'_, DB> { @@ -783,7 +783,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<Local> { + pub fn rename_conflicts<'a>( + &self, + to_be_renamed: &Local<'a>, + new_name: &Name, + ) -> Vec<Local<'a>> { 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); @@ -813,7 +817,7 @@ impl<'db> SemanticsImpl<'db> { pub fn as_format_args_parts( &self, string: &ast::String, - ) -> Option<Vec<(TextRange, Option<Either<PathResolution, InlineAsmOperand>>)>> { + ) -> Option<Vec<(TextRange, Option<Either<PathResolution<'db>, 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, _| { @@ -870,7 +874,7 @@ impl<'db> SemanticsImpl<'db> { TextRange, HirFileRange, ast::String, - Option<Either<PathResolution, InlineAsmOperand>>, + Option<Either<PathResolution<'db>, InlineAsmOperand>>, )> { let original_token = self.wrap_token_infile(original_token).map(ast::String::cast).transpose()?; @@ -892,7 +896,7 @@ impl<'db> SemanticsImpl<'db> { TextRange, HirFileRange, ast::String, - Option<Either<PathResolution, InlineAsmOperand>>, + Option<Either<PathResolution<'db>, InlineAsmOperand>>, )> { let relative_offset = offset.checked_sub(original_token.value.syntax().text_range().start())?; @@ -924,13 +928,13 @@ impl<'db> SemanticsImpl<'db> { &self, InFile { value: string, file_id }: InFile<&ast::String>, offset: TextSize, - ) -> Option<(TextRange, Option<Either<PathResolution, InlineAsmOperand>>)> { + ) -> Option<(TextRange, Option<Either<PathResolution<'db>, 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))) @@ -1899,14 +1903,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<Either<Field, TupleField>> { + pub fn resolve_field(&self, field: &ast::FieldExpr) -> Option<Either<Field, TupleField<'db>>> { self.analyze(field.syntax())?.resolve_field(field) } pub fn resolve_field_fallback( &self, field: &ast::FieldExpr, - ) -> Option<(Either<Either<Field, TupleField>, Function>, Option<GenericSubstitution<'db>>)> + ) -> Option<(Either<Either<Field, TupleField<'db>>, Function>, Option<GenericSubstitution<'db>>)> { self.analyze(field.syntax())?.resolve_field_fallback(self.db, field) } @@ -1914,7 +1918,7 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_record_field( &self, field: &ast::RecordExprField, - ) -> Option<(Field, Option<Local>, Type<'db>)> { + ) -> Option<(Field, Option<Local<'db>>, Type<'db>)> { self.resolve_record_field_with_substitution(field) .map(|(field, local, ty, _)| (field, local, ty)) } @@ -1922,7 +1926,7 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_record_field_with_substitution( &self, field: &ast::RecordExprField, - ) -> Option<(Field, Option<Local>, Type<'db>, GenericSubstitution<'db>)> { + ) -> Option<(Field, Option<Local<'db>>, Type<'db>, GenericSubstitution<'db>)> { self.analyze(field.syntax())?.resolve_record_field(self.db, field) } @@ -2026,18 +2030,18 @@ impl<'db> SemanticsImpl<'db> { Some(Macro { id }) } - pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution> { + pub fn resolve_path(&self, path: &ast::Path) -> Option<PathResolution<'db>> { self.resolve_path_with_subst(path).map(|(it, _)| it) } - pub fn resolve_path_per_ns(&self, path: &ast::Path) -> Option<PathResolutionPerNs> { + pub fn resolve_path_per_ns(&self, path: &ast::Path) -> Option<PathResolutionPerNs<'db>> { 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<GenericSubstitution<'db>>)> { + ) -> Option<(PathResolution<'db>, Option<GenericSubstitution<'db>>)> { self.analyze(path.syntax())?.resolve_path(self.db, path) } @@ -2106,17 +2110,17 @@ impl<'db> SemanticsImpl<'db> { .unwrap_or_default() } - fn with_ctx<F: FnOnce(&mut SourceToDefCtx<'_, '_>) -> T, T>(&self, f: F) -> T { + fn with_ctx<F: FnOnce(&mut SourceToDefCtx<'db, '_>) -> 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<T: ToDef>(&self, src: &T) -> Option<T::Def> { + pub fn to_def<T: ToDef<'db>>(&self, src: &T) -> Option<T::Def> { let src = self.find_file(src.syntax()).with_value(src); T::to_def(self, src) } - pub fn to_def2<T: ToDef>(&self, src: InFile<&T>) -> Option<T::Def> { + pub fn to_def2<T: ToDef<'db>>(&self, src: InFile<&T>) -> Option<T::Def> { T::to_def(self, src) } @@ -2179,9 +2183,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 = @@ -2204,7 +2208,7 @@ impl<'db> SemanticsImpl<'db> { &self, def: DefWithoutBodyWithAnonConsts, root_expr: ExprId, - ) -> Option<AnonConstId> { + ) -> Option<AnonConstId<'db>> { 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() @@ -2215,7 +2219,7 @@ impl<'db> SemanticsImpl<'db> { def: ExpressionStoreOwnerId, store: &ExpressionStore, node: ExprOrPatId, - ) -> Option<InferBodyId> { + ) -> Option<InferBodyId<'db>> { let handle_def_without_body = |def| { let root_expr = match node { ExprOrPatId::ExprId(expr) => store.find_root_for_expr(expr), @@ -2236,7 +2240,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(); @@ -2457,7 +2461,7 @@ impl<'db> SemanticsImpl<'db> { &self, element: Either<&ast::Expr, &ast::StmtList>, text_range: TextRange, - ) -> Option<FxIndexSet<Local>> { + ) -> Option<FxIndexSet<Local<'db>>> { let sa = self.analyze(element.either(|e| e.syntax(), |s| s.syntax()))?; let infer_body = sa.infer_body?; let store = sa.store()?; @@ -2506,7 +2510,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<Local> = FxIndexSet::default(); + let mut locals: FxIndexSet<Local<'db>> = FxIndexSet::default(); let mut add_to_locals_used = |id, parent_expr| { let path = match id { ExprOrPatId::ExprId(expr_id) => { @@ -2637,16 +2641,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<Self::Def>; + fn to_def(sema: &SemanticsImpl<'db>, src: InFile<&Self>) -> Option<Self::Def>; } 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<Self::Def> { + fn to_def(sema: &SemanticsImpl<'db>, src: InFile<&Self>) -> Option<Self::Def> { sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from) } } @@ -2673,7 +2677,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), @@ -2682,10 +2686,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<Self::Def> { + fn to_def(sema: &SemanticsImpl<'db>, src: InFile<&Self>) -> Option<Self::Def> { sema.with_ctx(|ctx| ctx.bind_pat_to_def(src, sema)) } } @@ -2712,7 +2716,7 @@ impl ToDef for ast::IdentPat { #[derive(Debug)] pub struct SemanticsScope<'db> { pub db: &'db dyn HirDatabase, - infer_body: Option<InferBodyId>, + infer_body: Option<InferBodyId<'db>>, file_id: HirFileId, resolver: Resolver<'db>, } @@ -2753,7 +2757,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 { @@ -2790,7 +2794,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<PathResolution> { + pub fn speculative_resolve(&self, ast_path: &ast::Path) -> Option<PathResolution<'db>> { let mut kind = PathKind::Plain; let mut segments = vec![]; let mut first = true; @@ -2838,7 +2842,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 f7528d3db1..fa66339208 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(|| { @@ -347,8 +347,8 @@ impl SourceToDefCtx<'_, '_> { pub(super) fn bind_pat_to_def( &mut self, src: InFile<&ast::IdentPat>, - semantics: &SemanticsImpl<'_>, - ) -> Option<crate::Local> { + semantics: &SemanticsImpl<'db>, + ) -> Option<crate::Local<'db>> { 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 db4e92098e..fb27f9dec4 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs @@ -77,8 +77,8 @@ pub(crate) struct SourceAnalyzer<'db> { pub(crate) file_id: HirFileId, pub(crate) resolver: Resolver<'db>, pub(crate) body_or_sig: Option<BodyOrSig<'db>>, - pub(crate) type_owner: TypeOwnerId, - pub(crate) infer_body: Option<InferBodyId>, + pub(crate) type_owner: TypeOwnerId<'db>, + pub(crate) infer_body: Option<InferBodyId<'db>>, } #[derive(Debug)] @@ -87,19 +87,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, }, @@ -129,7 +129,7 @@ impl<'db> SourceAnalyzer<'db> { def: DefWithBodyId, node @ InFile { file_id, .. }: InFile<&SyntaxNode>, offset: Option<TextSize>, - 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); @@ -295,11 +295,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, }) } @@ -311,9 +311,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, .. } => { @@ -328,18 +328,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, }) } @@ -476,8 +476,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> { @@ -516,7 +516,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? @@ -690,7 +690,7 @@ impl<'db> SourceAnalyzer<'db> { pub(crate) fn resolve_field( &self, field: &ast::FieldExpr, - ) -> Option<Either<Field, TupleField>> { + ) -> Option<Either<Field, TupleField<'db>>> { let def = self.infer_body?; let expr_id = self.expr_id(field.clone().into())?.as_expr()?; self.infer()?.field_resolution(expr_id).map(|it| { @@ -701,7 +701,7 @@ impl<'db> SourceAnalyzer<'db> { fn field_subst( &self, field_expr: ExprId, - infer: &InferenceResult, + infer: &InferenceResult<'_>, _db: &'db dyn HirDatabase, ) -> Option<GenericSubstitution<'db>> { let body = self.store()?; @@ -716,7 +716,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, field: &ast::FieldExpr, - ) -> Option<(Either<Either<Field, TupleField>, Function>, Option<GenericSubstitution<'db>>)> + ) -> Option<(Either<Either<Field, TupleField<'db>>, Function>, Option<GenericSubstitution<'db>>)> { let def = self.infer_body?; let expr_id = self.expr_id(field.clone().into())?.as_expr()?; @@ -949,7 +949,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, field: &ast::RecordExprField, - ) -> Option<(Field, Option<Local>, Type<'db>, GenericSubstitution<'db>)> { + ) -> Option<(Field, Option<Local<'db>>, 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))?; @@ -1160,7 +1160,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, path: &ast::Path, - ) -> Option<(PathResolution, Option<GenericSubstitution<'db>>)> { + ) -> Option<(PathResolution<'db>, Option<GenericSubstitution<'db>>)> { let parent = path.syntax().parent(); let parent = || parent.clone(); @@ -1486,9 +1486,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<PathResolutionPerNs> { + ) -> Option<PathResolutionPerNs<'db>> { let mut collector = ExprCollector::new(db, self.resolver.module(), self.file_id, LoweringMode::Ide); let hir_path = @@ -1628,7 +1628,7 @@ impl<'db> SourceAnalyzer<'db> { db: &'db dyn HirDatabase, format_args: InFile<&ast::FormatArgsExpr>, offset: TextSize, - ) -> Option<(TextRange, Option<PathResolution>)> { + ) -> Option<(TextRange, Option<PathResolution<'db>>)> { let (hygiene, implicits) = self.store_sm()?.implicit_format_args(format_args)?; implicits.iter().find(|(range, _)| range.contains_inclusive(offset)).map(|(range, name)| { ( @@ -1666,9 +1666,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<impl Iterator<Item = (TextRange, Option<PathResolution>)> + 'a> { + ) -> Option<impl Iterator<Item = (TextRange, Option<PathResolution<'db>>)> + 'a> { let (hygiene, names) = self.store_sm()?.implicit_format_args(format_args)?; Some(names.iter().map(move |(range, name)| { ( @@ -1846,14 +1846,14 @@ fn adjust( } #[inline] -pub(crate) fn resolve_hir_path( - db: &dyn HirDatabase, - resolver: &Resolver<'_>, - infer_body: Option<InferBodyId>, +pub(crate) fn resolve_hir_path<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, + infer_body: Option<InferBodyId<'db>>, path: &Path, hygiene: HygieneId, store: Option<&ExpressionStore>, -) -> Option<PathResolution> { +) -> Option<PathResolution<'db>> { resolve_hir_path_(db, resolver, infer_body, path, false, hygiene, store, false).any() } @@ -1869,16 +1869,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<InferBodyId>, +fn resolve_hir_path_<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, + infer_body: Option<InferBodyId<'db>>, 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| { @@ -1993,14 +1993,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<ExpressionStoreOwnerId>, - infer_body: Option<InferBodyId>, + infer_body: Option<InferBodyId<'db>>, path: &Path, hygiene: HygieneId, -) -> Option<PathResolution> { +) -> Option<PathResolution<'db>> { resolver.resolve_path_in_value_ns_fully(db, path, hygiene).and_then(|val| { let res = match val { ValueNs::LocalBinding(binding_id) => { @@ -2032,12 +2032,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<PathResolution> { +) -> Option<PathResolution<'db>> { (|| { let (ty, unresolved) = match path.type_anchor() { Some(type_ref) => resolver.generic_def().and_then(|def| { @@ -2127,7 +2127,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<LocalFieldId>)> { @@ -2159,7 +2159,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<LocalFieldId>)> { diff --git a/crates/hir/src/symbols.rs b/crates/hir/src/symbols.rs index 021a20ae1b..79a075ef8b 100644 --- a/crates/hir/src/symbols.rs +++ b/crates/hir/src/symbols.rs @@ -2,7 +2,7 @@ use std::marker::PhantomData; -use base_db::FxIndexSet; +use base_db::{FxIndexSet, salsa::Update}; use either::Either; use hir_def::{ AdtId, AssocItemId, AstIdLoc, Complete, DefWithBodyId, ExternCrateId, HasModule, ImplId, @@ -28,7 +28,7 @@ use crate::{Crate, HasCrate, Module, ModuleDef, Semantics}; /// The actual data that is stored in the index. It should be as compact as /// possible. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] +#[derive(Clone, PartialEq, Eq, Hash, Update)] pub struct FileSymbol<'db> { pub name: Symbol, pub def: ModuleDef, @@ -39,7 +39,33 @@ pub struct FileSymbol<'db> { pub is_assoc: bool, pub is_import: bool, pub do_not_complete: Complete, - _marker: PhantomData<&'db ()>, + _marker: PhantomData<fn() -> &'db ()>, +} + +impl<'db> std::fmt::Debug for FileSymbol<'db> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let FileSymbol { + name, + def, + loc, + container_name, + is_alias, + is_assoc, + is_import, + do_not_complete, + _marker: _, + } = self; + f.debug_struct("FileSymbol") + .field("name", name) + .field("def", def) + .field("loc", loc) + .field("container_name", container_name) + .field("is_alias", is_alias) + .field("is_assoc", is_assoc) + .field("is_import", is_import) + .field("do_not_complete", do_not_complete) + .finish() + } } #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] diff --git a/crates/hir/src/term_search/expr.rs b/crates/hir/src/term_search/expr.rs index a824c8bdca..0799426869 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 8e107afc9e..c0cfe18e6e 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<ScopeDef>, + defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + _defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + _defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + _defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + _defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + _defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator<Item = Expr<'db>> + 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<ScopeDef>, + _defs: &'a FxHashSet<ScopeDef<'db>>, lookup: &'lt mut LookupTable<'db>, should_continue: &'a dyn std::ops::Fn() -> bool, ) -> impl Iterator<Item = Expr<'db>> + 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 4c3168219f..865995def0 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<ast::Type>, initializer: Option<ast::Expr>, - definition: Definition, + definition: Definition<'db>, } /// Attempts to find an appropriate node to apply the action to. -fn find_bool_node(ctx: &AssistContext<'_, '_>) -> Option<BoolNodeData> { +fn find_bool_node<'db>(ctx: &AssistContext<'_, 'db>) -> Option<BoolNodeData<'db>> { let name = ctx.find_node_at_offset::<ast::Name>()?; 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 fb7dcdf371..eb74e91075 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 @@ -169,7 +169,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 f5d2a6cfc5..a2b15fd4c2 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<Self> { match scope_def { ScopeDef::ModuleDef(def) => Some(Ref { @@ -269,10 +269,10 @@ impl Ref { } #[derive(Debug, Clone)] -struct Refs(Vec<Ref>); +struct Refs<'db>(Vec<Ref<'db>>); -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<Definition>) -> Refs { + fn filter_out_by_defs(&self, defs: Vec<Definition<'db>>) -> 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<Definition> { +fn find_imported_defs<'db>(ctx: &AssistContext<'_, 'db>, use_item: Use) -> Vec<Definition<'db>> { [Direction::Prev, Direction::Next] .into_iter() .flat_map(|dir| { @@ -401,7 +401,10 @@ fn find_imported_defs(ctx: &AssistContext<'_, '_>, use_item: Use) -> Vec<Definit .collect() } -fn find_names_to_import(refs_in_target: Refs, imported_defs: Vec<Definition>) -> Vec<Name> { +fn find_names_to_import<'db>( + refs_in_target: Refs<'db>, + imported_defs: Vec<Definition<'db>>, +) -> Vec<Name> { 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 f8572dcd3a..c2eb49dde5 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<OutlivedLocal>, + outliving_locals: Vec<OutlivedLocal<'db>>, /// 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<Local>, Option<ast::SelfParam>) { + sema: &Semantics<'db, RootDatabase>, + ) -> (FxIndexSet<Local<'db>>, Option<ast::SelfParam>) { 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<Item = OutlivedLocal> + 'a { + ctx: &'a AssistContext<'_, 'db>, + ) -> impl Iterator<Item = OutlivedLocal<'db>> + '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<Local>, + locals: FxIndexSet<Local<'db>>, ) -> Vec<Param<'db>> { locals .into_iter() @@ -1254,10 +1254,10 @@ fn path_element_of(reference: &FileReference) -> Option<ast::Expr> { } /// 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<Local> { +) -> FxIndexSet<Local<'db>> { // 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<OutlivedLocal> { + local: Local<'db>, +) -> Option<OutlivedLocal<'db>> { 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<ast::SelfParam>, - 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<Local>, - params: &[Param<'_>], + ctx: &AssistContext<'_, 'db>, + to_this_param: Option<Local<'db>>, + params: &[Param<'db>], ) { - let mut usages_for_param: Vec<(&Param<'_>, Vec<ast::Expr>)> = Vec::new(); + let mut usages_for_param: Vec<(&Param<'db>, Vec<ast::Expr>)> = Vec::new(); let mut usages_for_self_param: Vec<ast::Expr> = 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 40c54e9882..60a1c7ab44 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<FileId, Vec<(TextRange, String)>>, use_stmts_to_be_inserted: &mut FxHashMap<TextSize, ast::Use>, ) { @@ -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<ast::Module>, - ctx: &AssistContext<'_, '_>, + ctx: &AssistContext<'_, 'db>, make: &SyntaxFactory, ) -> Option<TextRange> { //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<ast::Module>, selection_range: TextRange, diff --git a/crates/ide-assists/src/handlers/extract_variable.rs b/crates/ide-assists/src/handlers/extract_variable.rs index b75e7d4802..c2c50b16de 100644 --- a/crates/ide-assists/src/handlers/extract_variable.rs +++ b/crates/ide-assists/src/handlers/extract_variable.rs @@ -530,7 +530,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<hir::Adt>| 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 438966a1d6..fd67617be4 100644 --- a/crates/ide-assists/src/handlers/inline_call.rs +++ b/crates/ide-assists/src/handlers/inline_call.rs @@ -335,12 +335,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<ast::Type>, hir::Param<'_>)], + params: &[(ast::Pat, Option<ast::Type>, 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 2958acc478..d6582a9559 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<SearchScope>, - 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<SearchScope>, - path: &[Option<PathResolution>], + path: &[Option<PathResolution<'_>>], ) -> 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<Rename>, scopes: &Vec<SearchScope>, ) -> 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 979f832978..2be8dd1fbd 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 5542180362..8bfc3439f4 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<Item = (EditionedFileId, FileReference)> { 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 20048ea97b..f1a34f15d0 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<syntax::SmolStr>, ) { 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 8d906064c0..889beeac08 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 0b2b6682aa..c07c02e285 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 507ecaff0d..705305f557 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<PathResolution>, + resolution: Option<PathResolution<'db>>, /// 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<Name, Local>, + pub(crate) locals: FxHashMap<Name, Local<'db>>, /// 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<SmolStr>)) { + pub(crate) fn process_all_names(&self, f: &mut dyn FnMut(Name, ScopeDef<'db>, Vec<SmolStr>)) { 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<SmolStr> { + pub(crate) fn doc_aliases_in_scope(&self, scope_def: ScopeDef<'db>) -> Vec<SmolStr> { 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 61281f8cfb..2ff726c6d0 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 7cb1eaa061..9f8a2f71f1 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<hir::Name> { // 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<hir::Name> { 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<LocatedImport>, - 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<LocatedImport>, - 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<LocatedImport>, - 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<Documentation<'_>> { +fn scope_def_docs<'db>( + db: &'db RootDatabase, + resolution: ScopeDef<'db>, +) -> Option<Documentation<'db>> { 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<Documentati } } -fn scope_def_is_deprecated(ctx: &RenderContext<'_, '_>, 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 82cff37296..52cd664000 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<impl Iterator<Item = Module>> { 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<Definition> { - fn container_to_definition(container: ItemContainer) -> Option<Definition> { + pub fn enclosing_definition(&self, db: &RootDatabase) -> Option<Definition<'db>> { + fn container_to_definition<'db>(container: ItemContainer) -> Option<Definition<'db>> { 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<Documentation<'db>> { + ) -> Option<Documentation<'a>> { 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<Either<Cow<'db, hir::Docs>, Documentation<'db>>> { + ) -> Option<Either<Cow<'a, hir::Docs>, 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<GenericSubstitution<'db>>), 2> { + pub fn definitions(self) -> ArrayVec<(Definition<'db>, Option<GenericSubstitution<'db>>), 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<Definition, 2> { + pub fn definitions_no_ops(self) -> ArrayVec<Definition<'db>, 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<Definition> { + pub fn defined(self) -> Option<Definition<'db>> { 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<Definition> { + ) -> Option<Definition<'db>> { 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<Definition> { + ) -> Option<Definition<'db>> { 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<GenericSubstitution<'db>>), + Definition(Definition<'db>, Option<GenericSubstitution<'db>>), 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<Impl> for Definition { +impl<'db> From<Impl> for Definition<'db> { fn from(impl_: Impl) -> Self { Definition::SelfType(impl_) } } -impl From<InlineAsmOperand> for Definition { +impl<'db> From<InlineAsmOperand> for Definition<'db> { fn from(value: InlineAsmOperand) -> Self { Definition::InlineAsmOperand(value) } } -impl From<Either<PathResolution, InlineAsmOperand>> for Definition { - fn from(value: Either<PathResolution, InlineAsmOperand>) -> Self { +impl<'db> From<Either<PathResolution<'db>, InlineAsmOperand>> for Definition<'db> { + fn from(value: Either<PathResolution<'db>, 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<AssocItem> { 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<ExternAssocItem> { match self { Definition::Function(it) => it.as_extern_assoc_item(db), @@ -937,7 +960,7 @@ impl AsExternAssocItem for Definition { } } -impl From<AssocItem> for Definition { +impl<'db> From<AssocItem> for Definition<'db> { fn from(assoc_item: AssocItem) -> Self { match assoc_item { AssocItem::Function(it) => Definition::Function(it), @@ -947,8 +970,8 @@ impl From<AssocItem> for Definition { } } -impl From<PathResolution> for Definition { - fn from(path_resolution: PathResolution) -> Self { +impl<'db> From<PathResolution<'db>> 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<PathResolution> for Definition { } } -impl From<ModuleDef> for Definition { +impl<'db> From<ModuleDef> for Definition<'db> { fn from(def: ModuleDef) -> Self { match def { ModuleDef::Module(it) => Definition::Module(it), @@ -979,7 +1002,7 @@ impl From<ModuleDef> for Definition { } } -impl From<DocLinkDef> for Definition { +impl<'db> From<DocLinkDef> for Definition<'db> { fn from(def: DocLinkDef) -> Self { match def { DocLinkDef::ModuleDef(it) => it.into(), @@ -989,13 +1012,13 @@ impl From<DocLinkDef> for Definition { } } -impl From<Variant> for Definition { +impl<'db> From<Variant> for Definition<'db> { fn from(def: Variant) -> Self { ModuleDef::from(def).into() } } -impl TryFrom<DefWithBody> for Definition { +impl<'db> TryFrom<DefWithBody> for Definition<'db> { type Error = (); fn try_from(def: DefWithBody) -> Result<Self, Self::Error> { match def { @@ -1007,7 +1030,7 @@ impl TryFrom<DefWithBody> for Definition { } } -impl From<GenericDef> for Definition { +impl<'db> From<GenericDef> for Definition<'db> { fn from(def: GenericDef) -> Self { match def { GenericDef::Function(it) => it.into(), @@ -1021,7 +1044,7 @@ impl From<GenericDef> for Definition { } } -impl TryFrom<ExpressionStoreOwner> for Definition { +impl<'db> TryFrom<ExpressionStoreOwner> for Definition<'db> { type Error = (); fn try_from(def: ExpressionStoreOwner) -> Result<Self, Self::Error> { match def { @@ -1032,9 +1055,9 @@ impl TryFrom<ExpressionStoreOwner> for Definition { } } -impl TryFrom<Definition> for GenericDef { +impl TryFrom<Definition<'_>> for GenericDef { type Error = (); - fn try_from(def: Definition) -> Result<Self, Self::Error> { + fn try_from(def: Definition<'_>) -> Result<Self, Self::Error> { 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 f28ce53e91..b5f62c8fd7 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<ScopeDef> { + fn find_def(&self, path: &str) -> Option<ScopeDef<'_>> { 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 838aac2283..00e81b3ef4 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<Definition> { +) -> Option<Definition<'db>> { 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 6edc550b33..f5dff47acf 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<ScopeDef> { + fn scope_definitions<'a>(&self, sema: &Semantics<'a, RootDatabase>) -> FxHashSet<ScopeDef<'a>> { 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 ff4d5a2886..b89c2fdf4a 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 d59df3601f..b688cb188d 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<PathResolution, InlineAsmOperand>, + res: Either<PathResolution<'db>, 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<hir::Type<'db>> { +fn def_to_ty<'db>( + sema: &Semantics<'db, RootDatabase>, + def: &Definition<'db>, +) -> Option<hir::Type<'db>> { 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/symbol_index.rs b/crates/ide-db/src/symbol_index.rs index 55acf5abf8..edec86285b 100644 --- a/crates/ide-db/src/symbol_index.rs +++ b/crates/ide-db/src/symbol_index.rs @@ -29,7 +29,7 @@ use std::{ use base_db::{ CrateOrigin, InternedSourceRootId, LangCrateOrigin, LibraryRoots, LocalRoots, SourceRootId, - source_root_crates, + salsa::Update, source_root_crates, }; use fst::{Automaton, Streamer, raw::IndexedValue}; use hir::{ @@ -40,7 +40,6 @@ use hir::{ }; use itertools::Itertools; use rayon::prelude::*; -use salsa::Update; use crate::RootDatabase; @@ -366,6 +365,25 @@ pub struct SymbolIndex<'db> { map: fst::Map<Vec<u8>>, } +// SAFETY: +// - It is safe to compare a `SymbolIndex` from a previous revision to a new one. +// - FileSymbol<'db>: Update +unsafe impl<'db> Update for SymbolIndex<'db> +where + FileSymbol<'db>: Update, +{ + unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool { + // SAFETY: Safe to dereference as per `salsa::Update` contract. + let this = unsafe { &mut *old_pointer }; + if *this != new_value { + *this = new_value; + true + } else { + false + } + } +} + impl<'db> SymbolIndex<'db> { /// The symbol index for a given source root within library_roots. pub fn library_symbols( @@ -475,18 +493,6 @@ impl Hash for SymbolIndex<'_> { } } -unsafe impl Update for SymbolIndex<'_> { - unsafe fn maybe_update(old_pointer: *mut Self, new_value: Self) -> bool { - let this = unsafe { &mut *old_pointer }; - if *this == new_value { - false - } else { - *this = new_value; - true - } - } -} - impl<'db> SymbolIndex<'db> { fn new(mut symbols: Box<[FileSymbol<'db>]>) -> SymbolIndex<'db> { fn cmp(lhs: &FileSymbol<'_>, rhs: &FileSymbol<'_>) -> Ordering { diff --git a/crates/ide-db/src/test_data/test_doc_alias.txt b/crates/ide-db/src/test_data/test_doc_alias.txt index 12eb7e8e0a..7a59abf36b 100644 --- a/crates/ide-db/src/test_data/test_doc_alias.txt +++ b/crates/ide-db/src/test_data/test_doc_alias.txt @@ -41,7 +41,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Struct", @@ -78,7 +77,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "mul1", @@ -115,7 +113,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "mul2", @@ -152,7 +149,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "s1", @@ -189,7 +185,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "s1", @@ -226,7 +221,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "s2", @@ -263,7 +257,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, ], ), diff --git a/crates/ide-db/src/test_data/test_symbol_index_collection.txt b/crates/ide-db/src/test_data/test_symbol_index_collection.txt index 0ef19eb493..d0619761c0 100644 --- a/crates/ide-db/src/test_data/test_symbol_index_collection.txt +++ b/crates/ide-db/src/test_data/test_symbol_index_collection.txt @@ -41,7 +41,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Alias", @@ -76,7 +75,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "B", @@ -113,7 +111,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "CONST", @@ -148,7 +145,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "CONST_WITH_INNER", @@ -183,7 +179,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Enum", @@ -220,7 +215,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "ItemLikeMacro", @@ -257,7 +251,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Macro", @@ -294,7 +287,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "STATIC", @@ -329,7 +321,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Struct", @@ -366,7 +357,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "StructFromMacro", @@ -403,7 +393,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "StructInFn", @@ -442,7 +431,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "StructInNamedConst", @@ -481,7 +469,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "StructInUnnamedConst", @@ -518,7 +505,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "StructT", @@ -555,7 +541,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Trait", @@ -590,7 +575,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Trait", @@ -627,7 +611,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Union", @@ -664,7 +647,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "a_mod", @@ -699,7 +681,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "b_mod", @@ -734,7 +715,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "define_struct", @@ -771,7 +751,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "generic_impl_fn", @@ -808,7 +787,6 @@ is_assoc: true, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "impl_fn", @@ -845,7 +823,6 @@ is_assoc: true, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "macro_rules_macro", @@ -882,7 +859,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "main", @@ -917,7 +893,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "really_define_struct", @@ -954,7 +929,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "trait_fn", @@ -991,7 +965,6 @@ is_assoc: true, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, ], ), @@ -1037,7 +1010,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, ], ), @@ -1081,7 +1053,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "IsThisJustATrait", @@ -1118,7 +1089,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "StructInModB", @@ -1155,7 +1125,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "SuperItemLikeMacro", @@ -1192,7 +1161,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "ThisStruct", @@ -1229,7 +1197,6 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, ], ), diff --git a/crates/ide-db/src/test_data/test_symbols_exclude_imports.txt b/crates/ide-db/src/test_data/test_symbols_exclude_imports.txt index b03d926efe..20b162b7cd 100644 --- a/crates/ide-db/src/test_data/test_symbols_exclude_imports.txt +++ b/crates/ide-db/src/test_data/test_symbols_exclude_imports.txt @@ -34,6 +34,5 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, ] diff --git a/crates/ide-db/src/test_data/test_symbols_with_imports.txt b/crates/ide-db/src/test_data/test_symbols_with_imports.txt index 84bb6670d7..1d475ab005 100644 --- a/crates/ide-db/src/test_data/test_symbols_with_imports.txt +++ b/crates/ide-db/src/test_data/test_symbols_with_imports.txt @@ -34,7 +34,6 @@ is_assoc: false, is_import: false, do_not_complete: Yes, - _marker: PhantomData<&()>, }, FileSymbol { name: "Foo", @@ -71,6 +70,5 @@ is_assoc: false, is_import: true, do_not_complete: Yes, - _marker: PhantomData<&()>, }, ] diff --git a/crates/ide-db/src/traits.rs b/crates/ide-db/src/traits.rs index 994427ac76..4a560d30ba 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<Definition> { +pub(crate) fn as_trait_assoc_def<'db>( + db: &dyn HirDatabase, + def: Definition<'db>, +) -> Option<Definition<'db>> { 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<Definition> { +) -> Option<Definition<'db>> { 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 e4ee066653..5c6c979416 100644 --- a/crates/ide-diagnostics/src/handlers/mutability_errors.rs +++ b/crates/ide-diagnostics/src/handlers/mutability_errors.rs @@ -7,7 +7,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<Diagnostic> { +pub(crate) fn need_mut( + ctx: &DiagnosticsContext<'_, '_>, + d: &hir::NeedMut<'_>, +) -> Option<Diagnostic> { let root = d.span.file_id.parse_or_expand(ctx.sema.db); let node = d.span.value.to_node(&root); let mut span = d.span; @@ -64,7 +67,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<Diagnostic> { 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 dede3b4aad..9e5150cf52 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<Diagnostic> { 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 461de4092e..3dbba0ff2d 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<SmolStr, parsing::Placeholder>, pub(crate) node: SyntaxNode, // Paths in `node` that we've resolved. - pub(crate) resolved_paths: FxHashMap<SyntaxNode, ResolvedPath>, + pub(crate) resolved_paths: FxHashMap<SyntaxNode, ResolvedPath<'db>>, pub(crate) ufcs_function_calls: FxHashMap<SyntaxNode, UfcsCallInfo<'db>>, 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<SyntaxNode, ResolvedPath>, + resolved_paths: &mut FxHashMap<SyntaxNode, ResolvedPath<'db>>, ) -> 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<hir::PathResolution> { + fn resolve_path(&self, path: &ast::Path) -> Option<hir::PathResolution<'db>> { // 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 51e4951cf6..c6a1d69672 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<Match>, ) { 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<Match>, ) { 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<SyntaxNode> { 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 fd462d003d..70d05cd3b5 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<hir::Namespace>, is_inner_doc: hir::IsInnerDoc, -) -> Option<Definition> { +) -> Option<Definition<'db>> { 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<DocComment } impl DocCommentToken { - pub(crate) fn get_definition_with_descend_at<T>( + 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<T>, + mut cb: impl FnMut(Definition<'db>, SyntaxNode, TextRange) -> Option<T>, ) -> Option<T> { 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<String> { +fn rewrite_url_link(db: &RootDatabase, def: Definition<'_>, target: &str) -> Option<String> { 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<String> { +fn mod_path_of_def(db: &RootDatabase, def: Definition<'_>) -> Option<String> { 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<Url>, Option<Url>) { @@ -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<String>)> { + def: Definition<'db>, +) -> Option<(Definition<'db>, String, Option<String>)> { 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 509c55a31e..720528d0b5 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<Option<(Option<Cow<'db, hir::Docs>>, Definition)>> { +) -> Option<Option<(Option<Cow<'db, hir::Docs>>, 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 b6d1689437..b778066f42 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs @@ -399,7 +399,7 @@ fn try_lookup_macro_def_in_macro_use( /// ``` fn try_filter_trait_item_definition( sema: &Semantics<'_, RootDatabase>, - def: &Definition, + def: &Definition<'_>, ) -> Option<Vec<NavigationTarget>> { let db = sema.db; let assoc = def.as_assoc_item(db)?; @@ -653,7 +653,7 @@ fn nav_for_break_points( Some(navs) } -fn def_to_nav(sema: &Semantics<'_, RootDatabase>, def: Definition) -> Vec<NavigationTarget> { +fn def_to_nav(sema: &Semantics<'_, RootDatabase>, def: Definition<'_>) -> Vec<NavigationTarget> { 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 ffd144a827..9de956be5e 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 db5464a1fe..dfe8dcaa77 100644 --- a/crates/ide/src/highlight_related.rs +++ b/crates/ide/src/highlight_related.rs @@ -668,7 +668,10 @@ fn cover_range(r0: Option<TextRange>, r1: Option<TextRange>) -> Option<TextRange } } -fn find_defs(sema: &Semantics<'_, RootDatabase>, token: SyntaxToken) -> FxHashSet<Definition> { +fn find_defs<'db>( + sema: &Semantics<'db, RootDatabase>, + token: SyntaxToken, +) -> FxHashSet<Definition<'db>> { 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 28e1dc72bf..3d73b5b0f2 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<GenericSubstitution<'_>>, scope_node: &SyntaxNode, macro_arm: Option<u32>, @@ -568,7 +568,7 @@ fn notable_traits<'db>( fn show_implementations_action( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, ) -> Option<HoverAction> { fn to_action(nav_target: NavigationTarget) -> HoverAction { HoverAction::Implementation(FilePosition { @@ -590,7 +590,7 @@ fn show_implementations_action( fn show_fn_references_action( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, ) -> Option<HoverAction> { match def { Definition::Function(it) => { @@ -607,7 +607,7 @@ fn show_fn_references_action( fn runnable_action( sema: &hir::Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, file_id: FileId, ) -> Option<HoverAction> { match def { @@ -628,7 +628,7 @@ fn runnable_action( fn goto_type_action_for_def( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, notable_traits: &[(hir::Trait, Vec<(Option<hir::Type<'_>>, hir::Name)>)], subst_types: Option<Vec<(hir::Symbol, hir::Type<'_>)>>, edition: Edition, diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index 638ea6bdb9..88d21b23e8 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -338,7 +338,7 @@ pub(super) fn try_for_lint(attr: &ast::Attr, token: &SyntaxToken) -> Option<Hove pub(super) fn process_markup( db: &RootDatabase, - def: Definition, + def: Definition<'_>, markup: &Markup, markup_range_map: Option<hir::Docs>, config: &HoverConfig<'_>, @@ -352,7 +352,11 @@ pub(super) fn process_markup( Markup::from(markup) } -fn definition_owner_name(db: &RootDatabase, def: Definition, edition: Edition) -> Option<String> { +fn definition_owner_name( + db: &RootDatabase, + def: Definition<'_>, + edition: Edition, +) -> Option<String> { match def { Definition::Field(f) => { let parent = f.parent_def(db); @@ -445,7 +449,7 @@ pub(super) fn path( pub(super) fn definition( db: &RootDatabase, - def: Definition, + def: Definition<'_>, famous_defs: Option<&FamousDefs<'_, '_>>, notable_traits: &[(Trait, Vec<(Option<Type<'_>>, Name)>)], macro_arm: Option<u32>, @@ -1077,7 +1081,7 @@ fn closure_ty( Some(res) } -fn definition_path(db: &RootDatabase, &def: &Definition, edition: Edition) -> Option<String> { +fn definition_path(db: &RootDatabase, &def: &Definition<'_>, edition: Edition) -> Option<String> { if matches!( def, Definition::TupleField(_) diff --git a/crates/ide/src/interpret.rs b/crates/ide/src/interpret.rs index 994d325ccc..f8e8d87449 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 335e1b5b13..c92f2bbace 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<Self> { + pub fn from_def(db: &RootDatabase, def: Definition<'_>, from_crate: Crate) -> Option<Self> { 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<MonikerResult> { 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<Moniker> { 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<Moniker> { let module = match definition { diff --git a/crates/ide/src/navigation_target.rs b/crates/ide/src/navigation_target.rs index fd6c8263f9..125b2f495a 100644 --- a/crates/ide/src/navigation_target.rs +++ b/crates/ide/src/navigation_target.rs @@ -296,7 +296,7 @@ impl<'db> TryToNav for FileSymbol<'db> { } } -impl TryToNav for Definition { +impl TryToNav for Definition<'_> { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -640,7 +640,7 @@ impl TryToNav for hir::GenericParam { } } -impl ToNav for LocalSource { +impl ToNav for LocalSource<'_> { fn to_nav(&self, db: &RootDatabase) -> UpmappingResult<NavigationTarget> { let InFile { file_id, value } = &self.source; let file_id = *file_id; @@ -675,7 +675,7 @@ impl ToNav for LocalSource { } } -impl ToNav for hir::Local { +impl ToNav for hir::Local<'_> { fn to_nav(&self, db: &RootDatabase) -> UpmappingResult<NavigationTarget> { self.primary_source(db).to_nav(db) } diff --git a/crates/ide/src/references.rs b/crates/ide/src/references.rs index 34286c4790..d85e01af41 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<Vec<ReferenceSearchResult>> { @@ -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<Vec<Definition>> { +) -> Option<Vec<Definition<'db>>> { 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 185815fa73..4a2cc5f551 100644 --- a/crates/ide/src/rename.rs +++ b/crates/ide/src/rename.rs @@ -274,13 +274,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<impl Iterator<Item = (FileRange, SyntaxKind, Definition, Name, RenameDefinition)>> -{ +) -> RenameResult< + impl Iterator<Item = (FileRange, SyntaxKind, Definition<'db>, Name, RenameDefinition)>, +> { let maybe_format_args = syntax.token_at_offset(offset).find(|t| matches!(t.kind(), SyntaxKind::STRING)); @@ -492,9 +493,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<SourceChange> { if never!(local.is_self(sema.db)) { bail!("rename_to_self invoked on self"); @@ -749,9 +750,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 ce4e5cf97f..77d1d5a23f 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<Runnable> { +fn module_def_doctest(sema: &Semantics<'_, RootDatabase>, def: Definition<'_>) -> Option<Runnable> { 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 db24c8dd06..9e8d772cb3 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<Definition, TokenId>, + def_map: FxHashMap<Definition<'a>, TokenId>, } #[derive(Debug)] @@ -131,7 +131,7 @@ fn all_modules(db: &dyn HirDatabase) -> Vec<Module> { fn documentation_for_definition( sema: &Semantics<'_, RootDatabase>, - def: Definition, + def: Definition<'_>, scope_node: &SyntaxNode, ) -> Option<Documentation<'static>> { let famous_defs = match &def { @@ -147,7 +147,7 @@ fn documentation_for_definition( fn get_definitions<'db>( sema: &Semantics<'db, RootDatabase>, token: SyntaxToken, -) -> Option<ArrayVec<(Definition, Option<hir::GenericSubstitution<'db>>), 2>> { +) -> Option<ArrayVec<(Definition<'db>, Option<hir::GenericSubstitution<'db>>), 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 @@ -164,7 +164,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(); @@ -195,7 +195,7 @@ impl StaticIndex<'_> { }; let mut result = StaticIndexedFile { file_id, 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 { @@ -265,7 +265,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 6823736d12..92daacd6d3 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<hir::Crate>, - 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 9af6d67b59..56020b4017 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, |