diff --git a/crates/hir-def/src/attrs/docs.rs b/crates/hir-def/src/attrs/docs.rs index 0dd20c1a0cb4..aebd888b70b0 100644 --- a/crates/hir-def/src/attrs/docs.rs +++ b/crates/hir-def/src/attrs/docs.rs @@ -7,6 +7,7 @@ //! and highlight injection). use std::{ + cell::LazyCell, convert::Infallible, ops::{ControlFlow, Range}, }; @@ -420,7 +421,21 @@ fn extend_with_attrs<'a, 'db>( make_resolver: &dyn Fn() -> Resolver<'db>, ) { // Lazily initialised when we first encounter a `#[doc = macro!()]`. - let mut expander: Option> = None; + let mut expander = LazyCell::new(|| { + let resolver = make_resolver(); + let def_map = resolver.top_level_def_map(); + let recursion_limit = def_map.recursion_limit(); + DocMacroExpander { + db, + krate, + macro_depth: file_id.macro_expansion_depth(db), + recursion_limit, + resolver, + file_id, + ast_id_map: file_id.ast_id_map(db), + span_map: file_id.span_map(db), + } + }); expand_cfg_attr_with_doc_comments::<_, Infallible>( AttrDocCommentIter::from_syntax_node(node).filter(|attr| match attr { @@ -441,27 +456,10 @@ fn extend_with_attrs<'a, 'db>( && let ast::LiteralKind::String(value) = value.kind() { result.extend_with_doc_attr(value, indent); - } else { - let exp = expander.get_or_insert_with(|| { - let resolver = make_resolver(); - let def_map = resolver.top_level_def_map(); - let recursion_limit = def_map.recursion_limit(); - DocMacroExpander { - db, - krate, - macro_depth: file_id.macro_expansion_depth(db), - recursion_limit, - resolver, - file_id, - ast_id_map: file_id.ast_id_map(db), - span_map: file_id.span_map(db), - } - }); - if let Some(expanded) = - expand_doc_expr_via_macro_pipeline(exp, value) - { - result.extend_with_unmapped_doc_str(&expanded, indent); - } + } else if let Some(expanded) = + expand_doc_expr_via_macro_pipeline(&mut expander, value) + { + result.extend_with_unmapped_doc_str(&expanded, indent); } } } diff --git a/crates/hir-def/src/builtin_derive.rs b/crates/hir-def/src/builtin_derive.rs index 6004a33ee19b..419afba1019e 100644 --- a/crates/hir-def/src/builtin_derive.rs +++ b/crates/hir-def/src/builtin_derive.rs @@ -111,7 +111,7 @@ impl BuiltinDeriveImplMethod { pub fn trait_method( self, db: &dyn SourceDatabase, - impl_: BuiltinDeriveImplId, + impl_: BuiltinDeriveImplId<'_>, ) -> Option { let loc = impl_.loc(db); let lang_items = crate::lang_item::lang_items(db, loc.krate(db)); diff --git a/crates/hir-def/src/dyn_map.rs b/crates/hir-def/src/dyn_map.rs index c38ceccd1fc0..d8d8a3db5a48 100644 --- a/crates/hir-def/src/dyn_map.rs +++ b/crates/hir-def/src/dyn_map.rs @@ -9,8 +9,8 @@ //! # use hir_def::dyn_map::DynMap; //! # use hir_def::dyn_map::Key; //! // keys define submaps of a `DynMap` -//! const STRING_TO_U32: Key = Key::new(); -//! const U32_TO_VEC: Key> = Key::new(); +//! const STRING_TO_U32: StaticKey = Key::new(); +//! const U32_TO_VEC: StaticKey> = Key::new(); //! //! // Note: concrete type, no type params! //! let mut map = DynMap::new(); @@ -25,88 +25,78 @@ //! a coincidence. pub mod keys { - use std::marker::PhantomData; - use either::Either; use hir_expand::{MacroCallId, attrs::AttrId}; - use rustc_hash::FxHashMap; - use syntax::{AstNode, AstPtr, ast}; + use syntax::ast; use crate::{ BlockId, BuiltinDeriveImplId, ConstId, EnumId, EnumVariantId, ExternBlockId, ExternCrateId, FieldId, FunctionId, ImplId, LifetimeParamId, Macro2Id, MacroRulesId, ProcMacroId, StaticId, StructId, TraitId, TypeAliasId, TypeOrConstParamId, UnionId, UseId, - dyn_map::{DynMap, Policy}, + dyn_map::{Key, ValueTrait}, }; - pub type Key = crate::dyn_map::Key, V, AstPtrPolicy>; - - pub const BLOCK: Key = Key::new(); - pub const FUNCTION: Key = Key::new(); - pub const CONST: Key = Key::new(); - pub const STATIC: Key = Key::new(); - pub const TYPE_ALIAS: Key = Key::new(); - pub const IMPL: Key = Key::new(); - pub const EXTERN_BLOCK: Key = Key::new(); - pub const TRAIT: Key = Key::new(); - pub const STRUCT: Key = Key::new(); - pub const UNION: Key = Key::new(); - pub const ENUM: Key = Key::new(); - pub const EXTERN_CRATE: Key = Key::new(); - pub const USE: Key = Key::new(); - - pub const ENUM_VARIANT: Key = Key::new(); - pub const TUPLE_FIELD: Key = Key::new(); - pub const RECORD_FIELD: Key = Key::new(); - pub const TYPE_PARAM: Key = Key::new(); - pub const CONST_PARAM: Key = Key::new(); - pub const LIFETIME_PARAM: Key = Key::new(); - - pub const MACRO_RULES: Key = Key::new(); - pub const MACRO2: Key = Key::new(); - pub const PROC_MACRO: Key = Key::new(); - pub const MACRO_CALL: Key = Key::new(); - pub const ATTR_MACRO_CALL: Key = Key::new(); - pub const DERIVE_MACRO_CALL: Key< - ast::Meta, - ( - AttrId, - /* derive() */ MacroCallId, - /* actual derive macros */ - Box<[Option>]>, - ), - > = Key::new(); - - /// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are - /// equal if they point to exactly the same object. - /// - /// In general, we do not guarantee that we have exactly one instance of a - /// syntax tree for each file. We probably should add such guarantee, but, for - /// the time being, we will use identity-less AstPtr comparison. - pub struct AstPtrPolicy { - _phantom: PhantomData<(AST, ID)>, + macro_rules! declare_keys { + { + $vis:vis const $key_name:ident<$key:ty, for<$db_lt:lifetime> $value:ty $(,)?>; + $( $rest:tt )* + } => { + $vis const $key_name: Key<$key, dyn for<$db_lt> ValueTrait<$db_lt, Output = $value>> = Key::new(); + declare_keys!( $($rest)* ); + }; + { + $vis:vis const $key_name:ident<$key:ty, $value:ty $(,)?>; + $( $rest:tt )* + } => { + declare_keys! { + $vis const $key_name<$key, for<'db> $value>; + $( $rest )* + } + }; + // Recursion base case. + () => {}; } - impl Policy for AstPtrPolicy { - type K = AstPtr; - type V = ID; - fn insert(map: &mut DynMap, key: AstPtr, value: ID) { - map.map - .entry::, ID>>() - .or_insert_with(Default::default) - .insert(key, value); - } - fn get<'a>(map: &'a DynMap, key: &AstPtr) -> Option<&'a ID> { - map.map.get::, ID>>()?.get(key) - } - fn is_empty(map: &DynMap) -> bool { - map.map.get::, ID>>().is_none_or(|it| it.is_empty()) - } + declare_keys! { + pub const BLOCK; + pub const FUNCTION; + pub const CONST; + pub const STATIC; + pub const TYPE_ALIAS; + pub const IMPL; + pub const EXTERN_BLOCK; + pub const TRAIT; + pub const STRUCT; + pub const UNION; + pub const ENUM; + pub const EXTERN_CRATE; + pub const USE; + + pub const ENUM_VARIANT; + pub const TUPLE_FIELD; + pub const RECORD_FIELD; + pub const TYPE_PARAM; + pub const CONST_PARAM; + pub const LIFETIME_PARAM; + + pub const MACRO_RULES; + pub const MACRO2; + pub const PROC_MACRO; + pub const MACRO_CALL; + pub const ATTR_MACRO_CALL; + pub const DERIVE_MACRO_CALL< + ast::Meta, + for<'db> ( + AttrId, + /* derive() */ MacroCallId, + /* actual derive macros */ + Box<[Option>>]>, + ), + >; } } use std::{ - hash::Hash, marker::PhantomData, ops::{Index, IndexMut}, }; @@ -114,86 +104,141 @@ use std::{ use rustc_hash::FxHashMap; use stdx::anymap::Map; -pub struct Key { - _phantom: PhantomData<(K, V, P)>, +pub trait ValueTrait<'db> { + type Output; } -impl Key { - #[allow( - clippy::new_without_default, - reason = "this a const fn, so it can't be default yet. See " - )] - pub(crate) const fn new() -> Key { - Key { _phantom: PhantomData } - } -} +type Value<'db, V> = >::Output; -impl Copy for Key {} +use syntax::{AstNode, AstPtr}; -impl Clone for Key { - fn clone(&self) -> Key { - *self - } -} +pub type StaticKey = Key ValueTrait<'db, Output = V>>; -pub trait Policy { - type K; - type V; - - fn insert(map: &mut DynMap, key: Self::K, value: Self::V); - fn get<'a>(map: &'a DynMap, key: &Self::K) -> Option<&'a Self::V>; - fn is_empty(map: &DynMap) -> bool; +pub struct Key { + _phantom: PhantomData<(K, V)>, } -impl Policy for (K, V) { - type K = K; - type V = V; - fn insert(map: &mut DynMap, key: K, value: V) { - map.map.entry::>().or_insert_with(Default::default).insert(key, value); - } - fn get<'a>(map: &'a DynMap, key: &K) -> Option<&'a V> { - map.map.get::>()?.get(key) +impl Key { + pub(crate) const fn new() -> Key + where + V: for<'db> ValueTrait<'db>, + Value<'static, V>: 'static, + { + Key { _phantom: PhantomData } } - fn is_empty(map: &DynMap) -> bool { - map.map.get::>().is_none_or(|it| it.is_empty()) +} + +impl Copy for Key {} + +impl Clone for Key { + fn clone(&self) -> Key { + *self } } #[derive(Default)] -pub struct DynMap { +pub struct DynMap<'db> { pub(crate) map: Map, + _marker: PhantomData<&'db ()>, } #[repr(transparent)] -pub struct KeyMap { - map: DynMap, +pub struct KeyMap<'db, KEY> { + map: DynMap<'db>, _phantom: PhantomData, } -impl KeyMap> { - pub fn insert(&mut self, key: P::K, value: P::V) { - P::insert(&mut self.map, key, value) +// XXX: AST Nodes and SyntaxNodes have identity equality semantics: nodes are +// equal if they point to exactly the same object. +// +// In general, we do not guarantee that we have exactly one instance of a +// syntax tree for each file. We probably should add such guarantee, but, for +// the time being, we will use identity-less AstPtr comparison. +impl<'db, K, V: ?Sized> KeyMap<'db, Key> +where + K: AstNode + 'static, + V: for<'db_> ValueTrait<'db_>, + Value<'static, V>: 'static, +{ + #[inline] + pub fn insert(&mut self, key: AstPtr, value: Value<'db, V>) { + // SAFETY: We only retrieve it with lifetime `'db`. + let value = unsafe { std::mem::transmute::, Value<'static, V>>(value) }; + self.map + .map + .entry::, Value<'static, V>>>() + .or_insert_with(Default::default) + .insert(key, value); } - pub fn get(&self, key: &P::K) -> Option<&P::V> { - P::get(&self.map, key) + + #[inline] + pub fn get(&self, key: &AstPtr) -> Option<&Value<'db, V>> { + let result = self.map.map.get::, Value<'static, V>>>()?.get(key); + // SAFETY: We only store with lifetime `'db`. + unsafe { std::mem::transmute::>, Option<&Value<'db, V>>>(result) } } + #[inline] pub fn is_empty(&self) -> bool { - P::is_empty(&self.map) + self.map.map.get::, Value<'static, V>>>().is_none_or(|it| it.is_empty()) } } -impl Index> for DynMap { - type Output = KeyMap>; - fn index(&self, _key: Key) -> &Self::Output { - // Safe due to `#[repr(transparent)]`. - unsafe { std::mem::transmute::<&DynMap, &KeyMap>>(self) } +impl<'db, K, V: ?Sized> Index> for DynMap<'db> +where + K: AstNode + 'static, + V: for<'db_> ValueTrait<'db_>, + Value<'static, V>: 'static, +{ + type Output = KeyMap<'db, Key>; + #[inline] + fn index(&self, _key: Key) -> &Self::Output { + // SAFETY: Safe due to `#[repr(transparent)]`. + unsafe { std::mem::transmute::<&DynMap<'db>, &KeyMap<'db, Key>>(self) } } } -impl IndexMut> for DynMap { - fn index_mut(&mut self, _key: Key) -> &mut Self::Output { - // Safe due to `#[repr(transparent)]`. - unsafe { std::mem::transmute::<&mut DynMap, &mut KeyMap>>(self) } +impl<'db, K, V: ?Sized> IndexMut> for DynMap<'db> +where + K: AstNode + 'static, + V: for<'db_> ValueTrait<'db_>, + Value<'static, V>: 'static, +{ + #[inline] + fn index_mut(&mut self, _key: Key) -> &mut Self::Output { + // SAFETY: Safe due to `#[repr(transparent)]`. + unsafe { std::mem::transmute::<&mut DynMap<'db>, &mut KeyMap<'db, Key>>(self) } + } +} + +#[cfg(test)] +mod tests { + use test_fixture::WithFixture; + + use syntax::{ + AstPtr, + ast::{self, make}, + }; + + use crate::{ModuleIdLt, test_db::TestDB}; + + use super::{DynMap, Key, ValueTrait}; + + const MODULE: Key ValueTrait<'db, Output = ModuleIdLt<'db>>> = + Key::new(); + + #[test] + fn lifetime_key_returns_database_bound_id() { + let (db, file_id) = TestDB::with_single_file(""); + let module = make::mod_(make::name("foo"), None); + let module = AstPtr::new(&module); + let module_id = db.module_for_file(file_id.file_id(&db)); + let module_id = unsafe { module_id.to_db(&db) }; + let mut map = DynMap::default(); + + map[MODULE].insert(module, module_id); + + let stored = map[MODULE].get(&module).unwrap(); + assert_eq!(*stored, module_id); } } diff --git a/crates/hir-def/src/expr_store.rs b/crates/hir-def/src/expr_store.rs index 5e6633d1cec1..d1451be9a256 100644 --- a/crates/hir-def/src/expr_store.rs +++ b/crates/hir-def/src/expr_store.rs @@ -587,7 +587,7 @@ impl ExpressionStore { pub fn blocks<'a>( &'a self, db: &'a dyn SourceDatabase, - ) -> impl Iterator + 'a { + ) -> impl Iterator)> { self.expr_only .as_ref() .map(|it| &*it.block_scopes) diff --git a/crates/hir-def/src/expr_store/expander.rs b/crates/hir-def/src/expr_store/expander.rs index a974815cc642..700b2a2b7838 100644 --- a/crates/hir-def/src/expr_store/expander.rs +++ b/crates/hir-def/src/expr_store/expander.rs @@ -33,7 +33,7 @@ impl<'db> Expander<'db> { pub(super) fn new( db: &'db dyn SourceDatabase, current_file_id: HirFileId, - def_map: &'db DefMap, + def_map: &DefMap<'_>, ) -> Expander<'db> { let recursion_limit = def_map.recursion_limit(); let recursion_limit = if cfg!(test) { diff --git a/crates/hir-def/src/expr_store/lower.rs b/crates/hir-def/src/expr_store/lower.rs index 1e5d9c2a626e..96d7b62b9f96 100644 --- a/crates/hir-def/src/expr_store/lower.rs +++ b/crates/hir-def/src/expr_store/lower.rs @@ -451,7 +451,7 @@ pub struct ExprCollector<'db> { db: &'db dyn SourceDatabase, cfg_options: &'db CfgOptions, expander: Expander<'db>, - def_map: &'db DefMap, + def_map: &'db DefMap<'db>, local_def_map: &'db LocalDefMap, module: ModuleId, lowering_mode: LoweringMode, diff --git a/crates/hir-def/src/find_path.rs b/crates/hir-def/src/find_path.rs index daece7fc5d56..2478a3023d82 100644 --- a/crates/hir-def/src/find_path.rs +++ b/crates/hir-def/src/find_path.rs @@ -124,7 +124,7 @@ struct FindPathCtx<'db> { from: ModuleIdLt<'db>, from_crate: Crate, crate_root: ModuleIdLt<'db>, - from_def_map: &'db DefMap, + from_def_map: &'db DefMap<'db>, fuel: Cell, } @@ -175,7 +175,7 @@ fn find_path_inner(ctx: &FindPathCtx<'_>, item: ItemInNs, max_len: usize) -> Opt #[tracing::instrument(skip_all)] fn find_path_for_module<'db>( - ctx: &'db FindPathCtx<'db>, + ctx: &FindPathCtx<'db>, visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, module_id: ModuleIdLt<'db>, maybe_extern: bool, @@ -271,7 +271,7 @@ fn find_path_for_module<'db>( fn find_in_scope<'db>( db: &'db dyn SourceDatabase, - def_map: &DefMap, + def_map: &DefMap<'db>, from: ModuleIdLt<'db>, item: ItemInNs, ignore_local_imports: bool, @@ -286,11 +286,11 @@ fn find_in_scope<'db>( /// Returns single-segment path (i.e. without any prefix) if `item` is found in prelude and its /// name doesn't clash in current scope. -fn find_in_prelude( - db: &dyn SourceDatabase, - local_def_map: &DefMap, +fn find_in_prelude<'db>( + db: &'db dyn SourceDatabase, + local_def_map: &DefMap<'db>, item: ItemInNs, - from: ModuleIdLt<'_>, + from: ModuleIdLt<'db>, ) -> Option { let (prelude_module, _) = local_def_map.prelude()?; let prelude_def_map = prelude_module.def_map(db); @@ -321,7 +321,7 @@ fn find_in_prelude( fn is_kw_kind_relative_to_from( db: &dyn SourceDatabase, - def_map: &DefMap, + def_map: &DefMap<'_>, item: ModuleIdLt<'_>, from: ModuleIdLt<'_>, ) -> Option { @@ -345,7 +345,7 @@ fn is_kw_kind_relative_to_from( #[tracing::instrument(skip_all)] fn calculate_best_path<'db>( - ctx: &'db FindPathCtx<'db>, + ctx: &FindPathCtx<'db>, visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, item: ItemInNs, max_len: usize, @@ -385,7 +385,7 @@ fn calculate_best_path<'db>( } fn find_in_sysroot<'db>( - ctx: &'db FindPathCtx<'db>, + ctx: &FindPathCtx<'db>, visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, item: ItemInNs, max_len: usize, @@ -439,7 +439,7 @@ fn find_in_sysroot<'db>( } fn find_in_dep<'db>( - ctx: &'db FindPathCtx<'db>, + ctx: &FindPathCtx<'db>, visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, item: ItemInNs, max_len: usize, @@ -476,7 +476,7 @@ fn find_in_dep<'db>( } fn calculate_best_path_local<'db>( - ctx: &'db FindPathCtx<'db>, + ctx: &FindPathCtx<'db>, visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, item: ItemInNs, max_len: usize, @@ -547,9 +547,7 @@ impl Choice { Ordering::Less => return, Ordering::Equal => { other.path_text_len += name.as_str().len(); - if let Ordering::Less | Ordering::Equal = - current.path_text_len.cmp(&other.path_text_len) - { + if other.path_text_len >= current.path_text_len { return; } } @@ -575,7 +573,7 @@ fn path_kind_len(kind: PathKind) -> usize { /// Finds locations in `from.krate` from which `item` can be imported by `from`. fn find_local_import_locations<'db>( - ctx: &'db FindPathCtx<'db>, + ctx: &FindPathCtx<'db>, item: ItemInNs, visited_modules: &mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, mut cb: impl FnMut(&mut FxHashSet<(ItemInNs, ModuleIdLt<'db>)>, &Name, ModuleIdLt<'db>), diff --git a/crates/hir-def/src/item_scope.rs b/crates/hir-def/src/item_scope.rs index 61d578bfda7f..f4af5538daaa 100644 --- a/crates/hir-def/src/item_scope.rs +++ b/crates/hir-def/src/item_scope.rs @@ -10,6 +10,7 @@ use indexmap::map::Entry; use itertools::Itertools; use la_arena::Idx; use rustc_hash::{FxHashMap, FxHashSet}; +use salsa::SalsaValue; use smallvec::SmallVec; use span::Edition; use stdx::{format_to, impl_from}; @@ -121,8 +122,8 @@ impl PerNsGlobImports { } } -#[derive(Debug, Default, PartialEq, Eq)] -pub struct ItemScope { +#[derive(Debug, Default, PartialEq, Eq, SalsaValue)] +pub struct ItemScope<'db> { /// Defs visible in this scope. This includes `declarations`, but also /// imports. The imports belong to this module and can be resolved by using them on /// the `use_imports_*` fields. @@ -136,7 +137,7 @@ pub struct ItemScope { declarations: ThinVec, impls: ThinVec<(ImplId, /* trait impl */ bool)>, - builtin_derive_impls: ThinVec, + builtin_derive_impls: ThinVec>, extern_blocks: ThinVec, unnamed_consts: ThinVec, /// Traits imported via `use Trait as _;`. @@ -168,15 +169,15 @@ pub struct ItemScope { macro_invocations: FxHashMap, MacroCallId>, /// The derive macro invocations in this scope, keyed by the owner item over the actual derive attributes /// paired with the derive macro invocations for the specific attribute. - derive_macros: FxHashMap, SmallVec<[DeriveMacroInvocation; 1]>>, + derive_macros: FxHashMap, SmallVec<[DeriveMacroInvocation<'db>; 1]>>, } -#[derive(Debug, PartialEq, Eq)] -struct DeriveMacroInvocation { +#[derive(Debug, PartialEq, Eq, SalsaValue)] +struct DeriveMacroInvocation<'db> { attr_id: AttrId, /// The `#[derive]` call attr_call_id: MacroCallId, - derive_call_ids: SmallVec<[Option>; 4]>, + derive_call_ids: SmallVec<[Option>>; 4]>, } pub(crate) static BUILTIN_SCOPE: LazyLock> = LazyLock::new(|| { @@ -197,8 +198,8 @@ pub(crate) enum BuiltinShadowMode { /// Legacy macros can only be accessed through special methods like `get_legacy_macros`. /// Other methods will only resolve values, types and module scoped macros only. -impl ItemScope { - pub fn entries(&self) -> impl Iterator + '_ { +impl<'db> ItemScope<'db> { + pub fn entries(&self) -> impl Iterator { // FIXME: shadowing self.types .keys() @@ -210,21 +211,19 @@ impl ItemScope { .map(move |name| (name, self.get(name))) } - pub fn values(&self) -> impl Iterator)> + '_ { + pub fn values(&self) -> impl Iterator)> { self.values.iter().map(|(n, &i)| (n, i)) } - pub fn types( - &self, - ) -> impl Iterator)> + '_ { + pub fn types(&self) -> impl Iterator)> { self.types.iter().map(|(n, &i)| (n, i)) } - pub fn macros(&self) -> impl Iterator)> + '_ { + pub fn macros(&self) -> impl Iterator)> { self.macros.iter().map(|(n, &i)| (n, i)) } - pub fn imports(&self) -> impl Iterator + '_ { + pub fn imports(&self) -> impl Iterator { self.use_imports_types .keys() .copied() @@ -236,7 +235,7 @@ impl ItemScope { .dedup() } - pub fn fully_resolve_import(&self, db: &dyn SourceDatabase, mut import: ImportId) -> PerNs { + pub fn fully_resolve_import(&self, db: &'db dyn SourceDatabase, mut import: ImportId) -> PerNs { let mut res = PerNs::none(); let mut scope = self; @@ -287,39 +286,39 @@ impl ItemScope { res } - pub fn declarations(&self) -> impl Iterator + '_ { + pub fn declarations(&self) -> impl Iterator { self.declarations.iter().copied() } - pub fn extern_crate_decls(&self) -> impl ExactSizeIterator + '_ { + pub fn extern_crate_decls(&self) -> impl ExactSizeIterator { self.extern_crate_decls.iter().copied() } - pub fn extern_blocks(&self) -> impl Iterator + '_ { + pub fn extern_blocks(&self) -> impl Iterator { self.extern_blocks.iter().copied() } - pub fn use_decls(&self) -> impl ExactSizeIterator + '_ { + pub fn use_decls(&self) -> impl ExactSizeIterator { self.use_decls.iter().copied() } - pub fn impls(&self) -> impl ExactSizeIterator + '_ { + pub fn impls(&self) -> impl ExactSizeIterator { self.impls.iter().map(|&(id, _)| id) } - pub fn trait_impls(&self) -> impl Iterator + '_ { + pub fn trait_impls(&self) -> impl Iterator { self.impls.iter().filter(|&&(_, is_trait_impl)| is_trait_impl).map(|&(id, _)| id) } - pub fn inherent_impls(&self) -> impl Iterator + '_ { + pub fn inherent_impls(&self) -> impl Iterator { self.impls.iter().filter(|&&(_, is_trait_impl)| !is_trait_impl).map(|&(id, _)| id) } - pub fn builtin_derive_impls(&self) -> impl ExactSizeIterator + '_ { + pub fn builtin_derive_impls(&self) -> impl ExactSizeIterator> { self.builtin_derive_impls.iter().copied() } - pub fn all_macro_calls(&self) -> impl Iterator + '_ { + pub fn all_macro_calls(&self) -> impl Iterator { self.macro_invocations.values().copied().chain(self.attr_macros.values().copied()).chain( self.derive_macros.values().flat_map(|it| { it.iter().flat_map(|it| { @@ -329,19 +328,19 @@ impl ItemScope { ) } - pub(crate) fn modules_in_scope(&self) -> impl Iterator + '_ { + pub(crate) fn modules_in_scope(&self) -> impl Iterator { self.types.values().filter_map(|ns| match ns.def { ModuleDefId::ModuleId(module) => Some((module, ns.vis)), _ => None, }) } - pub fn unnamed_consts(&self) -> impl Iterator + '_ { + pub fn unnamed_consts(&self) -> impl Iterator { self.unnamed_consts.iter().copied() } /// Iterate over all legacy textual scoped macros visible at the end of the module - pub fn legacy_macros(&self) -> impl Iterator + '_ { + pub fn legacy_macros(&self) -> impl Iterator { self.legacy_macros.iter().map(|(name, def)| (name, &**def)) } @@ -420,7 +419,7 @@ impl ItemScope { } } - pub(crate) fn traits(&self) -> impl Iterator + '_ { + pub(crate) fn traits(&self) -> impl Iterator { self.types .values() .filter_map(|def| match def.def { @@ -430,7 +429,7 @@ impl ItemScope { .chain(self.unnamed_trait_imports.iter().map(|&(t, _)| t)) } - pub(crate) fn resolutions(&self) -> impl Iterator, PerNs)> + '_ { + pub(crate) fn resolutions(&self) -> impl Iterator, PerNs)> { self.entries().map(|(name, res)| (Some(name.clone()), res)).chain( self.unnamed_trait_imports.iter().map(|(tr, trait_)| { ( @@ -454,7 +453,7 @@ impl ItemScope { } } -impl ItemScope { +impl<'db> ItemScope<'db> { pub(crate) fn declare(&mut self, def: ModuleDefId) { self.declarations.push(def) } @@ -475,7 +474,7 @@ impl ItemScope { self.impls.push((imp, is_trait_impl)); } - pub(crate) fn define_builtin_derive_impl(&mut self, imp: BuiltinDeriveImplId) { + pub(crate) fn define_builtin_derive_impl(&mut self, imp: BuiltinDeriveImplId<'db>) { self.builtin_derive_impls.push(imp); } @@ -510,7 +509,7 @@ impl ItemScope { pub(crate) fn set_derive_macro_invoc( &mut self, adt: AstId, - call: Either, + call: Either>, id: AttrId, idx: usize, ) { @@ -530,7 +529,7 @@ impl ItemScope { adt: AstId, attr_id: AttrId, attr_call_id: MacroCallId, - mut derive_call_ids: SmallVec<[Option>; 4]>, + mut derive_call_ids: SmallVec<[Option>>; 4]>, ) { derive_call_ids.shrink_to_fit(); self.derive_macros.entry(adt).or_default().push(DeriveMacroInvocation { @@ -546,7 +545,11 @@ impl ItemScope { Item = ( AstId, impl Iterator< - Item = (AttrId, MacroCallId, &[Option>]), + Item = ( + AttrId, + MacroCallId, + &[Option>>], + ), >, ), > + '_ { @@ -865,7 +868,7 @@ impl ItemScope { } // These methods are a temporary measure only meant to be used by `DefCollector::push_res_and_update_glob_vis()`. -impl ItemScope { +impl<'db> ItemScope<'db> { pub(crate) fn update_visibility_types(&mut self, name: &Name, vis: Visibility) { let res = self.types.get_mut(name).expect("tried to update visibility of non-existent type"); diff --git a/crates/hir-def/src/lang_item.rs b/crates/hir-def/src/lang_item.rs index 534a9c31cd53..7048092d01c7 100644 --- a/crates/hir-def/src/lang_item.rs +++ b/crates/hir-def/src/lang_item.rs @@ -151,7 +151,7 @@ impl LangItems { fn resolve_core_trait( db: &dyn SourceDatabase, - core_def_map: &DefMap, + core_def_map: &DefMap<'_>, modules: &[Symbol], name: Symbol, ) -> Option { @@ -176,7 +176,7 @@ fn resolve_core_trait( fn resolve_core_macro( db: &dyn SourceDatabase, - core_def_map: &DefMap, + core_def_map: &DefMap<'_>, modules: &[Symbol], name: Symbol, ) -> Option { @@ -397,7 +397,7 @@ macro_rules! language_item_table { } } - fn fill_non_lang_core_items(&mut self, db: &dyn SourceDatabase, core_def_map: &DefMap) { + fn fill_non_lang_core_items(&mut self, db: &dyn SourceDatabase, core_def_map: &DefMap<'_>) { $( self.$non_lang_trait = resolve_core_trait(db, core_def_map, &[ $(sym::$non_lang_trait_module),* ], sym::$non_lang_trait); )* $( self.$non_lang_macro_field = resolve_core_macro(db, core_def_map, &[ $(sym::$non_lang_macro_module),* ], sym::$non_lang_macro); )* } diff --git a/crates/hir-def/src/lib.rs b/crates/hir-def/src/lib.rs index 288fefd8ea10..79a54fe5bdfd 100644 --- a/crates/hir-def/src/lib.rs +++ b/crates/hir-def/src/lib.rs @@ -354,7 +354,7 @@ pub struct BuiltinDeriveImplLoc { pub derive_index: u32, } -#[salsa::interned(debug, unsafe(no_lifetime), revisions = usize::MAX)] +#[salsa::interned(debug)] #[derive(PartialOrd, Ord)] pub struct BuiltinDeriveImplId { #[returns(ref)] @@ -564,7 +564,7 @@ impl<'db> ModuleIdLt<'db> { unsafe { std::mem::transmute(self) } } - pub fn def_map(self, db: &'db dyn SourceDatabase) -> &'db DefMap { + pub fn def_map(self, db: &'db dyn SourceDatabase) -> &'db DefMap<'db> { match self.block(db) { Some(block) => block_def_map(db, block), None => crate_def_map(db, self.krate(db)), @@ -574,7 +574,7 @@ impl<'db> ModuleIdLt<'db> { pub(crate) fn local_def_map( self, db: &'db dyn SourceDatabase, - ) -> (&'db DefMap, &'db LocalDefMap) { + ) -> (&'db DefMap<'db>, &'db LocalDefMap) { match self.block(db) { Some(block) => (block_def_map(db, block), self.only_local_def_map(db)), None => { @@ -588,7 +588,7 @@ impl<'db> ModuleIdLt<'db> { crate_local_def_map(db, self.krate(db)).local(db) } - pub fn crate_def_map(self, db: &'db dyn SourceDatabase) -> &'db DefMap { + pub fn crate_def_map(self, db: &'db dyn SourceDatabase) -> &'db DefMap<'db> { crate_def_map(db, self.krate(db)) } @@ -742,7 +742,9 @@ pub enum AdtId { impl_from!(StructId, UnionId, EnumId for AdtId); /// A macro -#[derive(Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)] +#[derive( + Debug, PartialOrd, Ord, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype, salsa::SalsaValue, +)] pub enum MacroId { Macro2Id(Macro2Id), MacroRulesId(MacroRulesId), @@ -1241,7 +1243,7 @@ impl HasModule for BuiltinDeriveImplLoc { } } -impl HasModule for BuiltinDeriveImplId { +impl HasModule for BuiltinDeriveImplId<'_> { #[inline] fn module(&self, db: &dyn SourceDatabase) -> ModuleId { self.loc(db).module(db) diff --git a/crates/hir-def/src/macro_expansion_tests/mod.rs b/crates/hir-def/src/macro_expansion_tests/mod.rs index 188f57f7dda7..f55b83efd8ef 100644 --- a/crates/hir-def/src/macro_expansion_tests/mod.rs +++ b/crates/hir-def/src/macro_expansion_tests/mod.rs @@ -260,7 +260,7 @@ pub fn identity_when_valid(_attr: TokenStream, item: TokenStream) -> TokenStream fn resolve_macro_call_id( db: &dyn SourceDatabase, - def_map: &DefMap, + def_map: &DefMap<'_>, ast_id: AstId, ast_ptr: InFile>, ) -> Option { diff --git a/crates/hir-def/src/nameres.rs b/crates/hir-def/src/nameres.rs index c1daad5b3f6a..fc871f26147b 100644 --- a/crates/hir-def/src/nameres.rs +++ b/crates/hir-def/src/nameres.rs @@ -69,6 +69,7 @@ use hir_expand::{ use intern::{Symbol, sym}; use itertools::Itertools; use rustc_hash::FxHashMap; +use salsa::SalsaValue; use span::{Edition, FileAstId, FileId, ROOT_ERASED_FILE_AST_ID}; use stdx::format_to; use syntax::{AstNode, SmolStr, SyntaxNode, ToSmolStr, ast}; @@ -168,8 +169,8 @@ impl LocalDefMap { /// computed by the `crate_def_map` query. Additionally, every block expression introduces the /// opportunity to write arbitrary item and module hierarchies, and thus gets its own `DefMap` that /// is computed by the `block_def_map` query. -#[derive(Debug, PartialEq, Eq)] -pub struct DefMap { +#[derive(Debug, PartialEq, Eq, SalsaValue)] +pub struct DefMap<'db> { /// The crate this `DefMap` belongs to. krate: Crate, /// When this is a block def map, this will hold the block id of the block and module that @@ -177,7 +178,7 @@ pub struct DefMap { block: Option, pub root: ModuleId, /// The modules and their data declared in this crate. - pub modules: ModulesMap, + pub modules: ModulesMap<'db>, /// The prelude module for this crate. This either comes from an import /// marked with the `prelude_import` attribute, or (in the normal case) from /// a dependency (`std` or `core`). @@ -193,8 +194,10 @@ pub struct DefMap { /// Tracks which custom derives are in scope for an item, to allow resolution of derive helper /// attributes. // FIXME: Figure out a better way for the IDE layer to resolve these? - derive_helpers_in_scope: - FxHashMap, Vec<(Name, MacroId, Either)>>, + derive_helpers_in_scope: FxHashMap< + AstId, + Vec<(Name, MacroId, Either>)>, + >, /// A mapping from [`hir_expand::MacroDefId`] to [`crate::MacroId`]. pub macro_def_to_macro_id: FxHashMap, @@ -272,18 +275,18 @@ struct BlockInfo { parent: ModuleId, } -impl std::ops::Index> for DefMap { - type Output = ModuleData; +impl<'db> std::ops::Index> for DefMap<'db> { + type Output = ModuleData<'db>; - fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData { + fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData<'db> { self.modules .get(&unsafe { id.to_static() }) .unwrap_or_else(|| panic!("ModuleId not found in ModulesMap {:#?}: {id:#?}", self.root)) } } -impl std::ops::IndexMut for DefMap { - fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData { +impl<'db> std::ops::IndexMut for DefMap<'db> { + fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData<'db> { &mut self.modules[id] } } @@ -362,8 +365,8 @@ impl ModuleOrigin { } } -#[derive(Debug, PartialEq, Eq)] -pub struct ModuleData { +#[derive(Debug, PartialEq, Eq, SalsaValue)] +pub struct ModuleData<'db> { /// Where does this module come from? pub origin: ModuleOrigin, /// Declared visibility of this module. @@ -373,11 +376,11 @@ pub struct ModuleData { /// [`None`] for block modules because they are always its `DefMap`'s root. pub parent: Option, pub children: FxIndexMap, - pub scope: ItemScope, + pub scope: ItemScope<'db>, } #[inline] -pub fn crate_def_map(db: &dyn SourceDatabase, crate_id: Crate) -> &DefMap { +pub fn crate_def_map(db: &dyn SourceDatabase, crate_id: Crate) -> &DefMap<'_> { crate_local_def_map(db, crate_id).def_map(db) } @@ -385,7 +388,7 @@ pub fn crate_def_map(db: &dyn SourceDatabase, crate_id: Crate) -> &DefMap { pub(crate) struct DefMapPair<'db> { #[tracked] #[returns(ref)] - pub(crate) def_map: DefMap, + pub(crate) def_map: DefMap<'db>, #[returns(ref)] pub(crate) local: LocalDefMap, } @@ -425,7 +428,7 @@ pub(crate) fn crate_local_def_map(db: &dyn SourceDatabase, crate_id: Crate) -> D } #[salsa::tracked(returns(ref))] -pub fn block_def_map<'db>(db: &'db dyn SourceDatabase, block_id: BlockIdLt<'db>) -> DefMap { +pub fn block_def_map<'db>(db: &'db dyn SourceDatabase, block_id: BlockIdLt<'db>) -> DefMap<'db> { let block_id = unsafe { block_id.to_static() }; let ast_id = block_id.ast_id(db); let module = unsafe { block_id.module(db).to_static() }; @@ -453,7 +456,7 @@ pub fn block_def_map<'db>(db: &'db dyn SourceDatabase, block_id: BlockIdLt<'db>) def_map } -impl DefMap { +impl<'db> DefMap<'db> { pub fn edition(&self) -> Edition { self.data.edition } @@ -462,9 +465,9 @@ impl DefMap { db: &dyn SourceDatabase, krate: Crate, crate_data: Arc, - module_data: ModuleData, + module_data: ModuleData<'db>, block: Option, - ) -> DefMap { + ) -> DefMap<'db> { let mut modules = ModulesMap::new(); let root = unsafe { ModuleIdLt::new( @@ -518,7 +521,7 @@ impl DefMap { } } -impl DefMap { +impl<'db> DefMap<'db> { /// Returns all modules in the crate that are associated with the given file. pub fn modules_for_file<'a>( &'a self, @@ -533,7 +536,7 @@ impl DefMap { .map(|(id, _)| id) } - pub fn modules(&self) -> impl Iterator + '_ { + pub fn modules(&self) -> impl Iterator)> + '_ { self.modules.iter() } @@ -557,7 +560,7 @@ impl DefMap { pub fn derive_helpers_in_scope( &self, id: AstId, - ) -> Option<&[(Name, MacroId, Either)]> { + ) -> Option<&[(Name, MacroId, Either>)]> { self.derive_helpers_in_scope.get(&id.map(|it| it.upcast())).map(Deref::deref) } @@ -635,7 +638,7 @@ impl DefMap { // FIXME: this can use some more human-readable format (ideally, an IR // even), as this should be a great debugging aid. - pub fn dump(&self, db: &dyn SourceDatabase) -> String { + pub fn dump(&self, db: &'db dyn SourceDatabase) -> String { let mut buf = String::new(); let mut current_map = self; while let Some(block) = current_map.block { @@ -646,10 +649,10 @@ impl DefMap { go(&mut buf, db, current_map, "crate", current_map.root); return buf; - fn go( + fn go<'db>( buf: &mut String, db: &dyn SourceDatabase, - map: &DefMap, + map: &DefMap<'db>, path: &str, module: ModuleId, ) { @@ -667,7 +670,7 @@ impl DefMap { } } -impl DefMap { +impl<'db> DefMap<'db> { pub(crate) fn block_id(&self) -> Option { self.block.map(|block| block.block) } @@ -683,7 +686,7 @@ impl DefMap { pub(crate) fn resolve_path( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, original_module: ModuleId, path: &ModPath, shadow: BuiltinShadowMode, @@ -706,7 +709,7 @@ impl DefMap { pub(crate) fn resolve_path_locally( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, original_module: ModuleId, path: &ModPath, shadow: BuiltinShadowMode, @@ -727,11 +730,11 @@ impl DefMap { /// /// If `f` returns `Some(val)`, iteration is stopped and `Some(val)` is returned. If `f` returns /// `None`, iteration continues. - pub(crate) fn with_ancestor_maps<'db, T>( + pub(crate) fn with_ancestor_maps( &self, db: &'db dyn SourceDatabase, local_mod: ModuleIdLt<'db>, - f: &mut dyn FnMut(&DefMap, ModuleIdLt<'db>) -> Option, + f: &mut dyn FnMut(&DefMap<'db>, ModuleIdLt<'db>) -> Option, ) -> Option { if let Some(it) = f(self, local_mod) { return Some(it); @@ -749,7 +752,7 @@ impl DefMap { } } -impl ModuleData { +impl<'db> ModuleData<'db> { pub(crate) fn new( origin: ModuleOrigin, visibility: Visibility, @@ -885,51 +888,51 @@ fn sub_namespace_match( } /// A newtype wrapper around `FxHashMap` that implements `IndexMut`. -#[derive(Debug, PartialEq, Eq)] -pub struct ModulesMap { - inner: FxIndexMap, +#[derive(Debug, PartialEq, Eq, SalsaValue)] +pub struct ModulesMap<'db> { + inner: FxIndexMap>, } -impl ModulesMap { +impl<'db> ModulesMap<'db> { fn new() -> Self { Self { inner: FxIndexMap::default() } } - fn iter(&self) -> impl Iterator + '_ { + fn iter(&self) -> impl Iterator)> + '_ { self.inner.iter().map(|(&k, v)| (k, v)) } - fn iter_mut(&mut self) -> impl Iterator + '_ { + fn iter_mut(&mut self) -> impl Iterator)> + '_ { self.inner.iter_mut().map(|(&k, v)| (k, v)) } } -impl Deref for ModulesMap { - type Target = FxIndexMap; +impl<'db> Deref for ModulesMap<'db> { + type Target = FxIndexMap>; fn deref(&self) -> &Self::Target { &self.inner } } -impl DerefMut for ModulesMap { +impl<'db> DerefMut for ModulesMap<'db> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } } -impl Index> for ModulesMap { - type Output = ModuleData; +impl<'db> Index> for ModulesMap<'db> { + type Output = ModuleData<'db>; - fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData { + fn index(&self, id: ModuleIdLt<'_>) -> &ModuleData<'db> { self.inner .get(&unsafe { id.to_static() }) .unwrap_or_else(|| panic!("ModuleId not found in ModulesMap: {id:#?}")) } } -impl IndexMut for ModulesMap { - fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData { +impl<'db> IndexMut for ModulesMap<'db> { + fn index_mut(&mut self, id: ModuleId) -> &mut ModuleData<'db> { self.inner .get_mut(&id) .unwrap_or_else(|| panic!("ModuleId not found in ModulesMap: {id:#?}")) diff --git a/crates/hir-def/src/nameres/assoc.rs b/crates/hir-def/src/nameres/assoc.rs index 8dea9a4eda1d..92ea0466bc4f 100644 --- a/crates/hir-def/src/nameres/assoc.rs +++ b/crates/hir-def/src/nameres/assoc.rs @@ -135,7 +135,7 @@ impl ImplItems { struct AssocItemCollector<'db> { db: &'db dyn SourceDatabase, module_id: ModuleId, - def_map: &'db DefMap, + def_map: &'db DefMap<'db>, local_def_map: &'db LocalDefMap, ast_id_map: &'db AstIdMap, span_map: SpanMap<'db>, diff --git a/crates/hir-def/src/nameres/attr_resolution.rs b/crates/hir-def/src/nameres/attr_resolution.rs index 411b80fb6a03..91dd7d3082d1 100644 --- a/crates/hir-def/src/nameres/attr_resolution.rs +++ b/crates/hir-def/src/nameres/attr_resolution.rs @@ -25,12 +25,12 @@ pub enum ResolvedAttr { Other, } -impl DefMap { +impl<'db> DefMap<'db> { /// This cannot be used to resolve items that allow derives. pub(crate) fn resolve_attr_macro( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, original_module: ModuleId, ast_id: AstIdWithPath, attr: &Attr, diff --git a/crates/hir-def/src/nameres/collector.rs b/crates/hir-def/src/nameres/collector.rs index 97450c8d692a..34ed92d7b55d 100644 --- a/crates/hir-def/src/nameres/collector.rs +++ b/crates/hir-def/src/nameres/collector.rs @@ -59,12 +59,12 @@ use crate::{ const GLOB_RECURSION_LIMIT: usize = 100; const FIXED_POINT_LIMIT: usize = 8192; -pub(super) fn collect_defs( - db: &dyn SourceDatabase, - def_map: DefMap, +pub(super) fn collect_defs<'db>( + db: &'db dyn SourceDatabase, + def_map: DefMap<'db>, tree_id: TreeId, - crate_local_def_map: Option<&LocalDefMap>, -) -> (DefMap, LocalDefMap) { + crate_local_def_map: Option<&'db LocalDefMap>, +) -> (DefMap<'db>, LocalDefMap) { let krate = &def_map.krate.data(db); let cfg_options = def_map.krate.cfg_options(db); @@ -230,7 +230,7 @@ struct DeferredBuiltinDerive { /// Walks the tree of module recursively struct DefCollector<'db> { db: &'db dyn SourceDatabase, - def_map: DefMap, + def_map: DefMap<'db>, local_def_map: LocalDefMap, /// Set only in case of blocks. crate_local_def_map: Option<&'db LocalDefMap>, @@ -1330,7 +1330,7 @@ impl<'db> DefCollector<'db> { MacroSubNs::Attr } }; - let resolver = |def_map: &DefMap, path: &_| { + let resolver = |def_map: &DefMap<'db>, path: &_| { let resolved_res = def_map.resolve_path_fp_with_macro( self.crate_local_def_map.unwrap_or(&self.local_def_map), self.db, @@ -1768,7 +1768,7 @@ impl<'db> DefCollector<'db> { .collect(item_tree.top_level_items(), container); } - fn finish(mut self) -> (DefMap, LocalDefMap) { + fn finish(mut self) -> (DefMap<'db>, LocalDefMap) { // Emit diagnostics for all remaining unexpanded macros. let _p = tracing::info_span!("DefCollector::finish").entered(); @@ -1879,7 +1879,7 @@ struct ModCollector<'a, 'db> { mod_dir: ModDir, } -impl ModCollector<'_, '_> { +impl<'db> ModCollector<'_, 'db> { fn collect_in_top_module(&mut self, items: &[ModItemId]) { self.collect(items, self.module_id.into()) } @@ -1899,7 +1899,7 @@ impl ModCollector<'_, '_> { deferred_derives: &mut FxHashMap<_, Vec>, ast_id: FileAstId, id: AdtId, - def_map: &mut DefMap| { + def_map: &mut DefMap<'db>| { let ast_id = InFile::new(file_id, ast_id.upcast()); let Some(deferred_derives) = deferred_derives.remove(&ast_id.upcast()) else { return; @@ -1946,7 +1946,7 @@ impl ModCollector<'_, '_> { None, ) }; - let resolve_vis = |def_map: &DefMap, local_def_map: &LocalDefMap, visibility| { + let resolve_vis = |def_map: &DefMap<'db>, local_def_map: &LocalDefMap, visibility| { def_map .resolve_visibility(local_def_map, db, module_id, visibility, false) .unwrap_or(Visibility::Public) diff --git a/crates/hir-def/src/nameres/path_resolution.rs b/crates/hir-def/src/nameres/path_resolution.rs index 150b4eeb60f2..8106473e8e69 100644 --- a/crates/hir-def/src/nameres/path_resolution.rs +++ b/crates/hir-def/src/nameres/path_resolution.rs @@ -91,11 +91,11 @@ impl PerNs { } } -impl DefMap { +impl<'db> DefMap<'db> { pub(crate) fn resolve_visibility( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, // module to import to original_module: ModuleId, // pub(path) @@ -155,7 +155,7 @@ impl DefMap { pub(super) fn resolve_path_fp_with_macro( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, mode: ResolveMode, // module to import to mut original_module: ModuleId, @@ -243,7 +243,7 @@ impl DefMap { pub(super) fn resolve_path_fp_with_macro_single( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, mode: ResolveMode, original_module: ModuleId, path: &ModPath, @@ -371,7 +371,7 @@ impl DefMap { pub(super) fn resolve_path_fp_in_all_preludes( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, mode: ResolveMode, original_module: ModuleId, path: &ModPath, @@ -448,7 +448,7 @@ impl DefMap { fn resolve_remaining_segments<'a>( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, mode: ResolveMode, mut segments: impl Iterator, mut curr_per_ns: PerNs, @@ -630,7 +630,7 @@ impl DefMap { fn resolve_name_in_module( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, module: ModuleId, name: &Name, shadow: BuiltinShadowMode, @@ -691,7 +691,7 @@ impl DefMap { fn resolve_name_in_all_preludes( &self, local_def_map: &LocalDefMap, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, name: &Name, ) -> PerNs { // Resolve in: @@ -749,7 +749,7 @@ impl DefMap { from_crate_root.or_else(from_extern_prelude) } - fn resolve_in_prelude(&self, db: &dyn SourceDatabase, name: &Name) -> PerNs { + fn resolve_in_prelude(&self, db: &'db dyn SourceDatabase, name: &Name) -> PerNs { if let Some((prelude, _use)) = self.prelude { let def_map = if prelude.krate(db) == self.krate { self } else { prelude.def_map(db) }; def_map[prelude].scope.get(name) @@ -761,11 +761,11 @@ impl DefMap { /// Given a block module, returns its nearest non-block module and the `DefMap` it belongs to. #[inline] -fn adjust_to_nearest_non_block_module<'db>( +fn adjust_to_nearest_non_block_module<'db, 'dm>( db: &'db dyn SourceDatabase, - mut def_map: &'db DefMap, + mut def_map: &'dm DefMap<'db>, mut local_id: ModuleId, -) -> (&'db DefMap, ModuleId) { +) -> (&'dm DefMap<'db>, ModuleId) { if def_map.root_module_id() != local_id { // if we aren't the root, we are either not a block module, or a non-block module inside a // block def map. diff --git a/crates/hir-def/src/nameres/tests.rs b/crates/hir-def/src/nameres/tests.rs index 08d98dff33d3..de1b8df195ea 100644 --- a/crates/hir-def/src/nameres/tests.rs +++ b/crates/hir-def/src/nameres/tests.rs @@ -14,7 +14,7 @@ use crate::{ fn compute_crate_def_map( #[rust_analyzer::rust_fixture] ra_fixture: &str, - cb: impl FnOnce(&DefMap), + cb: impl FnOnce(&DefMap<'_>), ) { let db = TestDB::with_files(ra_fixture); let krate = db.fetch_test_crate(); diff --git a/crates/hir-def/src/resolver.rs b/crates/hir-def/src/resolver.rs index 5b11f5ff8bbb..4b9f40cc520f 100644 --- a/crates/hir-def/src/resolver.rs +++ b/crates/hir-def/src/resolver.rs @@ -52,7 +52,7 @@ pub struct Resolver<'db> { #[derive(Clone)] struct ModuleItemMap<'db> { - def_map: &'db DefMap, + def_map: &'db DefMap<'db>, local_def_map: &'db LocalDefMap, module_id: ModuleId, } @@ -134,7 +134,11 @@ pub enum LifetimeNs { impl<'db> Resolver<'db> { /// Resolve known trait from std, like `std::futures::Future` - pub fn resolve_known_trait(&self, db: &dyn SourceDatabase, path: &ModPath) -> Option { + pub fn resolve_known_trait( + &self, + db: &'db dyn SourceDatabase, + path: &ModPath, + ) -> Option { let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?; match res { ModuleDefId::TraitId(it) => Some(it), @@ -145,7 +149,7 @@ impl<'db> Resolver<'db> { /// Resolve known struct from std, like `std::boxed::Box` pub fn resolve_known_struct( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &ModPath, ) -> Option { let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?; @@ -156,7 +160,11 @@ impl<'db> Resolver<'db> { } /// Resolve known enum from std, like `std::result::Result` - pub fn resolve_known_enum(&self, db: &dyn SourceDatabase, path: &ModPath) -> Option { + pub fn resolve_known_enum( + &self, + db: &'db dyn SourceDatabase, + path: &ModPath, + ) -> Option { let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?; match res { ModuleDefId::AdtId(AdtId::EnumId(it)) => Some(it), @@ -164,13 +172,17 @@ impl<'db> Resolver<'db> { } } - pub fn resolve_module_path_in_items(&self, db: &dyn SourceDatabase, path: &ModPath) -> PerNs { + pub fn resolve_module_path_in_items( + &self, + db: &'db dyn SourceDatabase, + path: &ModPath, + ) -> PerNs { self.resolve_module_path(db, path, BuiltinShadowMode::Module) } pub fn resolve_path_in_type_ns( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &Path, ) -> Option<(TypeNs, Option, Option)> { self.resolve_path_in_type_ns_with_prefix_info(db, path).map( @@ -182,7 +194,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_in_type_ns_with_prefix_info( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &Path, ) -> Option<( TypeNs, @@ -293,7 +305,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_in_type_ns_fully( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &Path, ) -> Option { let (res, unresolved, _) = self.resolve_path_in_type_ns(db, path)?; @@ -305,7 +317,7 @@ impl<'db> Resolver<'db> { pub fn resolve_visibility( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, visibility: &RawVisibility, ) -> Option { match visibility { @@ -331,7 +343,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_in_value_ns( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &Path, hygiene_id: HygieneId, ) -> Option { @@ -352,7 +364,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_in_value_ns_with_prefix_info( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &Path, mut hygiene_id: HygieneId, ) -> Option<(ResolveValueResult, ResolvePathResultPrefixInfo, Visibility)> { @@ -519,7 +531,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_in_value_ns_fully( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &Path, hygiene: HygieneId, ) -> Option { @@ -531,7 +543,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_as_macro( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &ModPath, expected_macro_kind: Option, ) -> Option { @@ -551,7 +563,7 @@ impl<'db> Resolver<'db> { pub fn resolve_path_as_macro_def( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &ModPath, expected_macro_kind: Option, ) -> Option { @@ -686,7 +698,7 @@ impl<'db> Resolver<'db> { .map(|(name, module_id)| (name.clone(), module_id.0)) } - pub fn traits_in_scope(&self, db: &dyn SourceDatabase) -> FxHashSet { + pub fn traits_in_scope(&self, db: &'db dyn SourceDatabase) -> FxHashSet { // FIXME(trait_alias): Trait alias brings aliased traits in scope! Note that supertraits of // aliased traits are NOT brought in scope (unless also aliased). let mut traits = FxHashSet::default(); @@ -730,7 +742,7 @@ impl<'db> Resolver<'db> { self.item_scope_().2 } - pub fn item_scope(&self) -> &ItemScope { + pub fn item_scope(&self) -> &ItemScope<'db> { let (def_map, _, local_id) = self.item_scope_(); &def_map[local_id].scope } @@ -739,17 +751,17 @@ impl<'db> Resolver<'db> { self.module_scope.def_map.krate() } - pub fn def_map(&self) -> &DefMap { + pub fn def_map(&self) -> &DefMap<'db> { self.item_scope_().0 } #[inline] - pub fn top_level_def_map(&self) -> &'db DefMap { + pub fn top_level_def_map(&self) -> &'db DefMap<'db> { self.module_scope.def_map } #[inline] - pub fn is_visible(&self, db: &dyn SourceDatabase, visibility: Visibility) -> bool { + pub fn is_visible(&self, db: &'db dyn SourceDatabase, visibility: Visibility) -> bool { visibility.is_visible_from_def_map( db, self.module_scope.def_map, @@ -796,7 +808,7 @@ impl<'db> Resolver<'db> { /// (that contains `current_name` path) change from `renamed` to some another variable (returned as `Some`). pub fn rename_will_conflict_with_another_variable( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, current_name: &Name, current_name_as_path: &ModPath, mut hygiene_id: HygieneId, @@ -845,7 +857,7 @@ impl<'db> Resolver<'db> { /// from some other variable (returned as `Some`) to `renamed`. pub fn rename_will_conflict_with_renamed( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, name: &Name, name_as_path: &ModPath, mut hygiene_id: HygieneId, @@ -1009,7 +1021,7 @@ impl<'db> Resolver<'db> { fn resolve_module_path( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &ModPath, shadow: BuiltinShadowMode, ) -> PerNs { @@ -1024,7 +1036,7 @@ impl<'db> Resolver<'db> { } /// The innermost block scope that contains items or the module scope that contains this resolver. - fn item_scope_(&self) -> (&DefMap, &LocalDefMap, ModuleId) { + fn item_scope_(&self) -> (&DefMap<'db>, &LocalDefMap, ModuleId) { self.scopes() .find_map(|scope| match scope { Scope::BlockScope(m) => Some((m.def_map, m.local_def_map, m.module_id)), @@ -1050,7 +1062,7 @@ pub enum ScopeDef { } impl<'db> Scope<'db> { - fn process_names(&self, acc: &mut ScopeNames, db: &'db dyn SourceDatabase) { + fn process_names(&self, acc: &mut ScopeNames, db: &dyn SourceDatabase) { match self { Scope::BlockScope(m) => { m.def_map[m.module_id].scope.entries().for_each(|(name, def)| { @@ -1165,7 +1177,7 @@ impl<'db> Resolver<'db> { fn push_block_scope( self, - def_map: &'db DefMap, + def_map: &'db DefMap<'db>, local_def_map: &'db LocalDefMap, module_id: ModuleId, ) -> Resolver<'db> { @@ -1222,7 +1234,7 @@ impl<'db> ModuleItemMap<'db> { fn resolve_path_in_type_ns( &self, - db: &dyn SourceDatabase, + db: &'db dyn SourceDatabase, path: &ModPath, ) -> Option<( TypeNs, @@ -1243,7 +1255,7 @@ impl<'db> ModuleItemMap<'db> { } } -fn to_value_ns(per_ns: PerNs, def_map: &DefMap) -> Option<(ValueNs, Visibility)> { +fn to_value_ns(per_ns: PerNs, def_map: &DefMap<'_>) -> Option<(ValueNs, Visibility)> { let (def, vis) = per_ns.take_values_full().map(|res| (res.def, res.vis)).or_else(|| { let Some(MacrosItem { def: MacroId::ProcMacroId(proc_macro), vis, .. }) = per_ns.take_macros_full() diff --git a/crates/hir-def/src/test_db.rs b/crates/hir-def/src/test_db.rs index 4433522c1832..576f186c60aa 100644 --- a/crates/hir-def/src/test_db.rs +++ b/crates/hir-def/src/test_db.rs @@ -196,7 +196,7 @@ impl TestDB { } /// Finds the smallest/innermost module in `def_map` containing `position`. - fn mod_at_position(&self, def_map: &DefMap, position: FilePosition) -> ModuleId { + fn mod_at_position(&self, def_map: &DefMap<'_>, position: FilePosition) -> ModuleId { let mut size = None; let mut res = def_map.root; for (module, data) in def_map.modules() { @@ -243,7 +243,11 @@ impl TestDB { res } - fn block_at_position(&self, def_map: &DefMap, position: FilePosition) -> Option<&DefMap> { + fn block_at_position<'db>( + &'db self, + def_map: &DefMap<'_>, + position: FilePosition, + ) -> Option<&'db DefMap<'db>> { // Find the smallest (innermost) function in `def_map` containing the cursor. let mut size = None; let mut fn_def = None; @@ -307,8 +311,8 @@ impl TestDB { let mut containing_blocks = scopes.scope_chain(Some(scope)).filter_map(|scope| scopes.block(scope)); - if let Some(block) = containing_blocks.next().map(|block| block_def_map(self, block)) { - return Some(block); + if let Some(block) = containing_blocks.next() { + return Some(block_def_map(self, block)); } } diff --git a/crates/hir-def/src/visibility.rs b/crates/hir-def/src/visibility.rs index 2a406cf01fad..24aace5e258b 100644 --- a/crates/hir-def/src/visibility.rs +++ b/crates/hir-def/src/visibility.rs @@ -26,9 +26,9 @@ pub enum Visibility { } impl Visibility { - pub fn resolve( - db: &dyn SourceDatabase, - resolver: &crate::resolver::Resolver<'_>, + pub fn resolve<'db>( + db: &'db dyn SourceDatabase, + resolver: &crate::resolver::Resolver<'db>, raw_vis: &RawVisibility, ) -> Self { // we fall back to public visibility (i.e. fail open) if the path can't be resolved @@ -65,7 +65,7 @@ impl Visibility { pub(crate) fn is_visible_from_def_map<'db>( self, db: &'db dyn SourceDatabase, - def_map: &'db DefMap, + def_map: &DefMap<'db>, from_module: ModuleIdLt<'db>, ) -> bool { if cfg!(debug_assertions) { @@ -94,7 +94,7 @@ impl Visibility { fn is_visible_from_def_map_<'db>( db: &'db dyn SourceDatabase, - def_map: &'db DefMap, + def_map: &DefMap<'db>, mut to_module: ModuleIdLt<'db>, mut from_module: ModuleIdLt<'db>, ) -> bool { @@ -125,24 +125,18 @@ impl Visibility { // from_module needs to be a descendant of to_module let mut def_map = def_map; - let mut parent_arc; loop { if from_module == to_module { return true; } - match def_map[from_module].parent { - Some(parent) => from_module = parent, - None => { - match def_map.parent() { - Some(module) => { - parent_arc = module.def_map(db); - def_map = parent_arc; - from_module = module; - } - // Reached the root module, nothing left to check. - None => return false, - } - } + if let Some(parent) = def_map[from_module].parent { + from_module = parent + } else if let Some(module) = def_map.parent() { + def_map = module.def_map(db); + from_module = module; + } else { + // Reached the root module, nothing left to check. + return false; } } } @@ -155,7 +149,7 @@ impl Visibility { self, db: &dyn SourceDatabase, other: Visibility, - def_map: &DefMap, + def_map: &DefMap<'_>, ) -> Option { match (self, other) { (_, Visibility::Public) | (Visibility::Public, _) => Some(Visibility::Public), @@ -221,7 +215,7 @@ impl Visibility { self, db: &dyn SourceDatabase, other: Visibility, - def_map: &DefMap, + def_map: &DefMap<'_>, ) -> Option { match (self, other) { (vis, Visibility::Public) | (Visibility::Public, vis) => Some(vis), diff --git a/crates/hir-expand/src/files.rs b/crates/hir-expand/src/files.rs index 3524e0cb090c..2817e433e593 100644 --- a/crates/hir-expand/src/files.rs +++ b/crates/hir-expand/src/files.rs @@ -18,7 +18,7 @@ use crate::{ /// * `InFile` -- syntax node in a file /// * `InFile` -- ast node in a file /// * `InFile` -- offset in a file -#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] +#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, salsa::SalsaValue)] pub struct InFileWrapper { pub file_id: FileKind, pub value: T, diff --git a/crates/hir-expand/src/lib.rs b/crates/hir-expand/src/lib.rs index f7ac3f1c0269..0441f723d19a 100644 --- a/crates/hir-expand/src/lib.rs +++ b/crates/hir-expand/src/lib.rs @@ -1571,7 +1571,7 @@ impl From for span::MacroCallId { } } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, salsa::Supertype, salsa::SalsaValue)] pub enum HirFileId { FileId(EditionedFileId), MacroFile(MacroCallId), diff --git a/crates/hir-expand/src/name.rs b/crates/hir-expand/src/name.rs index 7968adabbccf..7e676da692d4 100644 --- a/crates/hir-expand/src/name.rs +++ b/crates/hir-expand/src/name.rs @@ -16,7 +16,7 @@ use syntax::{ast, format_smolstr}; /// This is because we want to show (in completions etc.) names as raw depending on the needs /// of the current crate, for example if it is edition 2021 complete `gen` even if the defining /// crate is in edition 2024 and wrote `r#gen`, and the opposite holds as well. -#[derive(Clone, PartialEq, Eq, Hash)] +#[derive(Clone, PartialEq, Eq, Hash, salsa::SalsaValue)] pub struct Name { symbol: Symbol, // If you are making this carry actual hygiene, beware that the special handling for variables and labels diff --git a/crates/hir-ty/src/builtin_derive.rs b/crates/hir-ty/src/builtin_derive.rs index f82fc940ff63..64fbea51e593 100644 --- a/crates/hir-ty/src/builtin_derive.rs +++ b/crates/hir-ty/src/builtin_derive.rs @@ -55,7 +55,7 @@ fn trait_args(trait_: BuiltinDeriveImplTrait, self_ty: Ty<'_>) -> GenericArgs<'_ pub(crate) fn generics_of<'db>( interner: DbInterner<'db>, - id: BuiltinDeriveImplId, + id: BuiltinDeriveImplId<'_>, ) -> Generics<'db> { let db = interner.db; let loc = id.loc(db); @@ -82,7 +82,7 @@ pub(crate) fn generics_of<'db>( } } -pub fn generic_params_count(db: &dyn HirDatabase, id: BuiltinDeriveImplId) -> usize { +pub fn generic_params_count(db: &dyn HirDatabase, id: BuiltinDeriveImplId<'_>) -> usize { let loc = id.loc(db); let adt_params = GenericParams::of(db, loc.adt.into()); let extra_params_count = match loc.trait_ { @@ -102,7 +102,7 @@ pub fn generic_params_count(db: &dyn HirDatabase, id: BuiltinDeriveImplId) -> us pub fn impl_trait<'db>( interner: DbInterner<'db>, - id: BuiltinDeriveImplId, + id: BuiltinDeriveImplId<'_>, ) -> EarlyBinder<'db, TraitRef<'db>> { let db = interner.db; let loc = id.loc(db); @@ -154,7 +154,7 @@ pub fn impl_trait<'db>( } #[salsa::tracked(returns(ref))] -pub fn predicates(db: &dyn HirDatabase, impl_: BuiltinDeriveImplId) -> GenericPredicates { +pub fn predicates(db: &dyn HirDatabase, impl_: BuiltinDeriveImplId<'_>) -> GenericPredicates { let loc = impl_.loc(db); let generic_params = GenericParams::of(db, loc.adt.into()); let interner = DbInterner::new_with(db, loc.module(db).krate(db)); @@ -232,7 +232,7 @@ pub fn predicates(db: &dyn HirDatabase, impl_: BuiltinDeriveImplId) -> GenericPr } /// Not cached in a query, currently used in `hir` only. If you need this in `hir-ty` consider introducing a query. -pub fn param_env<'db>(interner: DbInterner<'db>, id: BuiltinDeriveImplId) -> ParamEnv<'db> { +pub fn param_env<'db>(interner: DbInterner<'db>, id: BuiltinDeriveImplId<'_>) -> ParamEnv<'db> { let predicates = predicates(interner.db, id); crate::lower::param_env_from_predicates(interner, predicates) } diff --git a/crates/hir-ty/src/db.rs b/crates/hir-ty/src/db.rs index d005d62abda5..62dc265833cb 100644 --- a/crates/hir-ty/src/db.rs +++ b/crates/hir-ty/src/db.rs @@ -130,7 +130,7 @@ pub trait HirDatabase: SourceDatabase + 'static { env: ParamEnvAndCrate<'db>, func: FunctionId, fn_subst: GenericArgs<'db>, - ) -> (Either, GenericArgs<'db>) + ) -> (Either, BuiltinDeriveImplMethod)>, GenericArgs<'db>) { let db = self.as_dyn(); crate::method_resolution::lookup_impl_method_query(db, env, func, fn_subst) diff --git a/crates/hir-ty/src/lower.rs b/crates/hir-ty/src/lower.rs index 7b28689912e5..23498a1187e3 100644 --- a/crates/hir-ty/src/lower.rs +++ b/crates/hir-ty/src/lower.rs @@ -212,7 +212,7 @@ pub struct TyLoweringContext<'db, 'a> { types: &'db crate::next_solver::DefaultAny<'db>, lang_items: &'db LangItems, resolver: &'a Resolver<'db>, - store: &'db ExpressionStore, + store: &'a ExpressionStore, def: ExpressionStoreOwnerId, generic_def: GenericDefId, generics: &'a OnceCell>, @@ -236,7 +236,7 @@ impl<'db, 'a> TyLoweringContext<'db, 'a> { pub fn new( db: &'db dyn HirDatabase, resolver: &'a Resolver<'db>, - store: &'db ExpressionStore, + store: &'a ExpressionStore, def: ExpressionStoreOwnerId, generic_def: GenericDefId, generics: &'a OnceCell>, diff --git a/crates/hir-ty/src/method_resolution.rs b/crates/hir-ty/src/method_resolution.rs index 07ff9ac1936c..3e918b9de083 100644 --- a/crates/hir-ty/src/method_resolution.rs +++ b/crates/hir-ty/src/method_resolution.rs @@ -107,7 +107,7 @@ pub enum MethodError<'db> { NoMatch, /// Multiple methods might apply. - Ambiguity(Vec), + Ambiguity(Vec>), /// Found an applicable method, but it is not visible. PrivateMatch(Pick<'db>), @@ -122,8 +122,8 @@ pub enum MethodError<'db> { // A pared down enum describing just the places from which a method // candidate can arise. Used for error reporting only. #[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum CandidateSource { - Impl(AnyImplId), +pub enum CandidateSource<'db> { + Impl(AnyImplId<'db>), Trait(TraitId), } @@ -417,7 +417,7 @@ pub(crate) fn lookup_impl_method_query<'db>( env: ParamEnvAndCrate<'db>, func: FunctionId, fn_subst: GenericArgs<'db>, -) -> (Either, GenericArgs<'db>) { +) -> (Either, BuiltinDeriveImplMethod)>, GenericArgs<'db>) { let interner = DbInterner::new_with(db, env.krate); let infcx = interner.infer_ctxt().build(TypingMode::PostAnalysis); @@ -461,8 +461,10 @@ fn lookup_impl_assoc_item_for_trait_ref<'db>( trait_ref: TraitRef<'db>, env: ParamEnv<'db>, name: &Name, -) -> Option<(Either, GenericArgs<'db>)> -{ +) -> Option<( + Either, BuiltinDeriveImplMethod)>, + GenericArgs<'db>, +)> { let (impl_id, impl_subst) = find_matching_impl(infcx, env, trait_ref)?; let impl_id = match impl_id { AnyImplId::ImplId(it) => it, @@ -487,7 +489,7 @@ pub(crate) fn find_matching_impl<'db>( infcx: &InferCtxt<'db>, env: ParamEnv<'db>, trait_ref: TraitRef<'db>, -) -> Option<(AnyImplId, GenericArgs<'db>)> { +) -> Option<(AnyImplId<'db>, GenericArgs<'db>)> { let trait_ref = infcx.at(&ObligationCause::dummy(), env).deeply_normalize(trait_ref).ok()?; let obligation = Obligation::new(infcx.interner, ObligationCause::dummy(), env, trait_ref); @@ -592,7 +594,7 @@ impl<'db> InherentImpls<'db> { } impl<'db> InherentImpls<'db> { - fn collect_def_map(db: &'db dyn HirDatabase, def_map: &'db DefMap) -> Self { + 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 @@ -604,7 +606,7 @@ impl<'db> InherentImpls<'db> { fn collect<'db>( db: &'db dyn HirDatabase, - def_map: &DefMap, + def_map: &DefMap<'_>, map: &mut FxHashMap, Vec>, ) { for (_module_id, module_data) in def_map.modules() { @@ -653,13 +655,14 @@ struct OneTraitImpls<'db> { // It's safe to retain, as it only contains `SolverDefId<'db>` (which is `SalsaValue`), // and no `&'db` references. #[salsa_value(unsafe(prove(SolverDefId<'db>: SalsaValue)))] - non_blanket_impls: FxHashMap, (Box<[ImplId]>, Box<[BuiltinDeriveImplId]>)>, + non_blanket_impls: + FxHashMap, (Box<[ImplId]>, Box<[BuiltinDeriveImplId<'db>]>)>, blanket_impls: Box<[ImplId]>, } #[derive(Default)] struct OneTraitImplsBuilder<'db> { - non_blanket_impls: FxHashMap, (Vec, Vec)>, + non_blanket_impls: FxHashMap, (Vec, Vec>)>, blanket_impls: Vec, } @@ -713,7 +716,7 @@ impl<'db> TraitImpls<'db> { } impl<'db> TraitImpls<'db> { - fn collect_def_map(db: &'db dyn HirDatabase, def_map: &DefMap) -> Self { + fn collect_def_map(db: &'db dyn HirDatabase, def_map: &DefMap<'db>) -> 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); @@ -726,7 +729,7 @@ impl<'db> TraitImpls<'db> { fn collect<'db>( db: &'db dyn HirDatabase, - def_map: &DefMap, + def_map: &DefMap<'db>, lang_items: &LangItems, map: &mut FxHashMap>, ) { @@ -803,11 +806,11 @@ impl<'db> TraitImpls<'db> { }) } - pub fn for_trait_and_self_ty( - &'db self, + pub fn for_trait_and_self_ty<'a>( + &'a self, trait_: TraitId, self_ty: &SimplifiedType<'db>, - ) -> (&'db [ImplId], &'db [BuiltinDeriveImplId]) { + ) -> (&'a [ImplId], &'a [BuiltinDeriveImplId<'db>]) { self.map .get(&trait_) .and_then(|map| map.non_blanket_impls.get(self_ty)) @@ -818,7 +821,7 @@ impl<'db> TraitImpls<'db> { pub fn for_trait( &self, trait_: TraitId, - mut callback: impl FnMut(Either<&[ImplId], &[BuiltinDeriveImplId]>), + mut callback: impl FnMut(Either<&[ImplId], &[BuiltinDeriveImplId<'db>]>), ) { if let Some(impls) = self.map.get(&trait_) { callback(Either::Left(&impls.blanket_impls)); @@ -832,7 +835,7 @@ impl<'db> TraitImpls<'db> { pub fn for_self_ty( &self, self_ty: &SimplifiedType<'db>, - mut callback: impl FnMut(Either<&[ImplId], &[BuiltinDeriveImplId]>), + mut callback: impl FnMut(Either<&[ImplId], &[BuiltinDeriveImplId<'db>]>), ) { for for_trait in self.map.values() { if let Some(for_ty) = for_trait.non_blanket_impls.get(self_ty) { diff --git a/crates/hir-ty/src/method_resolution/probe.rs b/crates/hir-ty/src/method_resolution/probe.rs index 0a47e031b720..e5896ad05fe7 100644 --- a/crates/hir-ty/src/method_resolution/probe.rs +++ b/crates/hir-ty/src/method_resolution/probe.rs @@ -64,7 +64,7 @@ struct ProbeContext<'a, 'db, Choice> { /// Collects near misses when the candidate functions are missing a `self` keyword and is only /// used for error reporting - static_candidates: Vec, + static_candidates: Vec>, choice: Choice, } @@ -1520,7 +1520,11 @@ impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> { /// Used for ambiguous method call error reporting. Uses probing that throws away the result internally, /// so do not use to make a decision that may lead to a successful compilation. - fn candidate_source(&self, candidate: &Candidate<'db>, self_ty: Ty<'db>) -> CandidateSource { + fn candidate_source( + &self, + candidate: &Candidate<'db>, + self_ty: Ty<'db>, + ) -> CandidateSource<'db> { match candidate.kind { InherentImplCandidate { impl_def_id, .. } => CandidateSource::Impl(impl_def_id.into()), ObjectCandidate(trait_ref) | WhereClauseCandidate(trait_ref) => { @@ -1555,7 +1559,7 @@ impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> { } } - fn candidate_source_from_pick(&self, pick: &Pick<'db>) -> CandidateSource { + fn candidate_source_from_pick(&self, pick: &Pick<'db>) -> CandidateSource<'db> { match pick.kind { InherentImplPick(impl_) => CandidateSource::Impl(impl_.into()), ObjectPick(trait_) | TraitPick(trait_) => CandidateSource::Trait(trait_), @@ -2005,7 +2009,7 @@ impl<'a, 'db, Choice: ProbeChoice<'db>> ProbeContext<'a, 'db, Choice> { // -- but this could be overcome. } - fn record_static_candidate(&mut self, source: CandidateSource) { + fn record_static_candidate(&mut self, source: CandidateSource<'db>) { self.static_candidates.push(source); } diff --git a/crates/hir-ty/src/next_solver/def_id.rs b/crates/hir-ty/src/next_solver/def_id.rs index c45387b6894b..b1b559afb058 100644 --- a/crates/hir-ty/src/next_solver/def_id.rs +++ b/crates/hir-ty/src/next_solver/def_id.rs @@ -35,7 +35,7 @@ pub enum SolverDefId<'db> { ConstId(ConstId), FunctionId(FunctionId), ImplId(ImplId), - BuiltinDeriveImplId(BuiltinDeriveImplId), + BuiltinDeriveImplId(BuiltinDeriveImplId<'db>), StaticId(StaticId), AnonConstId(AnonConstId<'db>), TraitId(TraitId), @@ -128,7 +128,7 @@ impl_from!( ConstId, FunctionId, ImplId, - BuiltinDeriveImplId, + BuiltinDeriveImplId<'db>, StaticId, AnonConstId<'db>, TraitId, @@ -644,26 +644,26 @@ impl<'db> inherent::DefId> for CallableIdWrapper { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum AnyImplId { +pub enum AnyImplId<'db> { ImplId(ImplId), - BuiltinDeriveImplId(BuiltinDeriveImplId), + BuiltinDeriveImplId(BuiltinDeriveImplId<'db>), } -impl_from!(ImplId, BuiltinDeriveImplId for AnyImplId); +impl_from!(impl<'db> ImplId, BuiltinDeriveImplId<'db> for AnyImplId<'db>); -impl<'db> From for SolverDefId<'db> { +impl<'db> From> for SolverDefId<'db> { #[inline] - fn from(value: AnyImplId) -> SolverDefId<'db> { + fn from(value: AnyImplId<'db>) -> SolverDefId<'db> { match value { AnyImplId::ImplId(it) => it.into(), AnyImplId::BuiltinDeriveImplId(it) => it.into(), } } } -impl TryFrom> for AnyImplId { +impl<'db> TryFrom> for AnyImplId<'db> { type Error = (); #[inline] - fn try_from(value: SolverDefId<'_>) -> Result { + fn try_from(value: SolverDefId<'db>) -> Result { match value { SolverDefId::ImplId(it) => Ok(it.into()), SolverDefId::BuiltinDeriveImplId(it) => Ok(it.into()), @@ -671,7 +671,7 @@ impl TryFrom> for AnyImplId { } } } -impl<'db> inherent::DefId> for AnyImplId { +impl<'db> inherent::DefId> for AnyImplId<'db> { fn as_local(self) -> Option> { Some(self.into()) } diff --git a/crates/hir-ty/src/next_solver/infer/select.rs b/crates/hir-ty/src/next_solver/infer/select.rs index 1462f292058e..38686ceda22e 100644 --- a/crates/hir-ty/src/next_solver/infer/select.rs +++ b/crates/hir-ty/src/next_solver/infer/select.rs @@ -250,7 +250,7 @@ impl<'db, N> ImplSource<'db, N> { pub(crate) struct ImplSourceUserDefinedData<'db, N> { #[type_visitable(ignore)] #[type_foldable(identity)] - pub(crate) impl_def_id: AnyImplId, + pub(crate) impl_def_id: AnyImplId<'db>, pub(crate) args: GenericArgs<'db>, pub(crate) nested: Vec, } diff --git a/crates/hir-ty/src/next_solver/interner.rs b/crates/hir-ty/src/next_solver/interner.rs index 05e155962a31..6c66e1370c0c 100644 --- a/crates/hir-ty/src/next_solver/interner.rs +++ b/crates/hir-ty/src/next_solver/interner.rs @@ -908,7 +908,7 @@ impl<'db> Interner for DbInterner<'db> { type CoroutineClosureId = CoroutineClosureIdWrapper<'db>; type CoroutineId = CoroutineIdWrapper<'db>; type AdtId = AdtIdWrapper; - type ImplId = AnyImplId; + type ImplId = AnyImplId<'db>; type UnevaluatedConstId = GeneralConstIdWrapper<'db>; type TraitAssocTyId = TraitAssocTyId; type TraitAssocConstId = TraitAssocConstId; @@ -1628,7 +1628,7 @@ impl<'db> Interner for DbInterner<'db> { ) -> R { 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<'db>| { let type_block = simp.def().and_then(|def_id| { let module = match def_id { SolverDefId::AdtId(AdtId::StructId(id)) => id.module(self.db), @@ -2379,7 +2379,7 @@ TrivialTypeTraversalImpls! { InherentAssocConstId, InherentAssocTermId, OpaqueTyIdWrapper<'_>, - AnyImplId, + AnyImplId<'_>, GeneralConstIdWrapper<'_>, Safety, Span, diff --git a/crates/hir-ty/src/next_solver/solver.rs b/crates/hir-ty/src/next_solver/solver.rs index 5486a565815d..2bd34cbfff1b 100644 --- a/crates/hir-ty/src/next_solver/solver.rs +++ b/crates/hir-ty/src/next_solver/solver.rs @@ -177,7 +177,7 @@ impl<'db> SolverDelegate for SolverContext<'db> { &self, _goal_trait_ref: rustc_type_ir::TraitRef, trait_assoc_def_id: TraitAssocTermId, - impl_id: AnyImplId, + impl_id: AnyImplId<'_>, ) -> FetchEligibleAssocItemResponse { let AnyImplId::ImplId(impl_id) = impl_id else { // Builtin derive traits don't have type/consts assoc items. diff --git a/crates/hir-ty/src/tests.rs b/crates/hir-ty/src/tests.rs index c19a1f27af96..bb4b51100cb8 100644 --- a/crates/hir-ty/src/tests.rs +++ b/crates/hir-ty/src/tests.rs @@ -553,7 +553,7 @@ fn infer_with_mismatches(content: &str, include_mismatches: bool) -> String { pub(crate) fn visit_module( db: &TestDB, - crate_def_map: &DefMap, + crate_def_map: &DefMap<'_>, module_id: ModuleId, cb: &mut dyn FnMut(ModuleDefId), ) { @@ -581,8 +581,8 @@ pub(crate) fn visit_module( fn visit_scope( db: &TestDB, - crate_def_map: &DefMap, - scope: &ItemScope, + crate_def_map: &DefMap<'_>, + scope: &ItemScope<'_>, cb: &mut dyn FnMut(ModuleDefId), ) { for decl in scope.declarations() { diff --git a/crates/hir-ty/src/traits.rs b/crates/hir-ty/src/traits.rs index c485af5fdd88..b8fda912bf3c 100644 --- a/crates/hir-ty/src/traits.rs +++ b/crates/hir-ty/src/traits.rs @@ -175,7 +175,7 @@ pub enum WherePredicateEvaluation { pub fn where_predicate_must_hold<'db>( db: &'db dyn HirDatabase, resolver: &Resolver<'db>, - store: &'db ExpressionStore, + store: &ExpressionStore, def: ExpressionStoreOwnerId, generic_def: GenericDefId, env: ParamEnvAndCrate<'db>, @@ -247,7 +247,11 @@ pub fn where_predicate_must_hold<'db>( } } -pub fn is_inherent_impl_coherent(db: &dyn HirDatabase, def_map: &DefMap, impl_id: ImplId) -> bool { +pub fn is_inherent_impl_coherent( + db: &dyn HirDatabase, + def_map: &DefMap<'_>, + impl_id: ImplId, +) -> bool { let self_ty = db.impl_self_ty(impl_id).instantiate_identity().skip_norm_wip(); let self_ty = self_ty.kind(); let impl_allowed = match self_ty { diff --git a/crates/hir/src/attrs.rs b/crates/hir/src/attrs.rs index 210d6bde1f54..ae476084c892 100644 --- a/crates/hir/src/attrs.rs +++ b/crates/hir/src/attrs.rs @@ -227,7 +227,7 @@ impl_has_attrs![ (ExternCrateDecl, ExternCrateId), ]; -impl HasAttrs for Function { +impl HasAttrs for Function<'_> { fn attr_id(self, _db: &dyn HirDatabase) -> AttrsOwner { match self.id { crate::AnyFunctionId::FunctionId(id) => AttrsOwner::AttrDef(id.into()), @@ -236,7 +236,7 @@ impl HasAttrs for Function { } } -impl HasAttrs for Impl { +impl HasAttrs for Impl<'_> { fn attr_id(self, _db: &dyn HirDatabase) -> AttrsOwner { match self.id { hir_ty::next_solver::AnyImplId::ImplId(id) => AttrsOwner::AttrDef(id.into()), @@ -277,7 +277,7 @@ impl HasAttrs for GenericParam { } } -impl HasAttrs for AssocItem { +impl HasAttrs for AssocItem<'_> { #[inline] fn attr_id(self, db: &dyn HirDatabase) -> AttrsOwner { match self { @@ -303,23 +303,23 @@ impl HasAttrs for Field { } /// Resolves the item `link` points to in the scope of `def`. -pub fn resolve_doc_path_on( - db: &dyn HirDatabase, +pub fn resolve_doc_path_on<'db>( + db: &'db dyn HirDatabase, def: impl HasAttrs + Copy, link: &str, ns: Option, is_inner_doc: IsInnerDoc, -) -> Option { +) -> Option> { resolve_doc_path_on_(db, link, def.attr_id(db), ns, is_inner_doc) } -fn resolve_doc_path_on_( - db: &dyn HirDatabase, +fn resolve_doc_path_on_<'db>( + db: &'db dyn HirDatabase, link: &str, attr_id: AttrsOwner, ns: Option, is_inner_doc: IsInnerDoc, -) -> Option { +) -> Option> { let resolver = match attr_id { AttrsOwner::AttrDef(AttrDefId::ModuleId(it)) => { if is_inner_doc.yes() { @@ -369,13 +369,13 @@ fn resolve_doc_path_on_( } } -fn resolve_assoc_or_field( - db: &dyn HirDatabase, - resolver: Resolver<'_>, +fn resolve_assoc_or_field<'db>( + db: &'db dyn HirDatabase, + resolver: Resolver<'db>, path: ModPath, name: Name, ns: Option, -) -> Option { +) -> Option> { let path = Path::from_known_path_with_no_generic(path); let base_def = resolver.resolve_path_in_type_ns_fully(db, &path)?; @@ -472,7 +472,7 @@ fn resolve_assoc_item<'db>( ty: &Type<'db>, name: &Name, ns: Option, -) -> Option { +) -> Option> { ty.iterate_assoc_items(db, move |assoc_item| { if assoc_item.name(db)? != *name { return None; @@ -483,11 +483,11 @@ fn resolve_assoc_item<'db>( fn resolve_impl_trait_item<'db>( db: &'db dyn HirDatabase, - resolver: Resolver<'_>, + resolver: Resolver<'db>, ty: &Type<'db>, name: &Name, ns: Option, -) -> Option { +) -> Option> { let krate = ty.krate(db); let param_env = ty.param_env(db); let traits_in_scope = resolver.traits_in_scope(db); @@ -528,17 +528,17 @@ fn resolve_field( def: Variant, name: Name, ns: Option, -) -> Option { +) -> Option> { if let Some(Namespace::Types | Namespace::Macros) = ns { return None; } def.fields(db).into_iter().find(|f| f.name(db) == name).map(DocLinkDef::Field) } -fn as_module_def_if_namespace_matches( - assoc_item: AssocItem, +fn as_module_def_if_namespace_matches<'db>( + assoc_item: AssocItem<'db>, ns: Option, -) -> Option { +) -> Option> { let (def, expected_ns) = match assoc_item { AssocItem::Function(it) => (ModuleDef::Function(it), Namespace::Values), AssocItem::Const(it) => (ModuleDef::Const(it), Namespace::Values), diff --git a/crates/hir/src/diagnostics.rs b/crates/hir/src/diagnostics.rs index f6df18a6fb57..a64bac518a13 100644 --- a/crates/hir/src/diagnostics.rs +++ b/crates/hir/src/diagnostics.rs @@ -117,7 +117,7 @@ diagnostics![AnyDiagnostic<'db> -> InactiveCode, IncoherentImpl, IncorrectCase, - IncorrectGenericsLen, + IncorrectGenericsLen<'db>, IncorrectGenericsOrder, InferVarsNotAllowed, InvalidCast<'db>, @@ -143,16 +143,16 @@ diagnostics![AnyDiagnostic<'db> -> MismatchedArrayPatLen, DuplicateField, PatternArgInExternFn, - PrivateAssocItem, + PrivateAssocItem<'db>, PrivateField, RemoveTrailingReturn, RemoveUnnecessaryElse, UnusedMustUse<'db>, ReplaceFilterMapNextWithFindMap, TraitImplIncorrectSafety, - TraitImplMissingAssocItems, + TraitImplMissingAssocItems<'db>, TraitImplOrphan, - TraitImplRedundantAssocItems, + TraitImplRedundantAssocItems<'db>, TypedHole<'db>, TypeMismatch<'db>, UndeclaredLabel, @@ -169,8 +169,8 @@ diagnostics![AnyDiagnostic<'db> -> GenericArgsProhibited, ParenthesizedGenericArgsWithoutFnTrait, BadRtn, - MissingLifetime, - ElidedLifetimesInPath, + MissingLifetime<'db>, + ElidedLifetimesInPath<'db>, TypeMustBeKnown<'db>, UnionExprMustHaveExactlyOneField, UnionPatMustHaveExactlyOneField, @@ -290,9 +290,9 @@ pub struct DuplicateField { } #[derive(Debug)] -pub struct PrivateAssocItem { +pub struct PrivateAssocItem<'db> { pub expr_or_pat: InFile, - pub item: AssocItem, + pub item: AssocItem<'db>, } #[derive(Debug)] @@ -384,7 +384,7 @@ pub struct UnresolvedMethodCall<'db> { pub receiver: Type<'db>, pub name: Name, pub field_with_same_name: Option>, - pub assoc_func_with_same_name: Option, + pub assoc_func_with_same_name: Option>, } #[derive(Debug)] @@ -493,18 +493,18 @@ pub struct TraitImplIncorrectSafety { } #[derive(Debug, PartialEq, Eq)] -pub struct TraitImplMissingAssocItems { +pub struct TraitImplMissingAssocItems<'db> { pub file_id: HirFileId, pub impl_: AstPtr, - pub missing: Vec<(Name, AssocItem)>, + pub missing: Vec<(Name, AssocItem<'db>)>, } #[derive(Debug, PartialEq, Eq)] -pub struct TraitImplRedundantAssocItems { +pub struct TraitImplRedundantAssocItems<'db> { pub file_id: HirFileId, pub trait_: Trait, pub impl_: AstPtr, - pub assoc_item: (Name, AssocItem), + pub assoc_item: (Name, AssocItem<'db>), } #[derive(Debug)] @@ -559,29 +559,29 @@ pub struct InferVarsNotAllowed { } #[derive(Debug)] -pub struct IncorrectGenericsLen { +pub struct IncorrectGenericsLen<'db> { /// Points at the name if there are no generics. pub generics_or_segment: InFile>>, pub kind: IncorrectGenericsLenKind, pub provided: u32, pub expected: u32, - pub def: GenericDef, + pub def: GenericDef<'db>, } #[derive(Debug)] -pub struct MissingLifetime { +pub struct MissingLifetime<'db> { /// Points at the name if there are no generics. pub generics_or_segment: InFile>>, pub expected: u32, - pub def: GenericDef, + pub def: GenericDef<'db>, } #[derive(Debug)] -pub struct ElidedLifetimesInPath { +pub struct ElidedLifetimesInPath<'db> { /// Points at the name if there are no generics. pub generics_or_segment: InFile>>, pub expected: u32, - pub def: GenericDef, + pub def: GenericDef<'db>, pub hard_error: bool, } diff --git a/crates/hir/src/display.rs b/crates/hir/src/display.rs index 61eda80fb487..ad49761ab6f7 100644 --- a/crates/hir/src/display.rs +++ b/crates/hir/src/display.rs @@ -39,7 +39,7 @@ use crate::{ fn write_builtin_derive_impl_method<'db>( f: &mut HirFormatter<'_, 'db>, - impl_: BuiltinDeriveImplId, + impl_: BuiltinDeriveImplId<'db>, method: BuiltinDeriveImplMethod, ) -> Result { let db = f.db; @@ -85,7 +85,7 @@ fn write_builtin_derive_impl_method<'db>( Ok(()) } -impl<'db> HirDisplay<'db> for Function { +impl<'db> HirDisplay<'db> for Function<'db> { fn hir_fmt(&self, f: &mut HirFormatter<'_, 'db>) -> Result { let id = match self.id { AnyFunctionId::FunctionId(id) => id, @@ -303,7 +303,7 @@ fn write_impl_header<'db>(impl_: ImplId, f: &mut HirFormatter<'_, 'db>) -> Resul Ok(()) } -impl<'db> HirDisplay<'db> for SelfParam { +impl<'db> HirDisplay<'db> for SelfParam<'_> { fn hir_fmt(&self, f: &mut HirFormatter<'_, 'db>) -> Result { let func = match self.func.id { AnyFunctionId::FunctionId(id) => id, diff --git a/crates/hir/src/from_id.rs b/crates/hir/src/from_id.rs index 9b07aa494e44..6e1228d1ba06 100644 --- a/crates/hir/src/from_id.rs +++ b/crates/hir/src/from_id.rs @@ -4,8 +4,8 @@ //! are splitting the hir. use hir_def::{ - AdtId, AssocItemId, BuiltinDeriveImplId, DefWithBodyId, EnumVariantId, ExpressionStoreOwnerId, - FieldId, FunctionId, GenericDefId, GenericParamId, ImplId, ModuleDefId, VariantId, + AdtId, AssocItemId, BuiltinDeriveImplId, DefWithBodyId, ExpressionStoreOwnerId, FieldId, + FunctionId, GenericDefId, GenericParamId, ImplId, ModuleDefId, VariantId, hir::{BindingId, LabelId}, item_scope::ItemInNs as ItemInNsId, }; @@ -13,8 +13,8 @@ use hir_ty::next_solver::AnyImplId; use stdx::impl_from; use crate::{ - Adt, AnyFunctionId, AssocItem, BuiltinType, DefWithBody, EnumVariant, ExpressionStoreOwner, - Field, Function, GenericDef, GenericParam, Impl, ItemInNs, Label, Local, ModuleDef, Variant, + Adt, AnyFunctionId, AssocItem, BuiltinType, DefWithBody, ExpressionStoreOwner, Field, Function, + GenericDef, GenericParam, Impl, ItemInNs, Label, Local, ModuleDef, Variant, }; macro_rules! from_id { @@ -42,16 +42,35 @@ from_id![ (hir_def::TraitId, crate::Trait), (hir_def::StaticId, crate::Static), (hir_def::ConstId, crate::Const), - (crate::AnyFunctionId, crate::Function), - (hir_ty::next_solver::AnyImplId, crate::Impl), (hir_def::TypeOrConstParamId, crate::TypeOrConstParam), (hir_def::TypeParamId, crate::TypeParam), (hir_def::ConstParamId, crate::ConstParam), (hir_def::LifetimeParamId, crate::LifetimeParam), (hir_def::MacroId, crate::Macro), + (hir_def::EnumVariantId, crate::EnumVariant), (hir_def::ExternCrateId, crate::ExternCrateDecl), (hir_def::ExternBlockId, crate::ExternBlock), ]; +impl<'db> From> for crate::Function<'db> { + fn from(id: crate::AnyFunctionId<'db>) -> Self { + Self { id } + } +} +impl<'db> From> for crate::AnyFunctionId<'db> { + fn from(ty: crate::Function<'db>) -> Self { + ty.id + } +} +impl<'db> From> for crate::Impl<'db> { + fn from(id: hir_ty::next_solver::AnyImplId<'db>) -> Self { + Self { id } + } +} +impl<'db> From> for hir_ty::next_solver::AnyImplId<'db> { + fn from(ty: crate::Impl<'db>) -> Self { + ty.id + } +} impl_from!(AdtId { StructId => Struct, UnionId => Union, EnumId => Enum } for Adt); impl_from!(Adt { Struct => StructId, Union => UnionId, Enum => EnumId } for AdtId); @@ -76,19 +95,8 @@ impl_from!( for GenericParamId ); -impl From for EnumVariant { - fn from(id: EnumVariantId) -> Self { - EnumVariant { id } - } -} - -impl From for EnumVariantId { - fn from(def: EnumVariant) -> Self { - def.id - } -} - impl_from!( + impl<'db> ModuleDefId { ModuleId => Module, FunctionId => Function, @@ -101,12 +109,12 @@ impl_from!( BuiltinType => BuiltinType, MacroId => Macro, } - for ModuleDef + for ModuleDef<'db> ); -impl TryFrom for ModuleDefId { +impl TryFrom> for ModuleDefId { type Error = (); - fn try_from(id: ModuleDef) -> Result { + fn try_from(id: ModuleDef<'_>) -> Result { Ok(match id { ModuleDef::Module(it) => ModuleDefId::ModuleId(it.into()), ModuleDef::Function(it) => match it.id { @@ -125,9 +133,9 @@ impl TryFrom for ModuleDefId { } } -impl TryFrom for DefWithBodyId { +impl TryFrom> for DefWithBodyId { type Error = (); - fn try_from(def: DefWithBody) -> Result { + fn try_from(def: DefWithBody<'_>) -> Result { Ok(match def { DefWithBody::Function(it) => match it.id { AnyFunctionId::FunctionId(it) => it.into(), @@ -141,28 +149,31 @@ impl TryFrom for DefWithBodyId { } impl_from!( + impl<'db> DefWithBodyId { FunctionId => Function, StaticId => Static, ConstId => Const, VariantId => EnumVariant, } - for DefWithBody + for DefWithBody<'db> ); impl_from!( + impl<'db> AssocItemId { FunctionId => Function, TypeAliasId => TypeAlias, ConstId => Const } - for AssocItem + for AssocItem<'db> ); -impl TryFrom for GenericDefId { +impl TryFrom> for GenericDefId { type Error = (); - fn try_from(def: GenericDef) -> Result { + fn try_from(def: GenericDef<'_>) -> Result { def.id().ok_or(()) } } impl_from!( + impl<'db> GenericDefId { FunctionId => Function, AdtId => Adt, @@ -172,7 +183,7 @@ impl_from!( ConstId => Const, StaticId => Static, } - for GenericDef + for GenericDef<'db> ); impl From for GenericDefId { @@ -202,9 +213,9 @@ impl From for Field { } } -impl TryFrom for GenericDefId { +impl TryFrom> for GenericDefId { type Error = (); - fn try_from(item: AssocItem) -> Result { + fn try_from(item: AssocItem<'_>) -> Result { Ok(match item { AssocItem::Function(f) => match f.id { AnyFunctionId::FunctionId(it) => it.into(), @@ -228,11 +239,11 @@ impl From<(ExpressionStoreOwnerId, LabelId)> for Label { } } -impl_from!(ItemInNsId { Types => Types, Values => Values, Macros => Macros } for ItemInNs); +impl_from!(impl<'db> ItemInNsId { Types => Types, Values => Values, Macros => Macros } for ItemInNs<'db>); -impl TryFrom for hir_def::item_scope::ItemInNs { +impl TryFrom> for hir_def::item_scope::ItemInNs { type Error = (); - fn try_from(it: ItemInNs) -> Result { + fn try_from(it: ItemInNs<'_>) -> Result { Ok(match it { ItemInNs::Types(it) => Self::Types(it.try_into()?), ItemInNs::Values(it) => Self::Values(it.try_into()?), @@ -253,28 +264,28 @@ impl From for hir_def::builtin_type::BuiltinType { } } -impl From for crate::Impl { +impl<'db> From for crate::Impl<'db> { fn from(value: hir_def::ImplId) -> Self { crate::Impl { id: AnyImplId::ImplId(value) } } } -impl From for crate::Impl { - fn from(value: BuiltinDeriveImplId) -> Self { +impl<'db> From> for crate::Impl<'db> { + fn from(value: BuiltinDeriveImplId<'db>) -> Self { crate::Impl { id: AnyImplId::BuiltinDeriveImplId(value) } } } -impl From for crate::Function { +impl<'db> From for crate::Function<'db> { fn from(value: hir_def::FunctionId) -> Self { crate::Function { id: AnyFunctionId::FunctionId(value) } } } -impl TryFrom for ExpressionStoreOwnerId { +impl<'db> TryFrom> for ExpressionStoreOwnerId { type Error = (); - fn try_from(v: ExpressionStoreOwner) -> Result { + fn try_from(v: ExpressionStoreOwner<'db>) -> Result { match v { ExpressionStoreOwner::Signature(generic_def_id) => { Ok(Self::Signature(generic_def_id.try_into()?)) @@ -289,10 +300,10 @@ impl TryFrom for ExpressionStoreOwnerId { } } -impl TryFrom for FunctionId { +impl TryFrom> for FunctionId { type Error = (); - fn try_from(v: Function) -> Result { + fn try_from(v: Function<'_>) -> Result { match v.id { AnyFunctionId::FunctionId(id) => Ok(id), _ => Err(()), @@ -300,10 +311,10 @@ impl TryFrom for FunctionId { } } -impl TryFrom for ImplId { +impl TryFrom> for ImplId { type Error = (); - fn try_from(v: Impl) -> Result { + fn try_from(v: Impl<'_>) -> Result { match v.id { AnyImplId::ImplId(id) => Ok(id), _ => Err(()), diff --git a/crates/hir/src/has_source.rs b/crates/hir/src/has_source.rs index 3a6e19636a0b..45bde53c99a3 100644 --- a/crates/hir/src/has_source.rs +++ b/crates/hir/src/has_source.rs @@ -158,7 +158,7 @@ impl HasSource for EnumVariant { Some(self.id.lookup(db).source(db)) } } -impl HasSource for Function { +impl HasSource for Function<'_> { type Ast = ast::Fn; fn source(self, db: &dyn HirDatabase) -> Option> { match self.id { @@ -225,7 +225,7 @@ impl HasSource for Macro { } } } -impl HasSource for Impl { +impl HasSource for Impl<'_> { type Ast = ast::Impl; fn source(self, db: &dyn HirDatabase) -> Option> { match self.id { @@ -313,7 +313,7 @@ impl HasSource for Param<'_> { } } -impl HasSource for SelfParam { +impl HasSource for SelfParam<'_> { type Ast = ast::SelfParam; fn source(self, db: &dyn HirDatabase) -> Option> { diff --git a/crates/hir/src/lib.rs b/crates/hir/src/lib.rs index 474f4bbe4fe0..a596b058978e 100644 --- a/crates/hir/src/lib.rs +++ b/crates/hir/src/lib.rs @@ -37,6 +37,7 @@ mod display; #[doc(hidden)] pub use hir_def::ModuleId; +use salsa::SalsaValue; use std::{ borrow::Borrow, @@ -330,7 +331,7 @@ impl Crate { self, db: &dyn SourceDatabase, query: import_map::Query, - ) -> impl Iterator, Complete)> { + ) -> impl Iterator, Macro>, Complete)> { let _p = tracing::info_span!("query_external_importables").entered(); import_map::search_dependencies(db, self.into(), &query).into_iter().map( |(item, do_not_complete)| { @@ -388,10 +389,10 @@ pub struct Module { } /// The defs which can be visible in the module. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum ModuleDef { +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SalsaValue)] +pub enum ModuleDef<'db> { Module(Module), - Function(Function), + Function(Function<'db>), Adt(Adt), // Can't be directly declared, but can be imported. EnumVariant(EnumVariant), @@ -403,8 +404,9 @@ pub enum ModuleDef { Macro(Macro), } impl_from!( + impl<'db> Module, - Function, + Function<'db>, Adt(Struct, Enum, Union), EnumVariant, Const, @@ -413,15 +415,16 @@ impl_from!( TypeAlias, BuiltinType, Macro - for ModuleDef + for ModuleDef<'db> ); impl_from!( + impl<'db> Variant { Struct => Adt, Union => Adt, EnumVariant => EnumVariant } - for ModuleDef + for ModuleDef<'db> ); -impl ModuleDef { +impl<'db> ModuleDef<'db> { pub fn module(self, db: &dyn HirDatabase) -> Option { match self { ModuleDef::Module(it) => it.parent(db), @@ -466,7 +469,7 @@ impl ModuleDef { Some(name) } - pub fn diagnostics<'db>( + pub fn diagnostics( self, db: &'db dyn HirDatabase, style_lints: bool, @@ -510,7 +513,7 @@ impl ModuleDef { acc } - pub fn as_def_with_body(self) -> Option { + pub fn as_def_with_body(self) -> Option> { match self { ModuleDef::Function(it) => Some(it.into()), ModuleDef::Const(it) => Some(it.into()), @@ -527,7 +530,7 @@ impl ModuleDef { } /// Returns only defs that have generics from themselves, not their parent. - pub fn as_self_generic_def(self) -> Option { + pub fn as_self_generic_def(self) -> Option> { match self { ModuleDef::Function(it) => Some(it.into()), ModuleDef::Adt(it) => Some(it.into()), @@ -542,7 +545,7 @@ impl ModuleDef { } } - pub fn as_generic_def(self) -> Option { + pub fn as_generic_def(self) -> Option> { match self { ModuleDef::Function(it) => Some(it.into()), ModuleDef::Adt(it) => Some(it.into()), @@ -573,7 +576,7 @@ impl ModuleDef { } } -impl HasCrate for ModuleDef { +impl HasCrate for ModuleDef<'_> { fn krate(&self, db: &dyn HirDatabase) -> Crate { match self.module(db) { Some(module) => module.krate(db), @@ -582,7 +585,7 @@ impl HasCrate for ModuleDef { } } -impl HasAttrs for ModuleDef { +impl HasAttrs for ModuleDef<'_> { fn attr_id(self, db: &dyn HirDatabase) -> attrs::AttrsOwner { match self { ModuleDef::Module(it) => it.attr_id(db), @@ -599,7 +602,7 @@ impl HasAttrs for ModuleDef { } } -impl HasVisibility for ModuleDef { +impl HasVisibility for ModuleDef<'_> { fn visibility(&self, db: &dyn HirDatabase) -> Visibility { match *self { ModuleDef::Module(it) => it.visibility(db), @@ -730,11 +733,11 @@ impl Module { .collect() } - pub fn resolve_mod_path( + pub fn resolve_mod_path<'db>( &self, db: &dyn HirDatabase, segments: impl IntoIterator, - ) -> Option> { + ) -> Option>> { let items = self .id .resolver(db) @@ -1086,7 +1089,7 @@ impl Module { } } - pub fn declarations(self, db: &dyn HirDatabase) -> Vec { + pub fn declarations(self, db: &dyn HirDatabase) -> Vec> { let def_map = self.id.def_map(db); let scope = &def_map[self.id].scope; scope @@ -1102,7 +1105,7 @@ impl Module { scope.legacy_macros().flat_map(|(_, it)| it).map(|&it| it.into()).collect() } - pub fn impl_defs(self, db: &dyn HirDatabase) -> Vec { + pub fn impl_defs<'db>(self, db: &'db dyn HirDatabase) -> Vec> { let def_map = self.id.def_map(db); let scope = &def_map[self.id].scope; scope.impls().map(Impl::from).chain(scope.builtin_derive_impls().map(Impl::from)).collect() @@ -1110,10 +1113,10 @@ impl Module { /// Finds a path that can be used to refer to the given item from within /// this module, if possible. - pub fn find_path( + pub fn find_path<'a>( self, db: &dyn SourceDatabase, - item: impl Into, + item: impl Into>, cfg: FindPathConfig, ) -> Option { hir_def::find_path::find_path( @@ -1128,10 +1131,10 @@ impl Module { /// Finds a path that can be used to refer to the given item from within /// this module, if possible. This is used for returning import paths for use-statements. - pub fn find_use_path( + pub fn find_use_path<'db>( self, db: &dyn SourceDatabase, - item: impl Into, + item: impl Into>, prefix_kind: PrefixKind, cfg: FindPathConfig, ) -> Option { @@ -1875,7 +1878,7 @@ pub struct AnonConst<'db> { } impl<'db> AnonConst<'db> { - pub fn owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwner { + pub fn owner(self, db: &dyn HirDatabase) -> ExpressionStoreOwner<'static> { self.id.loc(db).owner.into() } @@ -1900,39 +1903,40 @@ impl<'db> AnonConst<'db> { #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum InferBody<'db> { - Body(DefWithBody), + Body(DefWithBody<'db>), AnonConst(AnonConst<'db>), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum ExpressionStoreOwner { - Body(DefWithBody), - Signature(GenericDef), +pub enum ExpressionStoreOwner<'db> { + Body(DefWithBody<'db>), + Signature(GenericDef<'db>), VariantFields(Variant), } -impl From for ExpressionStoreOwner { - fn from(v: GenericDef) -> Self { +impl<'db> From> for ExpressionStoreOwner<'db> { + fn from(v: GenericDef<'db>) -> Self { Self::Signature(v) } } -impl From for ExpressionStoreOwner { - fn from(v: DefWithBody) -> Self { +impl<'db> From> for ExpressionStoreOwner<'db> { + fn from(v: DefWithBody<'db>) -> Self { Self::Body(v) } } impl_from!( + impl<'db> ExpressionStoreOwnerId { Signature => Signature, Body => Body, VariantFields => VariantFields, } - for ExpressionStoreOwner + for ExpressionStoreOwner<'db> ); -impl ExpressionStoreOwner { +impl ExpressionStoreOwner<'_> { pub fn module(self, db: &dyn HirDatabase) -> Module { match self { Self::Body(body) => body.module(db), @@ -1944,15 +1948,15 @@ impl ExpressionStoreOwner { /// The defs which have a body. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum DefWithBody { - Function(Function), +pub enum DefWithBody<'db> { + Function(Function<'db>), Static(Static), Const(Const), EnumVariant(EnumVariant), } -impl_from!(Function, Const, Static, EnumVariant for DefWithBody); +impl_from!(impl<'db> Function<'db>, Const, Static, EnumVariant for DefWithBody<'db>); -impl DefWithBody { +impl<'db> DefWithBody<'db> { pub fn module(self, db: &dyn HirDatabase) -> Module { match self { DefWithBody::Const(c) => c.module(db), @@ -1972,7 +1976,7 @@ impl DefWithBody { } /// Returns the type this def's body has to evaluate to. - pub fn body_type(self, db: &dyn HirDatabase) -> Type<'_> { + pub fn body_type(self, db: &'db dyn HirDatabase) -> Type<'db> { match self { DefWithBody::Function(it) => it.ret_type(db), DefWithBody::Static(it) => it.ty(db), @@ -2020,7 +2024,7 @@ impl DefWithBody { } } - pub fn diagnostics<'db>( + pub fn diagnostics( self, db: &'db dyn HirDatabase, acc: &mut Vec>, @@ -2108,10 +2112,7 @@ impl DefWithBody { } /// Returns an iterator over the inferred types of all expressions in this body. - pub fn expression_types<'db>( - self, - db: &'db dyn HirDatabase, - ) -> impl Iterator> { + pub fn expression_types(self, db: &'db dyn HirDatabase) -> impl Iterator> { self.id().into_iter().flat_map(move |def_id| { let infer = InferenceResult::of(db, def_id); let def_id = def_id.generic_def(db); @@ -2121,7 +2122,7 @@ impl DefWithBody { } /// Returns an iterator over the inferred types of all patterns in this body. - pub fn pattern_types<'db>(self, db: &'db dyn HirDatabase) -> impl Iterator> { + pub fn pattern_types(self, db: &'db dyn HirDatabase) -> impl Iterator> { self.id().into_iter().flat_map(move |def_id| { let infer = InferenceResult::of(db, def_id); let def_id = def_id.generic_def(db); @@ -2131,7 +2132,7 @@ impl DefWithBody { } /// Returns an iterator over the inferred types of all bindings in this body. - pub fn binding_types<'db>(self, db: &'db dyn HirDatabase) -> impl Iterator> { + pub fn binding_types(self, db: &'db dyn HirDatabase) -> impl Iterator> { self.id().into_iter().flat_map(move |def_id| { let infer = InferenceResult::of(db, def_id); let def_id = def_id.generic_def(db); @@ -2180,25 +2181,29 @@ fn expr_store_diagnostics<'db>( .for_each(|(_ast_id, call_id)| macro_call_diagnostics(db, call_id, acc)); } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -enum AnyFunctionId { +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, SalsaValue)] +enum AnyFunctionId<'db> { FunctionId(FunctionId), - BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId }, + BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId<'db> }, } -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -pub struct Function { - pub(crate) id: AnyFunctionId, +#[derive(Clone, Copy, PartialEq, Eq, Hash, SalsaValue)] +pub struct Function<'db> { + pub(crate) id: AnyFunctionId<'db>, } -impl fmt::Debug for Function { +impl fmt::Debug for Function<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.id, f) } } -impl Function { - pub fn lang(db: &dyn HirDatabase, krate: Crate, lang_item: LangItem) -> Option { +impl<'db> Function<'db> { + pub fn lang( + db: &dyn HirDatabase, + krate: Crate, + lang_item: LangItem, + ) -> Option> { let lang_items = hir_def::lang_item::lang_items(db, krate.id); match lang_item.from_lang_items(lang_items)? { LangItemTarget::FunctionId(it) => Some(it.into()), @@ -2258,7 +2263,7 @@ impl Function { } } - fn fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId<'db>, PolyFnSig<'db>) { + fn fn_sig(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!(); @@ -2266,19 +2271,19 @@ impl Function { (fn_ptr.owner, sig_tys.with(hdr)) } - fn erased_fn_sig<'db>(self, db: &'db dyn HirDatabase) -> (TypeOwnerId<'db>, FnSig<'db>) { + fn erased_fn_sig(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) } /// Get this function's return type - pub fn ret_type(self, db: &dyn HirDatabase) -> Type<'_> { + pub fn ret_type(self, db: &'db dyn HirDatabase) -> Type<'db> { let (owner, sig) = self.erased_fn_sig(db); Type { owner, ty: EarlyBinder::bind(sig.output()) } } - pub fn async_ret_type<'db>(self, db: &'db dyn HirDatabase) -> Option> { + pub fn async_ret_type(self, db: &'db dyn HirDatabase) -> Option> { let AnyFunctionId::FunctionId(id) = self.id else { return None; }; @@ -2314,11 +2319,11 @@ impl Function { } } - pub fn self_param(self, db: &dyn HirDatabase) -> Option { + pub fn self_param(self, db: &'db dyn HirDatabase) -> Option> { self.has_self_param(db).then_some(SelfParam { func: self }) } - pub fn assoc_fn_params(self, db: &dyn HirDatabase) -> Vec> { + pub fn assoc_fn_params(self, db: &'db dyn HirDatabase) -> Vec> { let (owner, sig) = self.erased_fn_sig(db); let func = match self.id { AnyFunctionId::FunctionId(id) => Callee::Def(CallableDefId::FunctionId(id)), @@ -2346,12 +2351,12 @@ impl Function { } } - pub fn method_params(self, db: &dyn HirDatabase) -> Option>> { + pub fn method_params(self, db: &'db dyn HirDatabase) -> Option>> { self.self_param(db)?; Some(self.params_without_self(db)) } - pub fn params_without_self(self, db: &dyn HirDatabase) -> Vec> { + pub fn params_without_self(self, db: &'db dyn HirDatabase) -> Vec> { let mut params = self.assoc_fn_params(db); if self.has_self_param(db) { params.remove(0); @@ -2471,7 +2476,7 @@ impl Function { pub fn is_unsafe_to_call( self, db: &dyn HirDatabase, - caller: Option, + caller: Option>, call_edition: Edition, ) -> bool { let AnyFunctionId::FunctionId(id) = self.id else { @@ -2599,7 +2604,7 @@ pub struct Param<'db> { } impl<'db> Param<'db> { - pub fn parent_fn(&self) -> Option { + pub fn parent_fn(&self) -> Option> { match self.func { Callee::Def(CallableDefId::FunctionId(f)) => Some(f.into()), _ => None, @@ -2672,11 +2677,11 @@ impl<'db> Param<'db> { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct SelfParam { - func: Function, +pub struct SelfParam<'db> { + func: Function<'db>, } -impl SelfParam { +impl<'db> SelfParam<'db> { pub fn access(self, db: &dyn HirDatabase) -> Access { match self.func.id { AnyFunctionId::FunctionId(id) => { @@ -2707,17 +2712,17 @@ impl SelfParam { } } - pub fn parent_fn(&self) -> Function { + pub fn parent_fn(&self) -> Function<'db> { self.func } - pub fn ty<'db>(&self, db: &'db dyn HirDatabase) -> Type<'db> { + pub fn ty(&self, db: &'db dyn HirDatabase) -> Type<'db> { let (owner, sig) = self.func.erased_fn_sig(db); Type { owner, ty: EarlyBinder::bind(sig.inputs()[0]) } } } -impl HasVisibility for Function { +impl HasVisibility for Function<'_> { fn visibility(&self, db: &dyn HirDatabase) -> Visibility { match self.id { AnyFunctionId::FunctionId(id) => AssocItemId::from(id).assoc_visibility(db), @@ -2940,7 +2945,11 @@ impl Trait { traits.iter().map(|tr| Trait::from(*tr)).collect() } - pub fn function(self, db: &dyn HirDatabase, name: impl PartialEq) -> Option { + pub fn function( + self, + db: &dyn HirDatabase, + name: impl PartialEq, + ) -> Option> { self.id.trait_items(db).items.iter().find(|(n, _)| name == *n).and_then(|&(_, it)| match it { AssocItemId::FunctionId(id) => Some(id.into()), @@ -2948,11 +2957,11 @@ impl Trait { }) } - pub fn items(self, db: &dyn HirDatabase) -> Vec { + pub fn items(self, db: &dyn HirDatabase) -> Vec> { self.id.trait_items(db).items.iter().map(|(_name, it)| (*it).into()).collect() } - pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec { + pub fn items_with_supertraits(self, db: &dyn HirDatabase) -> Vec> { self.all_supertraits(db).into_iter().flat_map(|tr| tr.items(db)).collect() } @@ -3348,20 +3357,21 @@ impl HasVisibility for Macro { } #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum ItemInNs { - Types(ModuleDef), - Values(ModuleDef), +pub enum ItemInNs<'db> { + Types(ModuleDef<'db>), + Values(ModuleDef<'db>), Macros(Macro), } -impl From for ItemInNs { +impl From for ItemInNs<'static> { fn from(it: Macro) -> Self { Self::Macros(it) } } impl_from!( - ModuleDef { + impl<'db> + ModuleDef<'db> { Module => Types, Function => Values, Adt => Types, @@ -3373,11 +3383,11 @@ impl_from!( BuiltinType => Types, Macro => Macros, } - for ItemInNs + for ItemInNs<'db> ); -impl ItemInNs { - pub fn into_module_def(self) -> ModuleDef { +impl<'db> ItemInNs<'db> { + pub fn into_module_def(self) -> ModuleDef<'db> { match self { ItemInNs::Types(id) | ItemInNs::Values(id) => id, ItemInNs::Macros(id) => ModuleDef::Macro(id), @@ -3403,18 +3413,18 @@ impl ItemInNs { /// Invariant: `inner.as_extern_assoc_item(db).is_some()` /// We do not actively enforce this invariant. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub enum ExternAssocItem { - Function(Function), +pub enum ExternAssocItem<'db> { + Function(Function<'db>), Static(Static), TypeAlias(TypeAlias), } -pub trait AsExternAssocItem { - fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option; +pub trait AsExternAssocItem<'db> { + fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option>; } -impl AsExternAssocItem for Function { - fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsExternAssocItem<'db> for Function<'db> { + fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option> { let AnyFunctionId::FunctionId(id) = self.id else { return None; }; @@ -3422,14 +3432,14 @@ impl AsExternAssocItem for Function { } } -impl AsExternAssocItem for Static { - fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsExternAssocItem<'db> for Static { + fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option> { as_extern_assoc_item(db, ExternAssocItem::Static, self.id) } } -impl AsExternAssocItem for TypeAlias { - fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsExternAssocItem<'db> for TypeAlias { + fn as_extern_assoc_item(self, db: &dyn HirDatabase) -> Option> { as_extern_assoc_item(db, ExternAssocItem::TypeAlias, self.id) } } @@ -3437,13 +3447,13 @@ impl AsExternAssocItem for TypeAlias { /// Invariant: `inner.as_assoc_item(db).is_some()` /// We do not actively enforce this invariant. #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] -pub enum AssocItem { - Function(Function), +pub enum AssocItem<'db> { + Function(Function<'db>), Const(Const), TypeAlias(TypeAlias), } -impl From for AssocItem { +impl<'db> From for AssocItem<'db> { fn from(value: method_resolution::CandidateId) -> Self { match value { method_resolution::CandidateId::FunctionId(id) => AssocItem::Function(id.into()), @@ -3453,17 +3463,17 @@ impl From for AssocItem { } #[derive(Debug, Clone)] -pub enum AssocItemContainer { +pub enum AssocItemContainer<'db> { Trait(Trait), - Impl(Impl), + Impl(Impl<'db>), } -pub trait AsAssocItem { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option; +pub trait AsAssocItem<'db> { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option>; } -impl AsAssocItem for Function { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsAssocItem<'db> for Function<'db> { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option> { match self.id { AnyFunctionId::FunctionId(id) => as_assoc_item(db, AssocItem::Function, id), AnyFunctionId::BuiltinDeriveImplMethod { .. } => Some(AssocItem::Function(self)), @@ -3471,20 +3481,20 @@ impl AsAssocItem for Function { } } -impl AsAssocItem for Const { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl AsAssocItem<'static> for Const { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option> { as_assoc_item(db, AssocItem::Const, self.id) } } -impl AsAssocItem for TypeAlias { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl AsAssocItem<'static> for TypeAlias { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option> { as_assoc_item(db, AssocItem::TypeAlias, self.id) } } -impl AsAssocItem for ModuleDef { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsAssocItem<'db> for ModuleDef<'db> { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option> { match self { ModuleDef::Function(it) => it.as_assoc_item(db), ModuleDef::Const(it) => it.as_assoc_item(db), @@ -3494,8 +3504,8 @@ impl AsAssocItem for ModuleDef { } } -impl AsAssocItem for DefWithBody { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsAssocItem<'db> for DefWithBody<'db> { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option> { match self { DefWithBody::Function(it) => it.as_assoc_item(db), DefWithBody::Const(it) => it.as_assoc_item(db), @@ -3504,8 +3514,8 @@ impl AsAssocItem for DefWithBody { } } -impl AsAssocItem for GenericDef { - fn as_assoc_item(self, db: &dyn HirDatabase) -> Option { +impl<'db> AsAssocItem<'db> for GenericDef<'db> { + fn as_assoc_item(self, db: &dyn HirDatabase) -> Option> { match self { GenericDef::Function(it) => it.as_assoc_item(db), GenericDef::Const(it) => it.as_assoc_item(db), @@ -3517,9 +3527,9 @@ impl AsAssocItem for GenericDef { fn as_assoc_item<'db, ID, DEF, LOC>( db: &(dyn HirDatabase + 'db), - ctor: impl FnOnce(DEF) -> AssocItem, + ctor: impl FnOnce(DEF) -> AssocItem<'db>, id: ID, -) -> Option +) -> Option> where ID: Lookup>, DEF: From, @@ -3533,9 +3543,9 @@ where fn as_extern_assoc_item<'db, ID, DEF, LOC>( db: &(dyn HirDatabase + 'db), - ctor: impl FnOnce(DEF) -> ExternAssocItem, + ctor: impl FnOnce(DEF) -> ExternAssocItem<'db>, id: ID, -) -> Option +) -> Option> where ID: Lookup>, DEF: From, @@ -3549,7 +3559,7 @@ where } } -impl ExternAssocItem { +impl<'db> ExternAssocItem<'db> { pub fn name(self, db: &dyn HirDatabase) -> Name { match self { Self::Function(it) => it.name(db), @@ -3566,7 +3576,7 @@ impl ExternAssocItem { } } - pub fn as_function(self) -> Option { + pub fn as_function(self) -> Option> { match self { Self::Function(v) => Some(v), _ => None, @@ -3588,7 +3598,7 @@ impl ExternAssocItem { } } -impl AssocItem { +impl<'db> AssocItem<'db> { pub fn name(self, db: &dyn HirDatabase) -> Option { match self { AssocItem::Function(it) => Some(it.name(db)), @@ -3605,7 +3615,7 @@ impl AssocItem { } } - pub fn container(self, db: &dyn HirDatabase) -> AssocItemContainer { + pub fn container(self, db: &'db dyn HirDatabase) -> AssocItemContainer<'db> { let container = match self { AssocItem::Function(it) => match it.id { AnyFunctionId::FunctionId(id) => id.lookup(db).container, @@ -3648,14 +3658,14 @@ impl AssocItem { } } - pub fn implementing_ty(self, db: &dyn HirDatabase) -> Option> { + pub fn implementing_ty(self, db: &'db dyn HirDatabase) -> Option> { match self.container(db) { AssocItemContainer::Impl(i) => Some(i.self_ty(db)), _ => None, } } - pub fn as_function(self) -> Option { + pub fn as_function(self) -> Option> { match self { Self::Function(v) => Some(v), _ => None, @@ -3676,7 +3686,7 @@ impl AssocItem { } } - pub fn diagnostics<'db>( + pub fn diagnostics( self, db: &'db dyn HirDatabase, acc: &mut Vec>, @@ -3707,7 +3717,7 @@ impl AssocItem { } } -impl HasVisibility for AssocItem { +impl HasVisibility for AssocItem<'_> { fn visibility(&self, db: &dyn HirDatabase) -> Visibility { match self { AssocItem::Function(f) => f.visibility(db), @@ -3717,31 +3727,32 @@ impl HasVisibility for AssocItem { } } -impl_from!(AssocItem { Function, Const, TypeAlias } for ModuleDef); +impl_from!(impl<'db> AssocItem<'db> { Function, Const, TypeAlias } for ModuleDef<'db>); #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] -pub enum GenericDef { - Function(Function), +pub enum GenericDef<'db> { + Function(Function<'db>), Adt(Adt), Trait(Trait), TypeAlias(TypeAlias), - Impl(Impl), + Impl(Impl<'db>), // consts can have type parameters from their parents (i.e. associated consts of traits) Const(Const), Static(Static), } impl_from!( - Function, + impl<'db> + Function<'db>, Adt(Struct, Enum, Union), Trait, TypeAlias, - Impl, + Impl<'db>, Const, Static - for GenericDef + for GenericDef<'db> ); -impl GenericDef { +impl<'db> GenericDef<'db> { pub fn name(self, db: &dyn HirDatabase) -> Option { match self { GenericDef::Function(it) => Some(it.name(db)), @@ -3830,7 +3841,7 @@ impl GenericDef { }) } - pub fn diagnostics<'db>(self, db: &'db dyn HirDatabase, acc: &mut Vec>) { + pub fn diagnostics(self, db: &'db dyn HirDatabase, acc: &mut Vec>) { let Some(def) = self.id() else { return }; let generics = GenericParams::of(db, def); @@ -3903,7 +3914,7 @@ impl<'db> GenericSubstitution<'db> { } fn new_from_fn( - def: Function, + def: Function<'db>, subst: GenericArgs<'db>, owner: TypeOwnerId<'db>, ) -> Option { @@ -4029,7 +4040,7 @@ impl<'db> Local<'db> { } } - pub fn as_self_param(self, db: &dyn HirDatabase) -> Option { + pub fn as_self_param(self, db: &dyn HirDatabase) -> Option> { match self.parent { ExpressionStoreOwnerId::Body(DefWithBodyId::FunctionId(func)) if self.is_self(db) => { Some(SelfParam { func: func.into() }) @@ -4057,7 +4068,7 @@ impl<'db> Local<'db> { ) } - pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner { + pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner<'static> { self.parent.into() } @@ -4249,7 +4260,7 @@ impl Label { self.parent(db).module(db) } - pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner { + pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner<'static> { self.parent.into() } @@ -4283,7 +4294,7 @@ impl GenericParam { } } - pub fn parent(self) -> GenericDef { + pub fn parent(self) -> GenericDef<'static> { match self { GenericParam::TypeParam(it) => it.id.parent().into(), GenericParam::ConstParam(it) => it.id.parent().into(), @@ -4353,7 +4364,7 @@ impl TypeParam { self.merge().name(db) } - pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef { + pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef<'static> { self.id.parent().into() } @@ -4425,7 +4436,7 @@ impl LifetimeParam { self.id.parent.module(db).into() } - pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef { + pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef<'static> { self.id.parent.into() } } @@ -4455,7 +4466,7 @@ impl ConstParam { self.id.parent().module(db).into() } - pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef { + pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef<'static> { self.id.parent().into() } @@ -4504,7 +4515,7 @@ impl TypeOrConstParam { self.id.parent.module(db).into() } - pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef { + pub fn parent(self, _db: &dyn HirDatabase) -> GenericDef<'static> { self.id.parent.into() } @@ -4549,17 +4560,21 @@ impl TypeOrConstParam { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct Impl { - pub(crate) id: AnyImplId, +pub struct Impl<'db> { + pub(crate) id: AnyImplId<'db>, } -impl Impl { - pub fn all_in_crate(db: &dyn HirDatabase, krate: Crate) -> Vec { +impl<'db> Impl<'db> { + pub fn all_in_crate(db: &'db dyn HirDatabase, krate: Crate) -> Vec> { let mut result = Vec::new(); extend_with_def_map(db, crate_def_map(db, krate.id), &mut result); return result; - fn extend_with_def_map(db: &dyn HirDatabase, def_map: &DefMap, result: &mut Vec) { + fn extend_with_def_map<'db>( + db: &'db dyn HirDatabase, + def_map: &DefMap<'db>, + result: &mut Vec>, + ) { for (_, module) in def_map.modules() { result.extend(module.scope.impls().map(Impl::from)); result.extend(module.scope.builtin_derive_impls().map(Impl::from)); @@ -4573,7 +4588,7 @@ impl Impl { } } - pub fn all_in_module(db: &dyn HirDatabase, module: Module) -> Vec { + pub fn all_in_module(db: &'db dyn HirDatabase, module: Module) -> Vec> { module.impl_defs(db) } @@ -4582,7 +4597,7 @@ impl Impl { /// blanket impls, and only does a shallow type constructor check. In fact, this should've probably been on `Adt` /// etc., and not on `Type`. If you would want to create a precise list of all impls applying to a type, /// you would need to include blanket impls, and try to prove to predicates for each candidate. - pub fn all_for_type<'db>(db: &'db dyn HirDatabase, ty: Type<'db>) -> Vec { + pub fn all_for_type(db: &'db dyn HirDatabase, ty: Type<'db>) -> Vec> { let mut result = Vec::new(); let interner = DbInterner::new_no_crate(db); let Some(simplified_ty) = fast_reject::simplify_type( @@ -4592,10 +4607,11 @@ impl Impl { ) else { return Vec::new(); }; - let mut extend_with_impls = |impls: Either<&[ImplId], &[BuiltinDeriveImplId]>| match impls { - Either::Left(impls) => result.extend(impls.iter().copied().map(Impl::from)), - Either::Right(impls) => result.extend(impls.iter().copied().map(Impl::from)), - }; + let mut extend_with_impls = + |impls: Either<&[ImplId], &[BuiltinDeriveImplId<'db>]>| match impls { + Either::Left(impls) => result.extend(impls.iter().copied().map(Impl::from)), + Either::Right(impls) => result.extend(impls.iter().copied().map(Impl::from)), + }; method_resolution::with_incoherent_inherent_impls( db, ty.krate(db), @@ -4625,10 +4641,10 @@ impl Impl { result } - pub fn all_for_trait(db: &dyn HirDatabase, trait_: Trait) -> Vec { + pub fn all_for_trait(db: &'db dyn HirDatabase, trait_: Trait) -> Vec> { let module = trait_.module(db).id; let mut all = Vec::new(); - let mut handle_impls = |impls: &TraitImpls<'_>| { + let mut handle_impls = |impls: &TraitImpls<'db>| { 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)), @@ -4660,7 +4676,7 @@ impl Impl { } } - pub fn trait_ref(self, db: &dyn HirDatabase) -> Option> { + pub fn trait_ref(self, db: &'db dyn HirDatabase) -> Option> { match self.id { AnyImplId::ImplId(id) => { let trait_ref = db.impl_trait(id)?.instantiate_identity().skip_norm_wip(); @@ -4678,7 +4694,7 @@ impl Impl { } } - pub fn self_ty(self, db: &dyn HirDatabase) -> Type<'_> { + pub fn self_ty(self, db: &'db dyn HirDatabase) -> Type<'db> { match self.id { AnyImplId::ImplId(id) => { let ty = db.impl_self_ty(id).instantiate_identity().skip_norm_wip(); @@ -4695,7 +4711,7 @@ impl Impl { } } - pub fn items(self, db: &dyn HirDatabase) -> Vec { + pub fn items(self, db: &dyn HirDatabase) -> Vec> { match self.id { AnyImplId::ImplId(id) => { id.impl_items(db).items.iter().map(|&(_, it)| it.into()).collect() @@ -5136,7 +5152,7 @@ impl CaptureUsageSource { #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)] enum TypeOwnerId<'db> { GenericDefId(GenericDefId), - BuiltinDeriveImplId(BuiltinDeriveImplId), + BuiltinDeriveImplId(BuiltinDeriveImplId<'db>), AnonConstId(AnonConstId<'db>), // FIXME: What do when we unify two different crates? Currently we just randomly keep one. NoParams(base_db::Crate), @@ -5145,7 +5161,7 @@ enum TypeOwnerId<'db> { impl_from!( impl<'db> GenericDefId, - BuiltinDeriveImplId, + BuiltinDeriveImplId<'db>, AnonConstId<'db> for TypeOwnerId<'db> ); @@ -5375,7 +5391,7 @@ impl<'db> Type<'db> { pub fn try_rebase_into_owner( &self, db: &'db dyn HirDatabase, - new_owner: GenericDef, + new_owner: GenericDef<'db>, ) -> Option { let new_owner = new_owner.id()?.into(); if self.owner.can_rebase_into(db, new_owner, self.ty) { @@ -5388,7 +5404,7 @@ impl<'db> Type<'db> { pub fn rebase_into_owner_or_error( &self, db: &'db dyn HirDatabase, - new_owner: GenericDef, + new_owner: GenericDef<'db>, ) -> Self { self.try_rebase_into_owner(db, new_owner).unwrap_or_else(|| self.instantiate_with_errors()) } @@ -5995,7 +6011,7 @@ impl<'db> Type<'db> { pub fn iterate_assoc_items( &self, db: &'db dyn HirDatabase, - mut callback: impl FnMut(AssocItem) -> Option, + mut callback: impl FnMut(AssocItem<'db>) -> Option, ) -> Option { let mut slot = None; self.iterate_assoc_items_dyn(db, &mut |assoc_item_id| { @@ -6137,10 +6153,10 @@ impl<'db> Type<'db> { pub fn iterate_method_candidates_with_traits( &self, db: &'db dyn HirDatabase, - scope: &SemanticsScope<'_>, + scope: &SemanticsScope<'db>, traits_in_scope: &FxHashSet, name: Option<&Name>, - mut callback: impl FnMut(Function) -> Option, + mut callback: impl FnMut(Function<'db>) -> Option, ) -> Option { let _p = tracing::info_span!("iterate_method_candidates_with_traits").entered(); let mut slot = None; @@ -6159,9 +6175,9 @@ impl<'db> Type<'db> { pub fn iterate_method_candidates( &self, db: &'db dyn HirDatabase, - scope: &SemanticsScope<'_>, + scope: &SemanticsScope<'db>, name: Option<&Name>, - callback: impl FnMut(Function) -> Option, + callback: impl FnMut(Function<'db>) -> Option, ) -> Option { self.iterate_method_candidates_with_traits( db, @@ -6213,10 +6229,10 @@ impl<'db> Type<'db> { pub fn iterate_method_candidates_split_inherent( &self, db: &'db dyn HirDatabase, - scope: &SemanticsScope<'_>, + scope: &SemanticsScope<'db>, traits_in_scope: &FxHashSet, name: Option<&Name>, - mut callback: impl MethodCandidateCallback, + mut callback: impl MethodCandidateCallback<'db>, ) { let _p = tracing::info_span!( "iterate_method_candidates_split_inherent", @@ -6293,10 +6309,10 @@ impl<'db> Type<'db> { pub fn iterate_path_candidates( &self, db: &'db dyn HirDatabase, - scope: &SemanticsScope<'_>, + scope: &SemanticsScope<'db>, traits_in_scope: &FxHashSet, name: Option<&Name>, - mut callback: impl FnMut(AssocItem) -> Option, + mut callback: impl FnMut(AssocItem<'db>) -> Option, ) -> Option { let _p = tracing::info_span!("iterate_path_candidates").entered(); let mut slot = None; @@ -6322,10 +6338,10 @@ impl<'db> Type<'db> { pub fn iterate_path_candidates_split_inherent( &self, db: &'db dyn HirDatabase, - scope: &SemanticsScope<'_>, + scope: &SemanticsScope<'db>, traits_in_scope: &FxHashSet, name: Option<&Name>, - mut callback: impl PathCandidateCallback, + mut callback: impl PathCandidateCallback<'db>, ) { let _p = tracing::info_span!( "iterate_path_candidates_split_inherent", @@ -6575,7 +6591,7 @@ pub struct InlineAsmOperand { } impl InlineAsmOperand { - pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner { + pub fn parent(self, _db: &dyn HirDatabase) -> ExpressionStoreOwner<'static> { self.owner.into() } @@ -6605,11 +6621,11 @@ enum Callee<'db> { CoroutineClosure(InternedCoroutineClosureId<'db>, GenericArgs<'db>), FnPtr, FnImpl(traits::FnTrait), - BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId }, + BuiltinDeriveImplMethod { method: BuiltinDeriveImplMethod, impl_: BuiltinDeriveImplId<'db> }, } pub enum CallableKind<'db> { - Function(Function), + Function(Function<'db>), TupleStruct(Struct), TupleEnumVariant(EnumVariant), Closure(Closure<'db>), @@ -6647,7 +6663,7 @@ impl<'db> Callable<'db> { } } - fn as_function(&self) -> Option { + fn as_function(&self) -> Option> { match self.callee { Callee::Def(CallableDefId::FunctionId(it)) => Some(it.into()), Callee::BuiltinDeriveImplMethod { method, impl_ } => { @@ -6657,7 +6673,7 @@ impl<'db> Callable<'db> { } } - pub fn receiver_param(&self, db: &'db dyn HirDatabase) -> Option<(SelfParam, Type<'db>)> { + pub fn receiver_param(&self, db: &'db dyn HirDatabase) -> Option<(SelfParam<'db>, Type<'db>)> { if !self.is_bound_method { return None; } @@ -6811,9 +6827,9 @@ pub enum BindingMode { /// For IDE only #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub enum ScopeDef<'db> { - ModuleDef(ModuleDef), + ModuleDef(ModuleDef<'db>), GenericParam(GenericParam), - ImplSelfType(Impl), + ImplSelfType(Impl<'db>), AdtSelfType(Adt), Local(Local<'db>), Label(Label), @@ -6879,7 +6895,7 @@ impl ScopeDef<'_> { impl_from!( impl<'db> - ItemInNs { Types => ModuleDef, Values => ModuleDef, Macros => ModuleDef } + ItemInNs<'db> { Types => ModuleDef, Values => ModuleDef, Macros => ModuleDef } for ScopeDef<'db> ); @@ -6958,7 +6974,7 @@ impl HasCrate for T { } } -impl HasCrate for AssocItem { +impl HasCrate for AssocItem<'_> { fn krate(&self, db: &dyn HirDatabase) -> Crate { self.module(db).krate(db) } @@ -6994,7 +7010,7 @@ impl HasCrate for EnumVariant { } } -impl HasCrate for Function { +impl HasCrate for Function<'_> { fn krate(&self, db: &dyn HirDatabase) -> Crate { self.module(db).krate(db) } @@ -7042,7 +7058,7 @@ impl HasCrate for Adt { } } -impl HasCrate for Impl { +impl HasCrate for Impl<'_> { fn krate(&self, db: &dyn HirDatabase) -> Crate { self.module(db).krate(db) } @@ -7060,18 +7076,18 @@ impl<'db> HasCrate for AnonConst<'db> { } } -pub trait HasContainer { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer; +pub trait HasContainer<'db> { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'db>; } -impl HasContainer for ExternCrateDecl { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for ExternCrateDecl { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { container_id_to_hir(self.id.lookup(db).container.into()) } } -impl HasContainer for Module { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Module { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { // FIXME: handle block expressions as modules (their parent is in a different DefMap) let def_map = self.id.def_map(db); match def_map[self.id].parent { @@ -7081,8 +7097,8 @@ impl HasContainer for Module { } } -impl HasContainer for Function { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl<'db> HasContainer<'db> for Function<'db> { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'db> { match self.id { AnyFunctionId::FunctionId(id) => container_id_to_hir(id.lookup(db).container), AnyFunctionId::BuiltinDeriveImplMethod { impl_, .. } => { @@ -7092,50 +7108,50 @@ impl HasContainer for Function { } } -impl HasContainer for Struct { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Struct { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { ItemContainer::Module(Module { id: self.id.lookup(db).container }) } } -impl HasContainer for Union { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Union { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { ItemContainer::Module(Module { id: self.id.lookup(db).container }) } } -impl HasContainer for Enum { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Enum { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { ItemContainer::Module(Module { id: self.id.lookup(db).container }) } } -impl HasContainer for TypeAlias { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for TypeAlias { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { container_id_to_hir(self.id.lookup(db).container) } } -impl HasContainer for Const { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Const { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { container_id_to_hir(self.id.lookup(db).container) } } -impl HasContainer for Static { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Static { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { container_id_to_hir(self.id.lookup(db).container) } } -impl HasContainer for Trait { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for Trait { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { ItemContainer::Module(Module { id: self.id.lookup(db).container }) } } -impl HasContainer for ExternBlock { - fn container(&self, db: &dyn HirDatabase) -> ItemContainer { +impl HasContainer<'static> for ExternBlock { + fn container(&self, db: &dyn HirDatabase) -> ItemContainer<'static> { ItemContainer::Module(Module { id: self.id.lookup(db).container }) } } @@ -7145,7 +7161,7 @@ pub trait HasName { } macro_rules! impl_has_name { - ( $( $ty:ident ),* $(,)? ) => { + ( $( $ty:ty ),* $(,)? ) => { $( impl HasName for $ty { fn name(&self, db: &dyn HirDatabase) -> Option { @@ -7157,7 +7173,7 @@ macro_rules! impl_has_name { } impl_has_name!( - ModuleDef, + ModuleDef<'_>, Module, Field, Struct, @@ -7166,16 +7182,16 @@ impl_has_name!( EnumVariant, Adt, Variant, - DefWithBody, - Function, + DefWithBody<'_>, + Function<'_>, ExternCrateDecl, Const, Static, Trait, TypeAlias, Macro, - ExternAssocItem, - AssocItem, + ExternAssocItem<'_>, + AssocItem<'_>, DeriveHelper, ToolModule, Label, @@ -7219,7 +7235,7 @@ impl HasName for Param<'_> { } } -fn container_id_to_hir(c: ItemContainerId) -> ItemContainer { +fn container_id_to_hir(c: ItemContainerId) -> ItemContainer<'static> { match c { ItemContainerId::ExternBlockId(id) => ItemContainer::ExternBlock(ExternBlock { id }), ItemContainerId::ModuleId(id) => ItemContainer::Module(Module { id }), @@ -7229,17 +7245,17 @@ fn container_id_to_hir(c: ItemContainerId) -> ItemContainer { } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub enum ItemContainer { +pub enum ItemContainer<'db> { Trait(Trait), - Impl(Impl), + Impl(Impl<'db>), Module(Module), ExternBlock(ExternBlock), Crate(Crate), } /// Subset of `ide_db::Definition` that doc links can resolve to. -pub enum DocLinkDef { - ModuleDef(ModuleDef), +pub enum DocLinkDef<'db> { + ModuleDef(ModuleDef<'db>), Field(Field), SelfType(Trait), } @@ -7257,40 +7273,40 @@ fn push_ty_diagnostics<'db>( ); } -pub trait MethodCandidateCallback { - fn on_inherent_method(&mut self, f: Function) -> ControlFlow<()>; +pub trait MethodCandidateCallback<'db> { + fn on_inherent_method(&mut self, f: Function<'db>) -> ControlFlow<()>; - fn on_trait_method(&mut self, f: Function) -> ControlFlow<()>; + fn on_trait_method(&mut self, f: Function<'db>) -> ControlFlow<()>; } -impl MethodCandidateCallback for F +impl<'db, F> MethodCandidateCallback<'db> for F where - F: FnMut(Function) -> ControlFlow<()>, + F: FnMut(Function<'db>) -> ControlFlow<()>, { - fn on_inherent_method(&mut self, f: Function) -> ControlFlow<()> { + fn on_inherent_method(&mut self, f: Function<'db>) -> ControlFlow<()> { self(f) } - fn on_trait_method(&mut self, f: Function) -> ControlFlow<()> { + fn on_trait_method(&mut self, f: Function<'db>) -> ControlFlow<()> { self(f) } } -pub trait PathCandidateCallback { - fn on_inherent_item(&mut self, item: AssocItem) -> ControlFlow<()>; +pub trait PathCandidateCallback<'db> { + fn on_inherent_item(&mut self, item: AssocItem<'db>) -> ControlFlow<()>; - fn on_trait_item(&mut self, item: AssocItem) -> ControlFlow<()>; + fn on_trait_item(&mut self, item: AssocItem<'db>) -> ControlFlow<()>; } -impl PathCandidateCallback for F +impl<'db, F> PathCandidateCallback<'db> for F where - F: FnMut(AssocItem) -> ControlFlow<()>, + F: FnMut(AssocItem<'db>) -> ControlFlow<()>, { - fn on_inherent_item(&mut self, item: AssocItem) -> ControlFlow<()> { + fn on_inherent_item(&mut self, item: AssocItem<'db>) -> ControlFlow<()> { self(item) } - fn on_trait_item(&mut self, item: AssocItem) -> ControlFlow<()> { + fn on_trait_item(&mut self, item: AssocItem<'db>) -> ControlFlow<()> { self(item) } } @@ -7298,7 +7314,7 @@ where pub fn resolve_absolute_path<'a, I: Iterator + Clone + 'a>( db: &'a dyn HirDatabase, mut segments: I, -) -> impl Iterator + use<'a, I> { +) -> impl Iterator> + use<'a, I> { segments .next() .into_iter() diff --git a/crates/hir/src/semantics.rs b/crates/hir/src/semantics.rs index f298e25489a5..25a969281f82 100644 --- a/crates/hir/src/semantics.rs +++ b/crates/hir/src/semantics.rs @@ -69,14 +69,14 @@ const CONTINUE_NO_BREAKS: ControlFlow = ControlFlow::Continue(() #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum PathResolution<'db> { /// An item - Def(ModuleDef), + Def(ModuleDef<'db>), /// A local binding (only value namespace) Local(Local<'db>), /// A type parameter TypeParam(TypeParam), /// A const parameter ConstParam(ConstParam), - SelfType(Impl), + SelfType(Impl<'db>), BuiltinAttr(BuiltinAttr), ToolModule(ToolModule), DeriveHelper(DeriveHelper), @@ -221,7 +221,7 @@ impl Semantics<'_, DB> { // Note: We take `DB` as `?Sized` here in order to support type-erased // use of `Semantics` via `Semantics<'_, dyn HirDatabase>`: -impl Semantics<'_, DB> { +impl<'db, DB: HirDatabase + ?Sized> Semantics<'db, DB> { pub fn hir_file_for(&self, syntax_node: &SyntaxNode) -> HirFileId { self.imp.find_file(syntax_node).file_id } @@ -355,23 +355,23 @@ impl Semantics<'_, DB> { self.imp.resolve_range_expr(range_expr).map(Struct::from) } - pub fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option { + pub fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option> { self.imp.resolve_await_to_poll(await_expr) } - pub fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option { + pub fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option> { self.imp.resolve_prefix_expr(prefix_expr) } - pub fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option { + pub fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option> { self.imp.resolve_index_expr(index_expr) } - pub fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option { + pub fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option> { self.imp.resolve_bin_expr(bin_expr) } - pub fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option { + pub fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option> { self.imp.resolve_try_expr(try_expr) } @@ -421,11 +421,11 @@ impl Semantics<'_, DB> { self.imp.to_def(v) } - pub fn to_fn_def(&self, f: &ast::Fn) -> Option { + pub fn to_fn_def(&self, f: &ast::Fn) -> Option> { self.imp.to_def(f) } - pub fn to_impl_def(&self, i: &ast::Impl) -> Option { + pub fn to_impl_def(&self, i: &ast::Impl) -> Option> { self.imp.to_def(i) } @@ -672,7 +672,7 @@ impl<'db> SemanticsImpl<'db> { fn derive_macro_calls( &self, attr: &ast::Meta, - ) -> Option>>> { + ) -> Option>>>> { let adt = attr.parent_attr()?.syntax().parent().and_then(ast::Adt::cast)?; let file_id = self.find_file(adt.syntax()).file_id; let adt = InFile::new(file_id, &adt); @@ -1650,7 +1650,7 @@ impl<'db> SemanticsImpl<'db> { /// Returns the `return` expressions in this function's body, /// excluding those inside closures or async blocks. - pub fn fn_return_points(&self, func: Function) -> Vec> { + pub fn fn_return_points(&self, func: Function<'_>) -> Vec> { let func_id = match func.id { AnyFunctionId::FunctionId(id) => id, _ => return vec![], @@ -1803,7 +1803,7 @@ impl<'db> SemanticsImpl<'db> { self.analyze(call.syntax())?.resolve_expr_as_callable(self.db, call) } - pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option { + pub fn resolve_method_call(&self, call: &ast::MethodCallExpr) -> Option> { self.analyze(call.syntax())?.resolve_method_call(self.db, call) } @@ -1811,7 +1811,7 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_method_call_fallback( &self, call: &ast::MethodCallExpr, - ) -> Option<(Either, Option>)> { + ) -> Option<(Either, Field>, Option>)> { self.analyze(call.syntax())?.resolve_method_call_fallback(self.db, call) } @@ -1821,9 +1821,9 @@ impl<'db> SemanticsImpl<'db> { &self, env: Type<'db>, trait_: Trait, - func: Function, + func: Function<'db>, subst: impl IntoIterator>, - ) -> Option { + ) -> Option> { let AnyFunctionId::FunctionId(func) = func.id else { return Some(func) }; let interner = DbInterner::new_no_crate(self.db); let mut subst = subst.into_iter(); @@ -1852,23 +1852,23 @@ impl<'db> SemanticsImpl<'db> { self.analyze(range_expr.syntax())?.resolve_range_expr(self.db, range_expr) } - fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option { + fn resolve_await_to_poll(&self, await_expr: &ast::AwaitExpr) -> Option> { self.analyze(await_expr.syntax())?.resolve_await_to_poll(self.db, await_expr) } - fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option { + fn resolve_prefix_expr(&self, prefix_expr: &ast::PrefixExpr) -> Option> { self.analyze(prefix_expr.syntax())?.resolve_prefix_expr(self.db, prefix_expr) } - fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option { + fn resolve_index_expr(&self, index_expr: &ast::IndexExpr) -> Option> { self.analyze(index_expr.syntax())?.resolve_index_expr(self.db, index_expr) } - fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option { + fn resolve_bin_expr(&self, bin_expr: &ast::BinExpr) -> Option> { self.analyze(bin_expr.syntax())?.resolve_bin_expr(self.db, bin_expr) } - fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option { + fn resolve_try_expr(&self, try_expr: &ast::TryExpr) -> Option> { self.analyze(try_expr.syntax())?.resolve_try_expr(self.db, try_expr) } @@ -1910,8 +1910,10 @@ impl<'db> SemanticsImpl<'db> { pub fn resolve_field_fallback( &self, field: &ast::FieldExpr, - ) -> Option<(Either>, Function>, Option>)> - { + ) -> Option<( + Either>, Function<'db>>, + Option>, + )> { self.analyze(field.syntax())?.resolve_field_fallback(self.db, field) } @@ -1974,7 +1976,7 @@ impl<'db> SemanticsImpl<'db> { self.to_def(macro_call)?.expansion_span_map(self.db).matched_arm } - pub fn get_unsafe_ops(&self, def: ExpressionStoreOwner) -> FxHashSet { + pub fn get_unsafe_ops(&self, def: ExpressionStoreOwner<'_>) -> FxHashSet { let Ok(def) = ExpressionStoreOwnerId::try_from(def) else { return Default::default() }; let (body, source_map) = ExpressionStore::with_source_map(self.db, def); let mut res = FxHashSet::default(); @@ -2060,7 +2062,7 @@ impl<'db> SemanticsImpl<'db> { &self, scope: &SyntaxNode, path: &ModPath, - ) -> Option> { + ) -> Option>> { let analyze = self.analyze(scope)?; let items = analyze.resolver.resolve_module_path_in_items(self.db, path); Some(items.iter_items().map(|(item, _)| item.into())) @@ -2070,7 +2072,7 @@ impl<'db> SemanticsImpl<'db> { self.analyze(record_lit.syntax())?.resolve_variant(record_lit) } - pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option { + pub fn resolve_bind_pat_to_const(&self, pat: &ast::IdentPat) -> Option> { self.analyze(pat.syntax())?.resolve_bind_pat_to_const(self.db, pat) } @@ -2176,7 +2178,10 @@ impl<'db> SemanticsImpl<'db> { Some(res) } - pub fn store_owner_for(&self, node: InFile<&SyntaxNode>) -> Option { + pub fn store_owner_for( + &self, + node: InFile<&SyntaxNode>, + ) -> Option> { let container = self.with_ctx(|ctx| ctx.find_container(node))?; container.as_expression_store_owner().map(|id| id.into()) } @@ -2437,7 +2442,7 @@ impl<'db> SemanticsImpl<'db> { } } - pub fn impl_generated_from_derive(&self, impl_: Impl) -> Option { + pub fn impl_generated_from_derive(&self, impl_: Impl<'_>) -> Option { let id = match impl_.id { AnyImplId::ImplId(id) => id, AnyImplId::BuiltinDeriveImplId(id) => return Some(id.loc(self.db).adt.into()), @@ -2664,11 +2669,11 @@ to_def_impls![ (crate::Enum, ast::Enum, enum_to_def), (crate::Union, ast::Union, union_to_def), (crate::Trait, ast::Trait, trait_to_def), - (crate::Impl, ast::Impl, impl_to_def), + (crate::Impl<'db>, ast::Impl, impl_to_def), (crate::TypeAlias, ast::TypeAlias, type_alias_to_def), (crate::Const, ast::Const, const_to_def), (crate::Static, ast::Static, static_to_def), - (crate::Function, ast::Fn, fn_to_def), + (crate::Function<'db>, ast::Fn, fn_to_def), (crate::Field, ast::RecordField, record_field_to_def), (crate::Field, ast::TupleField, tuple_field_to_def), (crate::EnumVariant, ast::Variant, enum_variant_to_def), @@ -2735,14 +2740,14 @@ impl<'db> SemanticsScope<'db> { } // FIXME: This is a weird function, we shouldn't have this? - pub fn containing_function(&self) -> Option { + pub fn containing_function(&self) -> Option> { self.resolver.expression_store_owner().and_then(|owner| match owner { ExpressionStoreOwnerId::Body(DefWithBodyId::FunctionId(id)) => Some(id.into()), _ => None, }) } - pub fn expression_store_owner(&self) -> Option { + pub fn expression_store_owner(&self) -> Option> { self.resolver.expression_store_owner().map(Into::into) } @@ -2833,7 +2838,10 @@ impl<'db> SemanticsScope<'db> { ) } - pub fn resolve_mod_path(&self, path: &ModPath) -> impl Iterator + use<> { + pub fn resolve_mod_path( + &self, + path: &ModPath, + ) -> impl Iterator> + use<> { let items = self.resolver.resolve_module_path_in_items(self.db, path); items.iter_items().map(|(item, _)| item.into()) } @@ -2855,7 +2863,7 @@ impl<'db> SemanticsScope<'db> { }); } - pub fn generic_def(&self) -> Option { + pub fn generic_def(&self) -> Option> { self.resolver.generic_def().map(|id| id.into()) } diff --git a/crates/hir/src/semantics/child_by_source.rs b/crates/hir/src/semantics/child_by_source.rs index 19aa1581318b..2cdf2a2992fa 100644 --- a/crates/hir/src/semantics/child_by_source.rs +++ b/crates/hir/src/semantics/child_by_source.rs @@ -14,10 +14,7 @@ use hir_def::{ AdtId, AssocItemId, AstIdLoc, DefWithBodyId, EnumId, FieldId, GenericDefId, ImplId, LifetimeParamId, Lookup, MacroId, ModuleDefId, ModuleId, TraitId, TypeOrConstParamId, VariantId, - dyn_map::{ - DynMap, - keys::{self, Key}, - }, + dyn_map::{DynMap, StaticKey, keys}, expr_store::Body, hir::generics::GenericParams, item_scope::ItemScope, @@ -25,17 +22,27 @@ use hir_def::{ src::{HasChildSource, HasSource}, }; -pub(crate) trait ChildBySource { - fn child_by_source(&self, db: &dyn SourceDatabase, file_id: HirFileId) -> DynMap { +pub(crate) trait ChildBySource<'db> { + fn child_by_source(&self, db: &'db dyn SourceDatabase, file_id: HirFileId) -> DynMap<'db> { let mut res = DynMap::default(); self.child_by_source_to(db, &mut res, file_id); res } - fn child_by_source_to(&self, db: &dyn SourceDatabase, map: &mut DynMap, file_id: HirFileId); + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + map: &mut DynMap<'db>, + file_id: HirFileId, + ); } -impl ChildBySource for TraitId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for TraitId { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { let data = self.trait_items(db); data.macro_calls().filter(|(ast_id, _)| ast_id.file_id == file_id).for_each( @@ -60,8 +67,13 @@ impl ChildBySource for TraitId { } } -impl ChildBySource for ImplId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for ImplId { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { let data = self.impl_items(db); data.macro_calls().filter(|(ast_id, _)| ast_id.file_id == file_id).for_each( |(ast_id, call_id)| { @@ -85,16 +97,26 @@ impl ChildBySource for ImplId { } } -impl ChildBySource for ModuleId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for ModuleId { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { let def_map = self.def_map(db); let module_data = &def_map[*self]; module_data.scope.child_by_source_to(db, res, file_id); } } -impl ChildBySource for ItemScope { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for ItemScope<'db> { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { self.declarations().for_each(|item| add_module_def(db, res, file_id, item)); self.impls().for_each(|imp| insert_item_loc(db, res, file_id, imp, keys::IMPL)); self.extern_blocks().for_each(|extern_block| { @@ -138,9 +160,9 @@ impl ChildBySource for ItemScope { res[keys::MACRO_CALL].insert(ast, call); }, ); - fn add_module_def( - db: &dyn SourceDatabase, - map: &mut DynMap, + fn add_module_def<'db>( + db: &'db dyn SourceDatabase, + map: &mut DynMap<'db>, file_id: HirFileId, item: ModuleDefId, ) { @@ -176,8 +198,8 @@ impl ChildBySource for ItemScope { } } -impl ChildBySource for VariantId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, _: HirFileId) { +impl<'db> ChildBySource<'db> for VariantId { + fn child_by_source_to(&self, db: &'db dyn SourceDatabase, res: &mut DynMap<'db>, _: HirFileId) { let arena_map = self.child_source(db); let arena_map = arena_map.as_ref(); let parent = *self; @@ -193,8 +215,13 @@ impl ChildBySource for VariantId { } } -impl ChildBySource for EnumId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for EnumId { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { let loc = &self.lookup(db); if file_id != loc.id.file_id { return; @@ -213,8 +240,13 @@ impl ChildBySource for EnumId { } } -impl ChildBySource for DefWithBodyId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for DefWithBodyId { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { let (body, sm) = Body::with_source_map(db, *self); if let &DefWithBodyId::VariantId(v) = self { VariantId::EnumVariantId(v).child_by_source_to(db, res, file_id) @@ -233,8 +265,13 @@ impl ChildBySource for DefWithBodyId { } } -impl ChildBySource for GenericDefId { - fn child_by_source_to(&self, db: &dyn SourceDatabase, res: &mut DynMap, file_id: HirFileId) { +impl<'db> ChildBySource<'db> for GenericDefId { + fn child_by_source_to( + &self, + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, + file_id: HirFileId, + ) { let (gfile_id, generic_params_list) = self.file_id_and_params_of(db); if gfile_id != file_id { return; @@ -276,12 +313,12 @@ impl ChildBySource for GenericDefId { } } -fn insert_item_loc( - db: &dyn SourceDatabase, - res: &mut DynMap, +fn insert_item_loc<'db, ID, N, Data>( + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, file_id: HirFileId, id: ID, - key: Key, + key: StaticKey, ) where ID: Lookup + 'static, Data: AstIdLoc, @@ -293,9 +330,9 @@ fn insert_item_loc( } } -fn add_assoc_item( - db: &dyn SourceDatabase, - res: &mut DynMap, +fn add_assoc_item<'db>( + db: &'db dyn SourceDatabase, + res: &mut DynMap<'db>, file_id: HirFileId, item: AssocItemId, ) { diff --git a/crates/hir/src/semantics/source_to_def.rs b/crates/hir/src/semantics/source_to_def.rs index caa7b39885fe..9ad547bed9d4 100644 --- a/crates/hir/src/semantics/source_to_def.rs +++ b/crates/hir/src/semantics/source_to_def.rs @@ -92,10 +92,7 @@ use hir_def::{ EnumVariantId, ExpressionStoreOwnerId, ExternBlockId, ExternCrateId, FieldId, FunctionId, GenericDefId, GenericParamId, ImplId, LifetimeParamId, Lookup, MacroId, ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, UseId, VariantId, - dyn_map::{ - DynMap, - keys::{self, Key}, - }, + dyn_map::{DynMap, StaticKey, keys}, expr_store::{Body, ExpressionStore}, hir::{BindingId, Expr, LabelId}, nameres::{block_def_map, crate_def_map}, @@ -121,7 +118,7 @@ use crate::{ #[derive(Default)] pub(super) struct SourceToDefCache<'db> { - pub(super) dynmap_cache: FxHashMap<(ChildContainer, HirFileId), DynMap>, + pub(super) dynmap_cache: FxHashMap<(ChildContainer, HirFileId), DynMap<'db>>, expansion_info_cache: FxHashMap>, pub(super) file_to_def_cache: FxHashMap>, pub(super) included_file_cache: FxHashMap>, @@ -417,7 +414,8 @@ impl<'db> SourceToDefCtx<'db, '_> { &mut self, item: InFile<&ast::Adt>, src: InFile, - ) -> Option<(AttrId, MacroCallId, &[Option>])> { + ) -> Option<(AttrId, MacroCallId, &[Option>>])> + { let map = self.dyn_map(item)?; map[keys::DERIVE_MACRO_CALL] .get(&AstPtr::new(&src.value)) @@ -434,8 +432,12 @@ impl<'db> SourceToDefCtx<'db, '_> { adt: InFile<&ast::Adt>, ) -> Option< impl Iterator< - Item = (AttrId, MacroCallId, &'slf [Option>]), - > + use<'slf>, + Item = ( + AttrId, + MacroCallId, + &'slf [Option>>], + ), + > + use<'slf, 'db>, > { self.dyn_map(adt).as_ref().map(|&map| { let dyn_map = &map[keys::DERIVE_MACRO_CALL]; @@ -450,17 +452,17 @@ impl<'db> SourceToDefCtx<'db, '_> { fn to_def( &mut self, src: InFile<&Ast>, - key: Key, + key: StaticKey, ) -> Option { self.dyn_map(src)?[key].get(&AstPtr::new(src.value)).copied() } - fn dyn_map(&mut self, src: InFile<&Ast>) -> Option<&DynMap> { + fn dyn_map(&mut self, src: InFile<&Ast>) -> Option<&DynMap<'db>> { let container = self.find_container(src.map(|it| it.syntax()))?; Some(self.cache_for(container, src.file_id)) } - fn cache_for(&mut self, container: ChildContainer, file_id: HirFileId) -> &DynMap { + fn cache_for(&mut self, container: ChildContainer, file_id: HirFileId) -> &DynMap<'db> { let db = self.db; self.cache .dynmap_cache @@ -541,9 +543,10 @@ impl<'db> SourceToDefCtx<'db, '_> { } pub(super) fn proc_macro_to_def(&mut self, src: InFile<&ast::Fn>) -> Option { - self.dyn_map(src).and_then(|it| { - it[keys::PROC_MACRO].get(&AstPtr::new(src.value)).copied().map(MacroId::from) - }) + self.dyn_map(src)?[keys::PROC_MACRO] + .get(&AstPtr::new(src.value)) + .copied() + .map(MacroId::from) } pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option { @@ -745,7 +748,7 @@ impl_from! { } impl ChildContainer { - fn child_by_source(self, db: &dyn HirDatabase, file_id: HirFileId) -> DynMap { + fn child_by_source<'db>(self, db: &'db dyn HirDatabase, file_id: HirFileId) -> DynMap<'db> { let _p = tracing::info_span!("ChildContainer::child_by_source").entered(); match self { ChildContainer::DefWithBodyId(it) => it.child_by_source(db, file_id), diff --git a/crates/hir/src/source_analyzer.rs b/crates/hir/src/source_analyzer.rs index 209091683a01..183ef89faa85 100644 --- a/crates/hir/src/source_analyzer.rs +++ b/crates/hir/src/source_analyzer.rs @@ -648,7 +648,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, call: &ast::MethodCallExpr, - ) -> Option { + ) -> Option> { let expr_id = self.expr_id(call.clone().into())?.as_expr()?; let (f_in_trait, substs) = self.infer()?.method_resolution(expr_id)?; @@ -659,7 +659,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, call: &ast::MethodCallExpr, - ) -> Option<(Either, Option>)> { + ) -> Option<(Either, Field>, Option>)> { let expr_id = self.expr_id(call.clone().into())?.as_expr()?; let inference_result = self.infer()?; match inference_result.method_resolution(expr_id) { @@ -717,8 +717,10 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, field: &ast::FieldExpr, - ) -> Option<(Either>, Function>, Option>)> - { + ) -> Option<( + Either>, Function<'db>>, + Option>, + )> { let def = self.infer_body?; let expr_id = self.expr_id(field.clone().into())?.as_expr()?; let inference_result = self.infer()?; @@ -820,7 +822,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, await_expr: &ast::AwaitExpr, - ) -> Option { + ) -> Option> { let mut ty = self.ty_of_expr(await_expr.expr()?)?; let into_future_trait = self @@ -856,7 +858,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, prefix_expr: &ast::PrefixExpr, - ) -> Option { + ) -> Option> { let lang_items = self.lang_items(db); let (_op_trait, op_fn) = match prefix_expr.op_kind()? { ast::UnaryOp::Deref => { @@ -891,7 +893,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, index_expr: &ast::IndexExpr, - ) -> Option { + ) -> Option> { let base_ty = self.ty_of_expr(index_expr.base()?)?; let index_ty = self.ty_of_expr(index_expr.index()?)?; let lang_items = self.lang_items(db); @@ -917,7 +919,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, binop_expr: &ast::BinExpr, - ) -> Option { + ) -> Option> { let op = binop_expr.op_kind()?; let lhs = self.ty_of_expr(binop_expr.lhs()?)?; let rhs = self.ty_of_expr(binop_expr.rhs()?)?; @@ -935,7 +937,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, try_expr: &ast::TryExpr, - ) -> Option { + ) -> Option> { let ty = self.ty_of_expr(try_expr.expr()?)?; let op_fn = self.lang_items(db).TryTraitBranch?; @@ -1045,7 +1047,7 @@ impl<'db> SourceAnalyzer<'db> { &self, db: &'db dyn HirDatabase, pat: &ast::IdentPat, - ) -> Option { + ) -> Option> { let expr_or_pat_id = self.pat_id(&pat.clone().into())?; let store = self.store()?; @@ -1704,7 +1706,7 @@ impl<'db> SourceAnalyzer<'db> { db: &'db dyn HirDatabase, func: FunctionId, substs: GenericArgs<'db>, - ) -> Function { + ) -> Function<'db> { self.resolve_impl_method_or_trait_def_with_subst(db, func, substs).0 } @@ -1713,7 +1715,7 @@ impl<'db> SourceAnalyzer<'db> { db: &'db dyn HirDatabase, func: FunctionId, substs: GenericArgs<'db>, - ) -> (Function, GenericArgs<'db>) { + ) -> (Function<'db>, GenericArgs<'db>) { let owner = match self.resolver.generic_def() { Some(it) => it, None => return (func.into(), substs), @@ -1861,9 +1863,9 @@ pub(crate) fn resolve_hir_path<'db>( } #[inline] -pub(crate) fn resolve_hir_path_as_attr_macro( - db: &dyn HirDatabase, - resolver: &Resolver<'_>, +pub(crate) fn resolve_hir_path_as_attr_macro<'db>( + db: &'db dyn HirDatabase, + resolver: &Resolver<'db>, path: &Path, ) -> Option { resolver diff --git a/crates/hir/src/symbols.rs b/crates/hir/src/symbols.rs index b458dc0f1046..fe2bd3d3c312 100644 --- a/crates/hir/src/symbols.rs +++ b/crates/hir/src/symbols.rs @@ -31,7 +31,7 @@ use crate::{Crate, HasCrate, Module, ModuleDef, Semantics}; #[derive(Clone, PartialEq, Eq, Hash, SalsaValue)] pub struct FileSymbol<'db> { pub name: Symbol, - pub def: ModuleDef, + pub def: ModuleDef<'db>, pub loc: DeclarationLocation, pub container_name: Option, /// Whether this symbol is a doc alias for the original symbol. diff --git a/crates/hir/src/term_search/expr.rs b/crates/hir/src/term_search/expr.rs index 07994268696e..9d837c116109 100644 --- a/crates/hir/src/term_search/expr.rs +++ b/crates/hir/src/term_search/expr.rs @@ -17,7 +17,7 @@ use crate::{ /// Helper function to get path to `ModuleDef` fn mod_item_path( sema_scope: &SemanticsScope<'_>, - def: &ModuleDef, + def: &ModuleDef<'_>, cfg: FindPathConfig, ) -> Option { let db = sema_scope.db; @@ -28,7 +28,7 @@ fn mod_item_path( /// Helper function to get path to `ModuleDef` as string fn mod_item_path_str( sema_scope: &SemanticsScope<'_>, - def: &ModuleDef, + def: &ModuleDef<'_>, cfg: FindPathConfig, edition: Edition, ) -> Result { @@ -71,10 +71,10 @@ pub enum Expr<'db> { /// Well known type (such as `true` for bool) FamousType { ty: Type<'db>, value: &'static str }, /// Function call (does not take self param) - Function { func: Function, generics: Vec>, params: Vec> }, + Function { func: Function<'db>, generics: Vec>, params: Vec> }, /// Method call (has self param) Method { - func: Function, + func: Function<'db>, generics: Vec>, target: Box>, params: Vec>, @@ -375,7 +375,7 @@ impl<'db> Expr<'db> { /// Helper function to find name of container fn container_name( - container: AssocItemContainer, + container: AssocItemContainer<'_>, sema_scope: &SemanticsScope<'_>, cfg: FindPathConfig, edition: Edition, diff --git a/crates/ide-assists/src/handlers/auto_import.rs b/crates/ide-assists/src/handlers/auto_import.rs index dd082476d2d6..87c1ef4a9122 100644 --- a/crates/ide-assists/src/handlers/auto_import.rs +++ b/crates/ide-assists/src/handlers/auto_import.rs @@ -257,7 +257,7 @@ fn group_label(import_candidate: &ImportCandidate<'_>) -> GroupLabel { /// relevant. pub(crate) fn relevance_score( ctx: &AssistContext<'_, '_>, - import: &LocatedImport, + import: &LocatedImport<'_>, expected: Option<&Type<'_>>, current_module: Option<&Module>, ) -> i32 { diff --git a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs index c1ac4f172489..ee83fdf92402 100644 --- a/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs +++ b/crates/ide-assists/src/handlers/extract_struct_from_enum_variant.rs @@ -411,7 +411,7 @@ fn apply_references( fn process_references( ctx: &AssistContext<'_, '_>, visited_modules: &mut FxHashSet, - enum_module_def: &ModuleDef, + enum_module_def: &ModuleDef<'_>, variant_hir_name: &Name, refs: Vec, ) -> Vec<(ast::PathSegment, SyntaxNode, Option<(ImportScope, hir::ModPath)>)> { diff --git a/crates/ide-assists/src/handlers/fix_visibility.rs b/crates/ide-assists/src/handlers/fix_visibility.rs index d0f5c7c5003d..67a3ccfa3431 100644 --- a/crates/ide-assists/src/handlers/fix_visibility.rs +++ b/crates/ide-assists/src/handlers/fix_visibility.rs @@ -112,7 +112,7 @@ fn add_vis_to_referenced_module_def(acc: &mut Assists, ctx: &AssistContext<'_, ' fn target_data_for_def( db: &dyn HirDatabase, - def: hir::ModuleDef, + def: hir::ModuleDef<'_>, ) -> Option<(ast::AnyHasVisibility, TextRange, FileId, Option)> { fn offset_target_and_file_id( db: &dyn HirDatabase, diff --git a/crates/ide-assists/src/handlers/generate_blanket_trait_impl.rs b/crates/ide-assists/src/handlers/generate_blanket_trait_impl.rs index 738f461a1f2f..e3348a4c9158 100644 --- a/crates/ide-assists/src/handlers/generate_blanket_trait_impl.rs +++ b/crates/ide-assists/src/handlers/generate_blanket_trait_impl.rs @@ -150,7 +150,10 @@ pub(crate) fn generate_blanket_trait_impl( Some(()) } -fn existing_any_impl(traitd: &ast::Trait, sema: &Semantics<'_, RootDatabase>) -> Option { +fn existing_any_impl<'db>( + traitd: &ast::Trait, + sema: &Semantics<'db, RootDatabase>, +) -> Option> { let db = sema.db; let traitd = sema.to_def(traitd)?; traitd diff --git a/crates/ide-assists/src/handlers/generate_delegate_trait.rs b/crates/ide-assists/src/handlers/generate_delegate_trait.rs index e21f1ab35984..bde0254a59ae 100644 --- a/crates/ide-assists/src/handlers/generate_delegate_trait.rs +++ b/crates/ide-assists/src/handlers/generate_delegate_trait.rs @@ -96,7 +96,7 @@ pub(crate) fn generate_delegate_trait( let strukt = Struct::new(ctx.find_node_at_offset::()?)?; - let field: Field = match ctx.find_node_at_offset::() { + let field: Field<'_> = match ctx.find_node_at_offset::() { Some(field) => Field::new(ctx, Either::Left(field))?, None => { let field = ctx.find_node_at_offset::()?; @@ -111,19 +111,19 @@ pub(crate) fn generate_delegate_trait( /// A utility object that represents a struct's field. #[derive(Debug)] -struct Field { +struct Field<'db> { name: String, ty: ast::Type, range: syntax::TextRange, - impls: Vec, + impls: Vec>, edition: Edition, } -impl Field { +impl<'db> Field<'db> { pub(crate) fn new( - ctx: &AssistContext<'_, '_>, + ctx: &AssistContext<'_, 'db>, f: Either, - ) -> Option { + ) -> Option> { let db = ctx.sema.db; let module = ctx.sema.file_to_module_def(ctx.vfs_file_id())?; @@ -166,12 +166,12 @@ impl Field { /// has a bound type parameter. We handle these cases in different ways /// hence the enum. #[derive(Debug)] -enum Delegee { +enum Delegee<'db> { Bound(hir::Trait), - Impls(hir::Trait, hir::Impl), + Impls(hir::Trait, hir::Impl<'db>), } -impl Delegee { +impl<'db> Delegee<'db> { fn trait_(&self) -> &hir::Trait { match self { Delegee::Bound(it) | Delegee::Impls(it, _) => it, @@ -205,7 +205,12 @@ impl Struct { Some(Struct { name, strukt: s }) } - pub(crate) fn delegate(&self, field: Field, acc: &mut Assists, ctx: &AssistContext<'_, '_>) { + pub(crate) fn delegate( + &self, + field: Field<'_>, + acc: &mut Assists, + ctx: &AssistContext<'_, '_>, + ) { let db = ctx.db(); for (index, delegee) in field.impls.iter().enumerate() { @@ -256,7 +261,7 @@ fn generate_impl( strukt: &Struct, field_ty: &ast::Type, field_name: &str, - delegee: &Delegee, + delegee: &Delegee<'_>, edition: Edition, ) -> Option { let make = SyntaxFactory::without_mappings(); diff --git a/crates/ide-assists/src/handlers/generate_documentation_template.rs b/crates/ide-assists/src/handlers/generate_documentation_template.rs index 89adda93866f..813a49c0279f 100644 --- a/crates/ide-assists/src/handlers/generate_documentation_template.rs +++ b/crates/ide-assists/src/handlers/generate_documentation_template.rs @@ -290,7 +290,7 @@ fn is_public(ast_func: &ast::Fn, ctx: &AssistContext<'_, '_>) -> Option { } /// Checks that all parent modules of the function are public / exported -fn all_parent_mods_public(hir_func: &hir::Function, ctx: &AssistContext<'_, '_>) -> bool { +fn all_parent_mods_public(hir_func: &hir::Function<'_>, ctx: &AssistContext<'_, '_>) -> bool { let mut module = hir_func.module(ctx.db()); loop { if let Some(parent) = module.parent(ctx.db()) { @@ -495,7 +495,7 @@ fn build_path(ast_func: &ast::Fn, ctx: &AssistContext<'_, '_>, edition: Edition) let leaf = self_partial_type(ast_func) .or_else(|| ast_func.name().map(|n| n.to_string())) .unwrap_or_else(|| "*".into()); - let module_def: ModuleDef = ctx.sema.to_def(ast_func)?.module(ctx.db()).into(); + let module_def: ModuleDef<'_> = ctx.sema.to_def(ast_func)?.module(ctx.db()).into(); match module_def.canonical_path(ctx.db(), edition) { Some(path) => Some(format!("{crate_name}::{path}::{leaf}")), None => Some(format!("{crate_name}::{leaf}")), diff --git a/crates/ide-assists/src/handlers/generate_function.rs b/crates/ide-assists/src/handlers/generate_function.rs index 13096c6efc37..af9f781574a5 100644 --- a/crates/ide-assists/src/handlers/generate_function.rs +++ b/crates/ide-assists/src/handlers/generate_function.rs @@ -942,7 +942,7 @@ fn params_and_where_preds_in_scope( (generic_params, where_clauses) } -fn containing_body(ctx: &AssistContext<'_, '_>) -> Option { +fn containing_body<'db>(ctx: &AssistContext<'_, 'db>) -> Option> { let item: ast::Item = ctx.find_node_at_offset()?; let def = match item { ast::Item::Fn(it) => ctx.sema.to_def(&it)?.into(), diff --git a/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs b/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs index 39f304cac9ca..b958b14dbac7 100644 --- a/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs +++ b/crates/ide-assists/src/handlers/generate_is_empty_from_len.rs @@ -88,13 +88,13 @@ pub(crate) fn generate_is_empty_from_len( ) } -fn get_impl_method( - ctx: &AssistContext<'_, '_>, +fn get_impl_method<'db>( + ctx: &AssistContext<'_, 'db>, impl_: &ast::Impl, fn_name: &Name, -) -> Option { +) -> Option> { let db = ctx.sema.db; - let impl_def: hir::Impl = ctx.sema.to_def(impl_)?; + let impl_def: hir::Impl<'_> = ctx.sema.to_def(impl_)?; let scope = ctx.sema.scope(impl_.syntax())?; let ty = impl_def.self_ty(db); diff --git a/crates/ide-assists/src/handlers/inline_call.rs b/crates/ide-assists/src/handlers/inline_call.rs index fd67617be45d..fb4908e451a8 100644 --- a/crates/ide-assists/src/handlers/inline_call.rs +++ b/crates/ide-assists/src/handlers/inline_call.rs @@ -308,7 +308,7 @@ impl CallInfo { fn get_fn_params<'db>( db: &'db dyn HirDatabase, - function: hir::Function, + function: hir::Function<'db>, param_list: &ast::ParamList, make: &SyntaxFactory, ) -> Option, hir::Param<'db>)>> { @@ -338,7 +338,7 @@ fn get_fn_params<'db>( fn inline<'db>( sema: &Semantics<'db, RootDatabase>, function_def_file_id: EditionedFileId, - function: hir::Function, + function: hir::Function<'db>, fn_body: &ast::BlockExpr, params: &[(ast::Pat, Option, hir::Param<'db>)], CallInfo { node, arguments, generic_arg_list, krate }: &CallInfo, diff --git a/crates/ide-assists/src/handlers/qualify_method_call.rs b/crates/ide-assists/src/handlers/qualify_method_call.rs index edf0a855c4fe..27c77e3d1f96 100644 --- a/crates/ide-assists/src/handlers/qualify_method_call.rs +++ b/crates/ide-assists/src/handlers/qualify_method_call.rs @@ -67,7 +67,7 @@ pub(crate) fn qualify_method_call(acc: &mut Assists, ctx: &AssistContext<'_, '_> Some(()) } -fn item_for_path_search(db: &dyn HirDatabase, item: ItemInNs) -> Option { +fn item_for_path_search<'db>(db: &dyn HirDatabase, item: ItemInNs<'db>) -> Option> { Some(match item { ItemInNs::Types(_) | ItemInNs::Values(_) => match item_as_assoc(db, item) { Some(assoc_item) => match assoc_item.container(db) { @@ -83,7 +83,7 @@ fn item_for_path_search(db: &dyn HirDatabase, item: ItemInNs) -> Option Option { +fn item_as_assoc<'db>(db: &dyn HirDatabase, item: ItemInNs<'db>) -> Option> { item.into_module_def().as_assoc_item(db) } diff --git a/crates/ide-assists/src/handlers/qualify_path.rs b/crates/ide-assists/src/handlers/qualify_path.rs index 5e07d85db9cf..e411cf7cd26d 100644 --- a/crates/ide-assists/src/handlers/qualify_path.rs +++ b/crates/ide-assists/src/handlers/qualify_path.rs @@ -117,7 +117,7 @@ pub(crate) enum QualifyCandidate<'db> { UnqualifiedName(Option), TraitAssocItem(ast::Path, ast::PathSegment), TraitMethod(&'db RootDatabase, ast::MethodCallExpr), - ImplMethod(&'db RootDatabase, ast::MethodCallExpr, hir::Function), + ImplMethod(&'db RootDatabase, ast::MethodCallExpr, hir::Function<'db>), } impl QualifyCandidate<'_> { @@ -126,7 +126,7 @@ impl QualifyCandidate<'_> { mut replacer: impl FnMut(String), editor: &SyntaxEditor, import: &hir::ModPath, - item: hir::ItemInNs, + item: hir::ItemInNs<'_>, edition: Edition, ) { let import = mod_path_to_ast_with_factory(editor.make(), import, edition); @@ -158,7 +158,7 @@ impl QualifyCandidate<'_> { mcall_expr: &ast::MethodCallExpr, editor: &SyntaxEditor, import: ast::Path, - hir_fn: &hir::Function, + hir_fn: &hir::Function<'_>, ) -> Option<()> { let make = editor.make(); let receiver = mcall_expr.receiver()?; @@ -189,7 +189,7 @@ impl QualifyCandidate<'_> { mcall_expr: &ast::MethodCallExpr, editor: &SyntaxEditor, import: ast::Path, - item: hir::ItemInNs, + item: hir::ItemInNs<'_>, ) -> Option<()> { let trait_method_name = mcall_expr.name_ref()?; let trait_ = item_as_trait(db, item)?; @@ -198,13 +198,13 @@ impl QualifyCandidate<'_> { } } -fn find_trait_method( +fn find_trait_method<'db>( db: &RootDatabase, trait_: hir::Trait, trait_method_name: &ast::NameRef, -) -> Option { +) -> Option> { if let Some(hir::AssocItem::Function(method)) = - trait_.items(db).into_iter().find(|item: &hir::AssocItem| { + trait_.items(db).into_iter().find(|item: &hir::AssocItem<'_>| { item.name(db) .map(|name| name.as_str() == trait_method_name.text().trim_start_matches("r#")) .unwrap_or(false) @@ -216,7 +216,7 @@ fn find_trait_method( } } -fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs) -> Option { +fn item_as_trait(db: &RootDatabase, item: hir::ItemInNs<'_>) -> Option { match item.into_module_def() { hir::ModuleDef::Trait(trait_) => Some(trait_), item_module_def => item_module_def.as_assoc_item(db)?.container_trait(db), @@ -237,7 +237,7 @@ fn group_label(candidate: &ImportCandidate<'_>) -> GroupLabel { fn label( db: &RootDatabase, candidate: &ImportCandidate<'_>, - import: &LocatedImport, + import: &LocatedImport<'_>, edition: Edition, ) -> String { let import_path = &import.import_path; diff --git a/crates/ide-assists/src/handlers/remove_unused_imports.rs b/crates/ide-assists/src/handlers/remove_unused_imports.rs index aeffb8a45b56..487802196ed2 100644 --- a/crates/ide-assists/src/handlers/remove_unused_imports.rs +++ b/crates/ide-assists/src/handlers/remove_unused_imports.rs @@ -136,11 +136,11 @@ pub(crate) fn remove_unused_imports(acc: &mut Assists, ctx: &AssistContext<'_, ' } } -fn is_path_per_ns_unused_in_scope( - ctx: &AssistContext<'_, '_>, +fn is_path_per_ns_unused_in_scope<'db>( + ctx: &AssistContext<'_, 'db>, u: &ast::UseTree, scope: &[SearchScope], - path: &PathResolutionPerNs<'_>, + path: &PathResolutionPerNs<'db>, ) -> bool { if let Some(PathResolution::Def(ModuleDef::Trait(ref t))) = path.type_ns { if is_trait_unused_in_scope(ctx, u, scope, t) { @@ -155,11 +155,11 @@ fn is_path_per_ns_unused_in_scope( } } -fn is_path_unused_in_scope( - ctx: &AssistContext<'_, '_>, +fn is_path_unused_in_scope<'db>( + ctx: &AssistContext<'_, 'db>, u: &ast::UseTree, scope: &[SearchScope], - path: &[Option>], + path: &[Option>], ) -> bool { !path .iter() diff --git a/crates/ide-assists/src/utils.rs b/crates/ide-assists/src/utils.rs index 388aac19b40e..1258d785d294 100644 --- a/crates/ide-assists/src/utils.rs +++ b/crates/ide-assists/src/utils.rs @@ -162,7 +162,7 @@ pub enum DefaultMethods { pub fn filter_assoc_items( sema: &Semantics<'_, RootDatabase>, - items: &[hir::AssocItem], + items: &[hir::AssocItem<'_>], default_methods: DefaultMethods, ignore_items: IgnoreAssocItems, ) -> Vec> { @@ -226,14 +226,14 @@ pub fn filter_assoc_items( /// then inserts into `impl_`. Returns the modified `impl_` and the first associated item that got /// inserted. #[must_use] -pub fn add_trait_assoc_items_to_impl( +pub fn add_trait_assoc_items_to_impl<'db>( make: &SyntaxFactory, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, config: &AssistConfig, original_items: &[InFile], trait_: hir::Trait, impl_: &ast::Impl, - target_scope: &hir::SemanticsScope<'_>, + target_scope: &hir::SemanticsScope<'db>, ) -> Vec { let new_indent_level = IndentLevel::from_node(impl_.syntax()) + 1; original_items diff --git a/crates/ide-completion/src/completions.rs b/crates/ide-completion/src/completions.rs index f1a34f15d0a5..a7350467089b 100644 --- a/crates/ide-completion/src/completions.rs +++ b/crates/ide-completion/src/completions.rs @@ -64,7 +64,7 @@ impl From for Vec { } } -impl Builder { +impl<'db> Builder<'db> { /// Convenience method, which allows to add a freshly created completion into accumulator /// without binding it to the variable. pub(crate) fn add_to(self, acc: &mut Completions, db: &RootDatabase) { @@ -314,11 +314,11 @@ impl Completions { .add_to(self, ctx.db); } - pub(crate) fn add_function( + pub(crate) fn add_function<'db>( &mut self, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, - func: hir::Function, + func: hir::Function<'db>, local_name: Option, ) { let is_private_editable = match ctx.is_visible(&func) { @@ -336,11 +336,11 @@ impl Completions { .add_to(self, ctx.db); } - pub(crate) fn add_method( + pub(crate) fn add_method<'db>( &mut self, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, dot_access: &DotAccess<'_>, - func: hir::Function, + func: hir::Function<'db>, receiver: Option, local_name: Option, ) { @@ -360,12 +360,12 @@ impl Completions { .add_to(self, ctx.db); } - pub(crate) fn add_method_with_import( + pub(crate) fn add_method_with_import<'db>( &mut self, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, dot_access: &DotAccess<'_>, - func: hir::Function, - import: LocatedImport, + func: hir::Function<'db>, + import: LocatedImport<'db>, ) { let is_private_editable = match ctx.is_visible(&func) { Visible::Yes => false, diff --git a/crates/ide-completion/src/completions/dot.rs b/crates/ide-completion/src/completions/dot.rs index 774e14df4834..80a4085a0b8b 100644 --- a/crates/ide-completion/src/completions/dot.rs +++ b/crates/ide-completion/src/completions/dot.rs @@ -16,10 +16,10 @@ use crate::{ }; /// Complete dot accesses, i.e. fields or methods. -pub(crate) fn complete_dot( +pub(crate) fn complete_dot<'db>( acc: &mut Completions, - ctx: &CompletionContext<'_, '_>, - dot_access: &DotAccess<'_>, + ctx: &CompletionContext<'_, 'db>, + dot_access: &DotAccess<'db>, ) { let receiver_ty = match dot_access { DotAccess { receiver_ty: Some(receiver_ty), .. } => &receiver_ty.original, @@ -124,11 +124,11 @@ pub(crate) fn complete_dot( } } -pub(crate) fn complete_undotted_self( +pub(crate) fn complete_undotted_self<'db>( acc: &mut Completions, - ctx: &CompletionContext<'_, '_>, + ctx: &CompletionContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, - expr_ctx: &PathExprCtx<'_>, + expr_ctx: &PathExprCtx<'db>, ) { if !ctx.config.enable_self_on_the_fly { return; @@ -226,11 +226,11 @@ fn complete_fields( } } -fn complete_methods( - ctx: &CompletionContext<'_, '_>, - receiver: &hir::Type<'_>, +fn complete_methods<'db>( + ctx: &CompletionContext<'_, 'db>, + receiver: &hir::Type<'db>, traits_in_scope: &FxHashSet, - f: impl FnMut(hir::Function), + f: impl FnMut(hir::Function<'db>), ) { struct Callback<'a, 'db, F> { ctx: &'a CompletionContext<'a, 'db>, @@ -238,19 +238,19 @@ fn complete_methods( // We deliberately deduplicate by function ID and not name, because while inherent methods cannot be // duplicated, trait methods can. And it is still useful to show all of them (even when there // is also an inherent method, especially considering that it may be private, and filtered later). - seen_methods: FxHashSet, + seen_methods: FxHashSet>, // However, duplicate inherent methods is usually meaningless // https://github.com/rust-lang/rust-analyzer/issues/20773#issuecomment-4302781553 - seen_inherent_methods: FxHashMap, + seen_inherent_methods: FxHashMap>, } - impl MethodCandidateCallback for Callback<'_, '_, F> + impl<'db, F> MethodCandidateCallback<'db> for Callback<'_, 'db, F> where - F: FnMut(hir::Function), + F: FnMut(hir::Function<'db>), { // We don't want to exclude inherent trait methods - that is, methods of traits available from // `where` clauses or `dyn Trait`. - fn on_inherent_method(&mut self, func: hir::Function) -> ControlFlow<()> { + fn on_inherent_method(&mut self, func: hir::Function<'db>) -> ControlFlow<()> { if func.self_param(self.ctx.db).is_some() && self.seen_methods.insert(func) { let same_name = self.seen_inherent_methods.entry(func.name(self.ctx.db)); let do_complete = match &same_name { @@ -271,7 +271,7 @@ fn complete_methods( ControlFlow::Continue(()) } - fn on_trait_method(&mut self, func: hir::Function) -> ControlFlow<()> { + fn on_trait_method(&mut self, func: hir::Function<'db>) -> ControlFlow<()> { // This needs to come before the `seen_methods` test, so that if we see the same method twice, // once as inherent and once not, we will include it. if let ItemContainer::Trait(trait_) = func.container(self.ctx.db) diff --git a/crates/ide-completion/src/completions/expr.rs b/crates/ide-completion/src/completions/expr.rs index 3e95128bd70e..2cc8ba31f07e 100644 --- a/crates/ide-completion/src/completions/expr.rs +++ b/crates/ide-completion/src/completions/expr.rs @@ -16,21 +16,21 @@ struct PathCallback<'a, 'db, F> { ctx: &'a CompletionContext<'a, 'db>, acc: &'a mut Completions, add_assoc_item: F, - seen: FxHashSet, + seen: FxHashSet>, } -impl PathCandidateCallback for PathCallback<'_, '_, F> +impl<'db, F> PathCandidateCallback<'db> for PathCallback<'_, 'db, F> where - F: FnMut(&mut Completions, hir::AssocItem), + F: FnMut(&mut Completions, hir::AssocItem<'db>), { - fn on_inherent_item(&mut self, item: hir::AssocItem) -> ControlFlow<()> { + fn on_inherent_item(&mut self, item: hir::AssocItem<'db>) -> ControlFlow<()> { if self.seen.insert(item) { (self.add_assoc_item)(self.acc, item); } ControlFlow::Continue(()) } - fn on_trait_item(&mut self, item: hir::AssocItem) -> ControlFlow<()> { + fn on_trait_item(&mut self, item: hir::AssocItem<'db>) -> ControlFlow<()> { // The excluded check needs to come before the `seen` test, so that if we see the same method twice, // once as inherent and once not, we will include it. if item.container_trait(self.ctx.db).is_none_or(|trait_| { @@ -47,7 +47,7 @@ where pub(crate) fn complete_expr_path<'db>( acc: &mut Completions, ctx: &CompletionContext<'_, 'db>, - path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'_>, + path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'db>, expr_ctx: &PathExprCtx<'_>, ) { let _p = tracing::info_span!("complete_expr_path").entered(); diff --git a/crates/ide-completion/src/completions/flyimport.rs b/crates/ide-completion/src/completions/flyimport.rs index 972cc6d32fef..aaaab426b437 100644 --- a/crates/ide-completion/src/completions/flyimport.rs +++ b/crates/ide-completion/src/completions/flyimport.rs @@ -218,7 +218,7 @@ fn import_on_the_fly<'db>( ImportScope::find_insert_use_container(&position, &ctx.sema)?; - let ns_filter = |import: &LocatedImport| { + let ns_filter = |import: &LocatedImport<'_>| { match (kind, import.original_item) { // Aren't handled in flyimport (PathKind::Vis { .. } | PathKind::Use, _) => false, @@ -309,7 +309,7 @@ fn import_on_the_fly_pat_<'db>( ImportScope::find_insert_use_container(&position, &ctx.sema)?; - let ns_filter = |import: &LocatedImport| match import.original_item { + let ns_filter = |import: &LocatedImport<'_>| match import.original_item { ItemInNs::Macros(mac) => mac.is_fn_like(ctx.db), ItemInNs::Types(_) => true, ItemInNs::Values(def) => matches!(def, hir::ModuleDef::Const(_)), @@ -393,7 +393,7 @@ fn import_on_the_fly_method<'db>( Some(()) } -fn filter_excluded_flyimport(ctx: &CompletionContext<'_, '_>, import: &LocatedImport) -> bool { +fn filter_excluded_flyimport(ctx: &CompletionContext<'_, '_>, import: &LocatedImport<'_>) -> bool { let def = import.item_to_import.into_module_def(); let is_exclude_flyimport = ctx.exclude_flyimport.get(&def).copied(); diff --git a/crates/ide-completion/src/completions/item_list/trait_impl.rs b/crates/ide-completion/src/completions/item_list/trait_impl.rs index a705bca63fbc..21ece4f3f701 100644 --- a/crates/ide-completion/src/completions/item_list/trait_impl.rs +++ b/crates/ide-completion/src/completions/item_list/trait_impl.rs @@ -184,8 +184,8 @@ fn add_function_impl( acc: &mut Completions, ctx: &CompletionContext<'_, '_>, replacement_range: TextRange, - func: hir::Function, - impl_def: hir::Impl, + func: hir::Function<'_>, + impl_def: hir::Impl<'_>, ) { let fn_name = &func.name(ctx.db); let sugar: &[_] = if func.is_async(ctx.db) { @@ -204,8 +204,8 @@ fn add_function_impl_( acc: &mut Completions, ctx: &CompletionContext<'_, '_>, replacement_range: TextRange, - func: hir::Function, - impl_def: hir::Impl, + func: hir::Function<'_>, + impl_def: hir::Impl<'_>, fn_name: &Name, async_sugaring: AsyncSugaring, ) { @@ -261,10 +261,10 @@ enum AsyncSugaring { } /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc. -fn get_transformed_assoc_item( - ctx: &CompletionContext<'_, '_>, +fn get_transformed_assoc_item<'db>( + ctx: &CompletionContext<'_, 'db>, assoc_item: ast::AssocItem, - impl_def: hir::Impl, + impl_def: hir::Impl<'_>, macro_file: Option, ) -> Option { let trait_ = impl_def.trait_(ctx.db)?; @@ -292,10 +292,10 @@ fn get_transformed_assoc_item( } /// Transform a relevant associated item to inline generics from the impl, remove attrs and docs, etc. -fn get_transformed_fn( - ctx: &CompletionContext<'_, '_>, +fn get_transformed_fn<'db>( + ctx: &CompletionContext<'_, 'db>, fn_: ast::Fn, - impl_def: hir::Impl, + impl_def: hir::Impl<'_>, async_: AsyncSugaring, ) -> Option { let trait_ = impl_def.trait_(ctx.db)?; @@ -379,7 +379,7 @@ fn add_type_alias_impl( ctx: &CompletionContext<'_, '_>, replacement_range: TextRange, type_alias: hir::TypeAlias, - impl_def: hir::Impl, + impl_def: hir::Impl<'_>, ) { let alias_name = type_alias.name(ctx.db).as_str().to_smolstr(); @@ -462,7 +462,7 @@ fn add_const_impl( ctx: &CompletionContext<'_, '_>, replacement_range: TextRange, const_: hir::Const, - impl_def: hir::Impl, + impl_def: hir::Impl<'_>, ) { let const_name = const_.name(ctx.db).map(|n| n.display_no_db(ctx.edition).to_smolstr()); diff --git a/crates/ide-completion/src/completions/lifetime.rs b/crates/ide-completion/src/completions/lifetime.rs index 6291b42a0368..4ee764023368 100644 --- a/crates/ide-completion/src/completions/lifetime.rs +++ b/crates/ide-completion/src/completions/lifetime.rs @@ -18,7 +18,7 @@ use crate::{ pub(crate) fn complete_lifetime( acc: &mut Completions, ctx: &CompletionContext<'_, '_>, - lifetime_ctx: &LifetimeContext, + lifetime_ctx: &LifetimeContext<'_>, ) { let &LifetimeContext { kind: LifetimeKind::Lifetime { in_lifetime_param_bound, def }, .. } = lifetime_ctx @@ -45,7 +45,7 @@ pub(crate) fn complete_lifetime( pub(crate) fn complete_label( acc: &mut Completions, ctx: &CompletionContext<'_, '_>, - lifetime_ctx: &LifetimeContext, + lifetime_ctx: &LifetimeContext<'_>, ) { if !matches!(lifetime_ctx, LifetimeContext { kind: LifetimeKind::LabelRef, .. }) { return; diff --git a/crates/ide-completion/src/completions/pattern.rs b/crates/ide-completion/src/completions/pattern.rs index 7b887fb7d7b2..31e1cb659d68 100644 --- a/crates/ide-completion/src/completions/pattern.rs +++ b/crates/ide-completion/src/completions/pattern.rs @@ -126,10 +126,10 @@ pub(crate) fn complete_pattern( }); } -pub(crate) fn complete_pattern_path( +pub(crate) fn complete_pattern_path<'db>( acc: &mut Completions, - ctx: &CompletionContext<'_, '_>, - path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'_>, + ctx: &CompletionContext<'_, 'db>, + path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'db>, ) { match qualified { Qualified::With { resolution: Some(resolution), super_chain_len, .. } => { diff --git a/crates/ide-completion/src/completions/postfix.rs b/crates/ide-completion/src/completions/postfix.rs index 34b53e5e5bfe..3ba1e742529b 100644 --- a/crates/ide-completion/src/completions/postfix.rs +++ b/crates/ide-completion/src/completions/postfix.rs @@ -477,7 +477,7 @@ fn build_postfix_snippet_builder<'ctx>( ctx: &'ctx CompletionContext<'_, '_>, cap: SnippetCap, receiver: &'ctx ast::Expr, -) -> Option Builder + 'ctx> { +) -> Option Builder<'static> + 'ctx> { let receiver_range = ctx.sema.original_range_opt(receiver.syntax())?.range; if ctx.source_range().end() < receiver_range.start() { // This shouldn't happen, yet it does. I assume this might be due to an incorrect token @@ -493,7 +493,7 @@ fn build_postfix_snippet_builder<'ctx>( ctx: &'ctx CompletionContext<'_, '_>, cap: SnippetCap, delete_range: TextRange, - ) -> impl Fn(&str, &str, String) -> Builder + 'ctx { + ) -> impl Fn(&str, &str, String) -> Builder<'static> + 'ctx { move |label, detail, snippet| { let edit = TextEdit::replace(delete_range, snippet); let mut item = CompletionItem::new( @@ -521,7 +521,7 @@ fn build_postfix_snippet_builder<'ctx>( fn add_custom_postfix_completions( acc: &mut Completions, ctx: &CompletionContext<'_, '_>, - postfix_snippet: impl Fn(&str, &str, String) -> Builder, + postfix_snippet: impl Fn(&str, &str, String) -> Builder<'static>, receiver_text: &str, ) -> Option<()> { ImportScope::find_insert_use_container(&ctx.token.parent()?, &ctx.sema)?; diff --git a/crates/ide-completion/src/completions/snippet.rs b/crates/ide-completion/src/completions/snippet.rs index 7432c5226bfa..046cd36f9c91 100644 --- a/crates/ide-completion/src/completions/snippet.rs +++ b/crates/ide-completion/src/completions/snippet.rs @@ -122,7 +122,7 @@ fn snippet( cap: SnippetCap, label: &str, snippet: &str, -) -> Builder { +) -> Builder<'static> { let mut item = CompletionItem::new(CompletionItemKind::Snippet, ctx.source_range(), label, ctx.edition); item.insert_snippet(cap, snippet); diff --git a/crates/ide-completion/src/completions/type.rs b/crates/ide-completion/src/completions/type.rs index 391152f438b6..b2d8e9da51fc 100644 --- a/crates/ide-completion/src/completions/type.rs +++ b/crates/ide-completion/src/completions/type.rs @@ -12,7 +12,7 @@ use crate::{ pub(crate) fn complete_type_path<'db>( acc: &mut Completions, ctx: &CompletionContext<'_, 'db>, - path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'_>, + path_ctx @ PathCompletionCtx { qualified, .. }: &PathCompletionCtx<'db>, location: &TypeLocation, ) { let _p = tracing::info_span!("complete_type_path").entered(); diff --git a/crates/ide-completion/src/context.rs b/crates/ide-completion/src/context.rs index 705305f557e9..f06016a9588d 100644 --- a/crates/ide-completion/src/context.rs +++ b/crates/ide-completion/src/context.rs @@ -178,7 +178,7 @@ pub(crate) struct PathExprCtx<'db> { pub(crate) after_amp: bool, /// The surrounding RecordExpression we are completing a functional update pub(crate) is_func_update: Option, - pub(crate) self_param: Option>>, + pub(crate) self_param: Option, hir::Param<'db>>>, pub(crate) innermost_ret_ty: Option>, pub(crate) innermost_breakable_ty: Option>, pub(crate) impl_: Option, @@ -322,15 +322,15 @@ pub(crate) struct ParamContext { /// The state of the lifetime we are completing. #[derive(Debug)] -pub(crate) struct LifetimeContext { - pub(crate) kind: LifetimeKind, +pub(crate) struct LifetimeContext<'db> { + pub(crate) kind: LifetimeKind<'db>, } /// The kind of lifetime we are completing. #[derive(Debug)] -pub(crate) enum LifetimeKind { +pub(crate) enum LifetimeKind<'db> { LifetimeParam, - Lifetime { in_lifetime_param_bound: bool, def: Option }, + Lifetime { in_lifetime_param_bound: bool, def: Option> }, LabelRef, LabelDef, } @@ -397,7 +397,7 @@ pub(crate) enum NameRefKind<'db> { pub(crate) enum CompletionAnalysis<'db> { Name(NameContext), NameRef(NameRefContext<'db>), - Lifetime(LifetimeContext), + Lifetime(LifetimeContext<'db>), /// The string the cursor is currently inside String { /// original token @@ -476,7 +476,7 @@ pub(crate) struct CompletionContext<'a, 'db> { /// The module of the `scope`. pub(crate) module: hir::Module, /// The function where we're completing, if inside a function. - pub(crate) containing_function: Option, + pub(crate) containing_function: Option>, /// Whether nightly toolchain is used. Cached since this is looked up a lot. pub(crate) is_nightly: bool, /// The edition of the current crate @@ -505,7 +505,7 @@ pub(crate) struct CompletionContext<'a, 'db> { /// importing those traits. /// /// Note the trait *themselves* are not excluded, only their methods are. - pub(crate) exclude_flyimport: FxHashMap, + pub(crate) exclude_flyimport: FxHashMap, AutoImportExclusionType>, /// Traits whose methods should always be excluded, even when in scope (compare `exclude_flyimport_traits`). /// They will *not* be excluded, however, if they are available as a generic bound. /// @@ -587,7 +587,7 @@ impl<'db> CompletionContext<'_, 'db> { } /// Check if an item is `#[doc(hidden)]`. - pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs) -> bool { + pub(crate) fn is_item_hidden(&self, item: &hir::ItemInNs<'_>) -> bool { let attrs = item.attrs(self.db); let krate = item.krate(self.db); match (attrs, krate) { @@ -648,8 +648,8 @@ impl<'db> CompletionContext<'_, 'db> { pub(crate) fn iterate_path_candidates( &self, - ty: &hir::Type<'_>, - mut cb: impl FnMut(hir::AssocItem), + ty: &hir::Type<'db>, + mut cb: impl FnMut(hir::AssocItem<'db>), ) { let mut seen = FxHashSet::default(); ty.iterate_path_candidates(self.db, &self.scope, &self.traits_in_scope(), None, |item| { diff --git a/crates/ide-completion/src/context/analysis.rs b/crates/ide-completion/src/context/analysis.rs index 7280fd1ad575..6e0597074de1 100644 --- a/crates/ide-completion/src/context/analysis.rs +++ b/crates/ide-completion/src/context/analysis.rs @@ -879,11 +879,11 @@ fn expected_type_and_name<'db>( (ty.map(strip_refs), name) } -fn classify_lifetime( +fn classify_lifetime<'db>( sema: &Semantics<'_, RootDatabase>, original_file: &SyntaxNode, lifetime: ast::Lifetime, -) -> Option { +) -> Option> { let parent = lifetime.syntax().parent()?; if parent.kind() == SyntaxKind::ERROR { return None; diff --git a/crates/ide-completion/src/item.rs b/crates/ide-completion/src/item.rs index 675ffac04029..05f3f3556b42 100644 --- a/crates/ide-completion/src/item.rs +++ b/crates/ide-completion/src/item.rs @@ -472,12 +472,12 @@ pub enum CompletionItemRefMode { } impl CompletionItem { - pub(crate) fn new( + pub(crate) fn new<'db>( kind: impl Into, source_range: TextRange, label: impl Into, edition: Edition, - ) -> Builder { + ) -> Builder<'db> { let label = label.into(); Builder { source_range, @@ -528,9 +528,9 @@ impl CompletionItem { /// A helper to make `CompletionItem`s. #[must_use] #[derive(Debug, Clone)] -pub(crate) struct Builder { +pub(crate) struct Builder<'db> { source_range: TextRange, - imports_to_add: SmallVec<[LocatedImport; 1]>, + imports_to_add: SmallVec<[LocatedImport<'db>; 1]>, trait_name: Option, doc_aliases: Vec, adds_text: Option, @@ -550,8 +550,8 @@ pub(crate) struct Builder { edition: Edition, } -impl Builder { - pub(crate) fn from_resolution<'db>( +impl<'db> Builder<'db> { + pub(crate) fn from_resolution( ctx: &CompletionContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, @@ -661,27 +661,27 @@ impl Builder { import_to_add, } } - pub(crate) fn lookup_by(&mut self, lookup: impl Into) -> &mut Builder { + pub(crate) fn lookup_by(&mut self, lookup: impl Into) -> &mut Builder<'db> { self.lookup = Some(lookup.into()); self } - pub(crate) fn label(&mut self, label: impl Into) -> &mut Builder { + pub(crate) fn label(&mut self, label: impl Into) -> &mut Builder<'db> { self.label = label.into(); self } - pub(crate) fn trait_name(&mut self, trait_name: SmolStr) -> &mut Builder { + pub(crate) fn trait_name(&mut self, trait_name: SmolStr) -> &mut Builder<'db> { self.trait_name = Some(trait_name); self } - pub(crate) fn doc_aliases(&mut self, doc_aliases: Vec) -> &mut Builder { + pub(crate) fn doc_aliases(&mut self, doc_aliases: Vec) -> &mut Builder<'db> { self.doc_aliases = doc_aliases; self } - pub(crate) fn adds_text(&mut self, adds_text: SmolStr) -> &mut Builder { + pub(crate) fn adds_text(&mut self, adds_text: SmolStr) -> &mut Builder<'db> { self.adds_text = Some(adds_text); self } - pub(crate) fn insert_text(&mut self, insert_text: impl Into) -> &mut Builder { + pub(crate) fn insert_text(&mut self, insert_text: impl Into) -> &mut Builder<'db> { self.insert_text = Some(insert_text.into()); self } @@ -689,23 +689,23 @@ impl Builder { &mut self, cap: SnippetCap, snippet: impl Into, - ) -> &mut Builder { + ) -> &mut Builder<'db> { let _ = cap; self.is_snippet = true; self.insert_text(snippet) } - pub(crate) fn text_edit(&mut self, edit: TextEdit) -> &mut Builder { + pub(crate) fn text_edit(&mut self, edit: TextEdit) -> &mut Builder<'db> { self.text_edit = Some(edit); self } - pub(crate) fn snippet_edit(&mut self, _cap: SnippetCap, edit: TextEdit) -> &mut Builder { + pub(crate) fn snippet_edit(&mut self, _cap: SnippetCap, edit: TextEdit) -> &mut Builder<'db> { self.is_snippet = true; self.text_edit(edit) } - pub(crate) fn detail(&mut self, detail: impl Into) -> &mut Builder { + pub(crate) fn detail(&mut self, detail: impl Into) -> &mut Builder<'db> { self.set_detail(Some(detail)) } - pub(crate) fn set_detail(&mut self, detail: Option>) -> &mut Builder { + pub(crate) fn set_detail(&mut self, detail: Option>) -> &mut Builder<'db> { self.detail = detail.map(Into::into); if let Some(detail) = &self.detail && never!(detail.contains('\n'), "multiline detail:\n{}", detail) @@ -715,18 +715,21 @@ impl Builder { self } #[allow(unused)] - pub(crate) fn documentation(&mut self, docs: Documentation<'_>) -> &mut Builder { + pub(crate) fn documentation(&mut self, docs: Documentation<'_>) -> &mut Builder<'db> { self.set_documentation(Some(docs)) } - pub(crate) fn set_documentation(&mut self, docs: Option>) -> &mut Builder { + pub(crate) fn set_documentation( + &mut self, + docs: Option>, + ) -> &mut Builder<'db> { self.documentation = docs.map(Documentation::into_owned); self } - pub(crate) fn set_deprecated(&mut self, deprecated: bool) -> &mut Builder { + pub(crate) fn set_deprecated(&mut self, deprecated: bool) -> &mut Builder<'db> { self.deprecated = deprecated; self } - pub(crate) fn set_relevance(&mut self, relevance: CompletionRelevance) -> &mut Builder { + pub(crate) fn set_relevance(&mut self, relevance: CompletionRelevance) -> &mut Builder<'db> { // The default value of `CompletionRelevance.is_deprecated` is `false`, so it being `true` // would mean it was set manually. Advise using the other function instead. // @@ -742,15 +745,15 @@ impl Builder { pub(crate) fn with_relevance( &mut self, relevance: impl FnOnce(CompletionRelevance) -> CompletionRelevance, - ) -> &mut Builder { + ) -> &mut Builder<'db> { self.relevance = relevance(mem::take(&mut self.relevance)); self } - pub(crate) fn trigger_call_info(&mut self) -> &mut Builder { + pub(crate) fn trigger_call_info(&mut self) -> &mut Builder<'db> { self.trigger_call_info = true; self } - pub(crate) fn add_import(&mut self, import_to_add: LocatedImport) -> &mut Builder { + pub(crate) fn add_import(&mut self, import_to_add: LocatedImport<'db>) -> &mut Builder<'db> { self.imports_to_add.push(import_to_add); self } @@ -758,7 +761,7 @@ impl Builder { &mut self, ref_mode: CompletionItemRefMode, offset: TextSize, - ) -> &mut Builder { + ) -> &mut Builder<'db> { self.ref_match = Some((ref_mode, offset)); self } diff --git a/crates/ide-completion/src/render.rs b/crates/ide-completion/src/render.rs index 43b2a53a7f7e..bcf1b4b99a42 100644 --- a/crates/ide-completion/src/render.rs +++ b/crates/ide-completion/src/render.rs @@ -38,7 +38,7 @@ use crate::{ pub(crate) struct RenderContext<'a, 'db> { completion: &'a CompletionContext<'a, 'db>, is_private_editable: bool, - import_to_add: Option, + import_to_add: Option>, doc_aliases: Vec, } @@ -57,7 +57,7 @@ impl<'a, 'db> RenderContext<'a, 'db> { self } - pub(crate) fn import_to_add(mut self, import_to_add: Option) -> Self { + pub(crate) fn import_to_add(mut self, import_to_add: Option>) -> Self { self.import_to_add = import_to_add; self } @@ -110,7 +110,11 @@ impl<'a, 'db> RenderContext<'a, 'db> { /// ``` /// /// [`try_as_dyn`]: https://doc.rust-lang.org/std/any/fn.try_as_dyn.html - fn is_deprecated(&self, def: impl HasAttrs, def_as_assoc_item: Option) -> bool { + fn is_deprecated( + &self, + def: impl HasAttrs, + def_as_assoc_item: Option>, + ) -> bool { let db = self.db(); def.attrs(db).is_deprecated() || def_as_assoc_item @@ -258,7 +262,7 @@ pub(crate) fn render_path_resolution<'db>( path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, resolution: ScopeDef<'db>, -) -> Builder { +) -> Builder<'db> { render_resolution_path(ctx, path_ctx, local_name, None, resolution) } @@ -267,15 +271,15 @@ pub(crate) fn render_pattern_resolution<'db>( pattern_ctx: &PatternContext, local_name: hir::Name, resolution: ScopeDef<'db>, -) -> Builder { +) -> Builder<'db> { render_resolution_pat(ctx, pattern_ctx, local_name, None, resolution) } -pub(crate) fn render_resolution_with_import( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_resolution_with_import<'db>( + ctx: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, - import_edit: LocatedImport, -) -> Option { + import_edit: LocatedImport<'db>, +) -> Option> { let resolution = ScopeDef::from(import_edit.original_item); let local_name = get_import_name(resolution, &ctx, &import_edit)?; // This now just renders the alias text, but we need to find the aliases earlier and call this with the alias instead. @@ -284,11 +288,11 @@ pub(crate) fn render_resolution_with_import( Some(render_resolution_path(ctx, path_ctx, local_name, Some(import_edit), resolution)) } -pub(crate) fn render_resolution_with_import_pat( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_resolution_with_import_pat<'db>( + ctx: RenderContext<'_, 'db>, pattern_ctx: &PatternContext, - import_edit: LocatedImport, -) -> Option { + import_edit: LocatedImport<'db>, +) -> Option> { let resolution = ScopeDef::from(import_edit.original_item); let local_name = get_import_name(resolution, &ctx, &import_edit)?; Some(render_resolution_pat(ctx, pattern_ctx, local_name, Some(import_edit), resolution)) @@ -297,7 +301,7 @@ pub(crate) fn render_resolution_with_import_pat( pub(crate) fn render_expr<'db>( ctx: &CompletionContext<'_, 'db>, expr: &hir::term_search::Expr<'db>, -) -> Option { +) -> Option> { let mut i = 1; let mut snippet_formatter = |ty: &hir::Type<'_>| { let arg_name = ty @@ -359,7 +363,7 @@ pub(crate) fn render_expr<'db>( fn get_import_name<'db>( resolution: ScopeDef<'db>, ctx: &RenderContext<'_, 'db>, - import_edit: &LocatedImport, + import_edit: &LocatedImport<'db>, ) -> Option { // FIXME: Temporary workaround for handling aliased import. // This should be removed after we have proper support for importing alias. @@ -377,7 +381,7 @@ fn get_import_name<'db>( fn scope_def_to_name<'db>( resolution: ScopeDef<'db>, ctx: &RenderContext<'_, 'db>, - import_edit: &LocatedImport, + import_edit: &LocatedImport<'db>, ) -> Option { Some(match resolution { ScopeDef::ModuleDef(hir::ModuleDef::Function(f)) => f.name(ctx.completion.db), @@ -391,9 +395,9 @@ fn render_resolution_pat<'db>( ctx: RenderContext<'_, 'db>, pattern_ctx: &PatternContext, local_name: hir::Name, - import_to_add: Option, + import_to_add: Option>, resolution: ScopeDef<'db>, -) -> Builder { +) -> Builder<'db> { let _p = tracing::info_span!("render_resolution_pat").entered(); use hir::ModuleDef::*; @@ -409,9 +413,9 @@ fn render_resolution_path<'db>( ctx: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: hir::Name, - import_to_add: Option, + import_to_add: Option>, resolution: ScopeDef<'db>, -) -> Builder { +) -> Builder<'db> { let _p = tracing::info_span!("render_resolution_path").entered(); use hir::ModuleDef::*; @@ -531,9 +535,9 @@ fn render_resolution_path<'db>( fn render_resolution_simple_<'db>( ctx: RenderContext<'_, 'db>, local_name: &hir::Name, - import_to_add: Option, + import_to_add: Option>, resolution: ScopeDef<'db>, -) -> Builder { +) -> Builder<'db> { let _p = tracing::info_span!("render_resolution_simple_").entered(); let db = ctx.db(); @@ -621,12 +625,12 @@ fn scope_def_is_deprecated(ctx: &RenderContext<'_, '_>, resolution: ScopeDef<'_> } } -pub(crate) fn render_type_keyword_snippet( +pub(crate) fn render_type_keyword_snippet<'db>( ctx: &CompletionContext<'_, '_>, path_ctx: &PathCompletionCtx<'_>, label: &str, snippet: &str, -) -> Builder { +) -> Builder<'db> { let source_range = ctx.source_range(); let mut item = CompletionItem::new(CompletionItemKind::Keyword, source_range, label, ctx.edition); @@ -648,7 +652,7 @@ pub(crate) fn render_type_keyword_snippet( fn adds_ret_type_arrow( ctx: &CompletionContext<'_, '_>, path_ctx: &PathCompletionCtx<'_>, - item: &mut Builder, + item: &mut Builder<'_>, insert_text: String, ) { if let Some((arrow, at)) = path_ctx.required_thin_arrow() { @@ -759,7 +763,7 @@ fn path_ref_match( completion: &CompletionContext<'_, '_>, path_ctx: &PathCompletionCtx<'_>, ty: &hir::Type<'_>, - item: &mut Builder, + item: &mut Builder<'_>, ) { if let Some(original_path) = &path_ctx.original_path { // At least one char was typed by the user already, in that case look for the original path diff --git a/crates/ide-completion/src/render/function.rs b/crates/ide-completion/src/render/function.rs index 4698a9cd4a0c..926088325204 100644 --- a/crates/ide-completion/src/render/function.rs +++ b/crates/ide-completion/src/render/function.rs @@ -26,33 +26,33 @@ enum FuncKind<'ctx> { Method(&'ctx DotAccess<'ctx>, Option), } -pub(crate) fn render_fn( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_fn<'db>( + ctx: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: Option, - func: hir::Function, -) -> Builder { + func: hir::Function<'db>, +) -> Builder<'db> { let _p = tracing::info_span!("render_fn").entered(); render(ctx, local_name, func, FuncKind::Function(path_ctx)) } -pub(crate) fn render_method( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_method<'db>( + ctx: RenderContext<'_, 'db>, dot_access: &DotAccess<'_>, receiver: Option, local_name: Option, - func: hir::Function, -) -> Builder { + func: hir::Function<'db>, +) -> Builder<'db> { let _p = tracing::info_span!("render_method").entered(); render(ctx, local_name, func, FuncKind::Method(dot_access, receiver)) } -fn render( - ctx @ RenderContext { completion, .. }: RenderContext<'_, '_>, +fn render<'db>( + ctx @ RenderContext { completion, .. }: RenderContext<'_, 'db>, local_name: Option, - func: hir::Function, + func: hir::Function<'db>, func_kind: FuncKind<'_>, -) -> Builder { +) -> Builder<'db> { let db = completion.db; let name = local_name.unwrap_or_else(|| func.name(db)); @@ -209,16 +209,16 @@ fn compute_return_type_match( } } -pub(super) fn add_call_parens<'b>( - builder: &'b mut Builder, +pub(super) fn add_call_parens<'b, 'db>( + builder: &'b mut Builder<'db>, ctx: &CompletionContext<'_, '_>, cap: SnippetCap, name: SmolStr, escaped_name: SmolStr, - self_param: Option, + self_param: Option>, params: Vec>, ret_type: &hir::Type<'_>, -) -> &'b mut Builder { +) -> &'b mut Builder<'db> { cov_mark::hit!(inserts_parens_for_function_calls); let (mut snippet, label_suffix) = if self_param.is_none() && params.is_empty() { @@ -305,7 +305,7 @@ fn ref_of_param(ctx: &CompletionContext<'_, '_>, arg: &str, ty: &hir::Type<'_>) "" } -fn detail(ctx: &CompletionContext<'_, '_>, func: hir::Function) -> String { +fn detail(ctx: &CompletionContext<'_, '_>, func: hir::Function<'_>) -> String { let mut ret_ty = func.ret_type(ctx.db); let mut detail = String::new(); @@ -331,7 +331,7 @@ fn detail(ctx: &CompletionContext<'_, '_>, func: hir::Function) -> String { detail } -fn detail_full(ctx: &CompletionContext<'_, '_>, func: hir::Function) -> String { +fn detail_full(ctx: &CompletionContext<'_, '_>, func: hir::Function<'_>) -> String { let signature = format!("{}", func.display(ctx.db, ctx.display_target)); let mut detail = String::with_capacity(signature.len()); @@ -346,7 +346,7 @@ fn detail_full(ctx: &CompletionContext<'_, '_>, func: hir::Function) -> String { detail } -fn params_display(ctx: &CompletionContext<'_, '_>, detail: &mut String, func: hir::Function) { +fn params_display(ctx: &CompletionContext<'_, '_>, detail: &mut String, func: hir::Function<'_>) { if let Some(self_param) = func.self_param(ctx.db) { format_to!(detail, "{}", self_param.display(ctx.db, ctx.display_target)); let assoc_fn_params = func.assoc_fn_params(ctx.db); @@ -373,10 +373,10 @@ fn params_display(ctx: &CompletionContext<'_, '_>, detail: &mut String, func: hi fn params<'db>( ctx: &CompletionContext<'_, 'db>, - func: hir::Function, + func: hir::Function<'db>, func_kind: &FuncKind<'_>, has_dot_receiver: bool, -) -> Option<(Option, Vec>)> { +) -> Option<(Option>, Vec>)> { ctx.config.callable.as_ref()?; // Don't add parentheses if the expected type is a function reference with the same signature. diff --git a/crates/ide-completion/src/render/literal.rs b/crates/ide-completion/src/render/literal.rs index 943ff5821969..32cca145c30d 100644 --- a/crates/ide-completion/src/render/literal.rs +++ b/crates/ide-completion/src/render/literal.rs @@ -19,13 +19,13 @@ use crate::{ }, }; -pub(crate) fn render_variant_lit( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_variant_lit<'db>( + ctx: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, local_name: Option, variant: hir::EnumVariant, path: Option, -) -> Option { +) -> Option> { let _p = tracing::info_span!("render_variant_lit").entered(); let db = ctx.db(); @@ -33,13 +33,13 @@ pub(crate) fn render_variant_lit( render(ctx, path_ctx, Variant::EnumVariant(variant), name, path) } -pub(crate) fn render_struct_literal( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_struct_literal<'db>( + ctx: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, strukt: hir::Struct, path: Option, local_name: Option, -) -> Option { +) -> Option> { let _p = tracing::info_span!("render_struct_literal").entered(); let db = ctx.db(); @@ -47,13 +47,13 @@ pub(crate) fn render_struct_literal( render(ctx, path_ctx, Variant::Struct(strukt), name, path) } -fn render( - ctx @ RenderContext { completion, .. }: RenderContext<'_, '_>, +fn render<'db>( + ctx @ RenderContext { completion, .. }: RenderContext<'_, 'db>, path_ctx: &PathCompletionCtx<'_>, thing: Variant, name: hir::Name, path: Option, -) -> Option { +) -> Option> { let db = completion.db; let mut kind = thing.kind(db); let should_add_parens = !matches!( diff --git a/crates/ide-completion/src/render/macro_.rs b/crates/ide-completion/src/render/macro_.rs index 85a0761c17e0..d18b6f1c857d 100644 --- a/crates/ide-completion/src/render/macro_.rs +++ b/crates/ide-completion/src/render/macro_.rs @@ -10,35 +10,35 @@ use crate::{ render::RenderContext, }; -pub(crate) fn render_macro( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_macro<'db>( + ctx: RenderContext<'_, 'db>, PathCompletionCtx { kind, has_macro_bang, has_call_parens, .. }: &PathCompletionCtx<'_>, name: hir::Name, macro_: hir::Macro, -) -> Builder { +) -> Builder<'db> { let _p = tracing::info_span!("render_macro").entered(); render(ctx, *kind == PathKind::Use, *has_macro_bang, *has_call_parens, name, macro_) } -pub(crate) fn render_macro_pat( - ctx: RenderContext<'_, '_>, +pub(crate) fn render_macro_pat<'db>( + ctx: RenderContext<'_, 'db>, _pattern_ctx: &PatternContext, name: hir::Name, macro_: hir::Macro, -) -> Builder { +) -> Builder<'db> { let _p = tracing::info_span!("render_macro_pat").entered(); render(ctx, false, false, false, name, macro_) } -fn render( - ctx @ RenderContext { completion, .. }: RenderContext<'_, '_>, +fn render<'db>( + ctx @ RenderContext { completion, .. }: RenderContext<'_, 'db>, is_use_path: bool, has_macro_bang: bool, has_call_parens: bool, name: hir::Name, macro_: hir::Macro, -) -> Builder { +) -> Builder<'db> { let source_range = if ctx.is_immediately_after_macro_bang() { cov_mark::hit!(completes_macro_call_if_cursor_at_bang_token); completion.token.parent().map_or_else(|| ctx.source_range(), |it| it.text_range()) diff --git a/crates/ide-completion/src/snippet.rs b/crates/ide-completion/src/snippet.rs index 20981433ae7a..34e49cf43462 100644 --- a/crates/ide-completion/src/snippet.rs +++ b/crates/ide-completion/src/snippet.rs @@ -149,7 +149,10 @@ impl Snippet { } /// Returns [`None`] if the required items do not resolve. - pub(crate) fn imports(&self, ctx: &CompletionContext<'_, '_>) -> Option> { + pub(crate) fn imports( + &self, + ctx: &CompletionContext<'_, '_>, + ) -> Option>> { import_edits(ctx, &self.requires) } @@ -165,7 +168,7 @@ impl Snippet { fn import_edits( ctx: &CompletionContext<'_, '_>, requires: &[ModPath], -) -> Option> { +) -> Option>> { let import_cfg = ctx.config.find_path_config(ctx.is_nightly); let resolve = |import| { diff --git a/crates/ide-db/src/active_parameter.rs b/crates/ide-db/src/active_parameter.rs index 506645261b8d..a8b14c388464 100644 --- a/crates/ide-db/src/active_parameter.rs +++ b/crates/ide-db/src/active_parameter.rs @@ -109,18 +109,18 @@ pub fn callable_for_node<'db>( Some((callable, active_param)) } -pub fn generic_def_for_node( - sema: &Semantics<'_, RootDatabase>, +pub fn generic_def_for_node<'db>( + sema: &Semantics<'db, RootDatabase>, generic_arg_list: &ast::GenericArgList, token: &SyntaxToken, -) -> Option<(hir::GenericDef, usize, bool, Option)> { +) -> Option<(hir::GenericDef<'db>, usize, bool, Option)> { let parent = generic_arg_list.syntax().parent()?; let mut variant = None; let def = match_ast! { match parent { ast::PathSegment(ps) => { let res = sema.resolve_path(&ps.parent_path())?; - let generic_def: hir::GenericDef = match res { + let generic_def: hir::GenericDef<'_> = match res { hir::PathResolution::Def(hir::ModuleDef::Adt(it)) => it.into(), hir::PathResolution::Def(hir::ModuleDef::Function(it)) => it.into(), hir::PathResolution::Def(hir::ModuleDef::Trait(it)) => it.into(), diff --git a/crates/ide-db/src/defs.rs b/crates/ide-db/src/defs.rs index c1fd002b3467..45ac90978a24 100644 --- a/crates/ide-db/src/defs.rs +++ b/crates/ide-db/src/defs.rs @@ -37,14 +37,14 @@ pub enum Definition<'db> { TupleField(TupleField<'db>), Module(Module), Crate(Crate), - Function(Function), + Function(Function<'db>), Adt(Adt), EnumVariant(EnumVariant), Const(Const), Static(Static), Trait(Trait), TypeAlias(TypeAlias), - SelfType(Impl), + SelfType(Impl<'db>), GenericParam(GenericParam), Local(Local<'db>), Label(Label), @@ -105,7 +105,7 @@ impl<'db> Definition<'db> { } pub fn enclosing_definition(&self, db: &RootDatabase) -> Option> { - fn container_to_definition<'db>(container: ItemContainer) -> Option> { + fn container_to_definition<'db>(container: ItemContainer<'db>) -> Option> { match container { ItemContainer::Trait(it) => Some(it.into()), ItemContainer::Impl(it) => Some(it.into()), @@ -386,7 +386,7 @@ pub fn find_std_module( pub enum IdentClass<'db> { NameClass(NameClass<'db>), NameRefClass(NameRefClass<'db>), - Operator(OperatorClass), + Operator(OperatorClass<'db>), } impl<'db> IdentClass<'db> { @@ -654,62 +654,62 @@ impl<'db> NameClass<'db> { } #[derive(Debug)] -pub enum OperatorClass { +pub enum OperatorClass<'db> { Range(Struct), - Await(Function), - Prefix(Function), - Index(Function), - Try(Function), - Bin(Function), + Await(Function<'db>), + Prefix(Function<'db>), + Index(Function<'db>), + Try(Function<'db>), + Bin(Function<'db>), } -impl OperatorClass { +impl<'db> OperatorClass<'db> { pub fn classify_range_pat( sema: &Semantics<'_, RootDatabase>, range_pat: &ast::RangePat, - ) -> Option { + ) -> Option> { sema.resolve_range_pat(range_pat).map(OperatorClass::Range) } pub fn classify_range_expr( sema: &Semantics<'_, RootDatabase>, range_expr: &ast::RangeExpr, - ) -> Option { + ) -> Option> { sema.resolve_range_expr(range_expr).map(OperatorClass::Range) } pub fn classify_await( - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, await_expr: &ast::AwaitExpr, - ) -> Option { + ) -> Option> { sema.resolve_await_to_poll(await_expr).map(OperatorClass::Await) } pub fn classify_prefix( - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, prefix_expr: &ast::PrefixExpr, - ) -> Option { + ) -> Option> { sema.resolve_prefix_expr(prefix_expr).map(OperatorClass::Prefix) } pub fn classify_try( - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, try_expr: &ast::TryExpr, - ) -> Option { + ) -> Option> { sema.resolve_try_expr(try_expr).map(OperatorClass::Try) } pub fn classify_index( - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, index_expr: &ast::IndexExpr, - ) -> Option { + ) -> Option> { sema.resolve_index_expr(index_expr).map(OperatorClass::Index) } pub fn classify_bin( - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, bin_expr: &ast::BinExpr, - ) -> Option { + ) -> Option> { sema.resolve_bin_expr(bin_expr).map(OperatorClass::Bin) } } @@ -755,7 +755,7 @@ impl<'db> NameRefClass<'db> { sema.resolve_record_field_with_substitution(&record_field) { let res = match local { - None => NameRefClass::Definition(Definition::Field(field), Some(adt_subst)), + None => NameRefClass::Definition(field.into(), Some(adt_subst)), Some(local) => { NameRefClass::FieldShorthand { field_ref: field, local_ref: local, adt_subst } } @@ -770,7 +770,7 @@ impl<'db> NameRefClass<'db> { // Only use this to resolve to macro calls for last segments as qualifiers resolve // to modules below. if let Some(macro_def) = sema.resolve_macro_call(¯o_call) { - return Some(NameRefClass::Definition(Definition::Macro(macro_def), None)); + return Some(NameRefClass::Definition(macro_def.into(), None)); } } return sema @@ -794,18 +794,18 @@ impl<'db> NameRefClass<'db> { .map(|(def, subst)| { match def { Either::Left(Either::Left(def)) => NameRefClass::Definition(def.into(), subst), - Either::Left(Either::Right(def)) => NameRefClass::Definition(Definition::TupleField(def), subst), + Either::Left(Either::Right(def)) => NameRefClass::Definition(def.into(), subst), Either::Right(def) => NameRefClass::Definition(def.into(), subst), } }) }, ast::RecordPatField(record_pat_field) => { sema.resolve_record_pat_field_with_subst(&record_pat_field) - .map(|(field, _, subst)| NameRefClass::Definition(Definition::Field(field), Some(subst))) + .map(|(field, _, subst)| NameRefClass::Definition(field.into(), Some(subst))) }, ast::RecordExprField(record_expr_field) => { sema.resolve_record_field_with_substitution(&record_expr_field) - .map(|(field, _, _, subst)| NameRefClass::Definition(Definition::Field(field), Some(subst))) + .map(|(field, _, _, subst)| NameRefClass::Definition(field.into(), Some(subst))) }, ast::AssocTypeArg(_) => { // `Trait` @@ -823,7 +823,7 @@ impl<'db> NameRefClass<'db> { .find(|alias| alias.name(sema.db).as_str() == name_ref.text().trim_start_matches("r#")) { // No substitution, this can only occur in type position. - return Some(NameRefClass::Definition(Definition::TypeAlias(ty), None)); + return Some(NameRefClass::Definition(ty.into(), None)); } None }, @@ -838,7 +838,7 @@ impl<'db> NameRefClass<'db> { let extern_crate = sema.to_def(&extern_crate_ast)?; let krate = extern_crate.resolved_crate(sema.db)?; Some(if extern_crate_ast.rename().is_some() { - NameRefClass::Definition(Definition::Crate(krate), None) + NameRefClass::Definition(krate.into(), None) } else { NameRefClass::ExternCrateShorthand { krate, decl: extern_crate } }) @@ -896,7 +896,8 @@ impl_from!( Field, TupleField<'db>, Module, - Function, + Crate, + Function<'db>, Adt, EnumVariant, Const, @@ -913,8 +914,8 @@ impl_from!( for Definition<'db> ); -impl<'db> From for Definition<'db> { - fn from(impl_: Impl) -> Self { +impl<'db> From> for Definition<'db> { + fn from(impl_: Impl<'db>) -> Self { Definition::SelfType(impl_) } } @@ -925,8 +926,8 @@ impl<'db> From, InlineAsmOperand>> for Definition<'db } } -impl AsAssocItem for Definition<'_> { - fn as_assoc_item(self, db: &dyn hir::db::HirDatabase) -> Option { +impl<'db> AsAssocItem<'db> for Definition<'db> { + fn as_assoc_item(self, db: &dyn hir::db::HirDatabase) -> Option> { match self { Definition::Function(it) => it.as_assoc_item(db), Definition::Const(it) => it.as_assoc_item(db), @@ -936,8 +937,8 @@ impl AsAssocItem for Definition<'_> { } } -impl AsExternAssocItem for Definition<'_> { - fn as_extern_assoc_item(self, db: &dyn hir::db::HirDatabase) -> Option { +impl<'db> AsExternAssocItem<'db> for Definition<'db> { + fn as_extern_assoc_item(self, db: &dyn hir::db::HirDatabase) -> Option> { match self { Definition::Function(it) => it.as_extern_assoc_item(db), Definition::Static(it) => it.as_extern_assoc_item(db), @@ -947,8 +948,8 @@ impl AsExternAssocItem for Definition<'_> { } } -impl<'db> From for Definition<'db> { - fn from(assoc_item: AssocItem) -> Self { +impl<'db> From> for Definition<'db> { + fn from(assoc_item: AssocItem<'db>) -> Self { match assoc_item { AssocItem::Function(it) => Definition::Function(it), AssocItem::Const(it) => Definition::Const(it), @@ -972,8 +973,8 @@ impl<'db> From> for Definition<'db> { } } -impl<'db> From for Definition<'db> { - fn from(def: ModuleDef) -> Self { +impl<'db> From> for Definition<'db> { + fn from(def: ModuleDef<'db>) -> Self { match def { ModuleDef::Module(it) => Definition::Module(it), ModuleDef::Function(it) => Definition::Function(it), @@ -989,8 +990,8 @@ impl<'db> From for Definition<'db> { } } -impl<'db> From for Definition<'db> { - fn from(def: DocLinkDef) -> Self { +impl<'db> From> for Definition<'db> { + fn from(def: DocLinkDef<'db>) -> Self { match def { DocLinkDef::ModuleDef(it) => it.into(), DocLinkDef::Field(it) => it.into(), @@ -1005,9 +1006,9 @@ impl<'db> From for Definition<'db> { } } -impl<'db> TryFrom for Definition<'db> { +impl<'db> TryFrom> for Definition<'db> { type Error = (); - fn try_from(def: DefWithBody) -> Result { + fn try_from(def: DefWithBody<'db>) -> Result { match def { DefWithBody::Function(it) => Ok(it.into()), DefWithBody::Static(it) => Ok(it.into()), @@ -1017,8 +1018,8 @@ impl<'db> TryFrom for Definition<'db> { } } -impl<'db> From for Definition<'db> { - fn from(def: GenericDef) -> Self { +impl<'db> From> for Definition<'db> { + fn from(def: GenericDef<'db>) -> Self { match def { GenericDef::Function(it) => it.into(), GenericDef::Adt(it) => it.into(), @@ -1031,9 +1032,9 @@ impl<'db> From for Definition<'db> { } } -impl<'db> TryFrom for Definition<'db> { +impl<'db> TryFrom> for Definition<'db> { type Error = (); - fn try_from(def: ExpressionStoreOwner) -> Result { + fn try_from(def: ExpressionStoreOwner<'db>) -> Result { match def { ExpressionStoreOwner::Body(def_with_body) => def_with_body.try_into(), ExpressionStoreOwner::Signature(generic_def) => Ok(generic_def.into()), @@ -1042,9 +1043,9 @@ impl<'db> TryFrom for Definition<'db> { } } -impl TryFrom> for GenericDef { +impl<'db> TryFrom> for GenericDef<'db> { type Error = (); - fn try_from(def: Definition<'_>) -> Result { + fn try_from(def: Definition<'db>) -> Result { match def { Definition::Function(it) => Ok(it.into()), Definition::Adt(it) => Ok(it.into()), diff --git a/crates/ide-db/src/documentation.rs b/crates/ide-db/src/documentation.rs index 407049f4b362..59fcc8a55767 100644 --- a/crates/ide-db/src/documentation.rs +++ b/crates/ide-db/src/documentation.rs @@ -40,40 +40,40 @@ pub trait HasDocs: HasAttrs + Copy { fn docs_with_rangemap(self, db: &dyn HirDatabase) -> Option> { self.hir_docs(db).map(Cow::Borrowed) } - fn resolve_doc_path( + fn resolve_doc_path<'db>( self, - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, link: &str, ns: Option, is_inner_doc: hir::IsInnerDoc, - ) -> Option { + ) -> Option> { resolve_doc_path_on(db, self, link, ns, is_inner_doc) } } macro_rules! impl_has_docs { - ($($def:ident,)*) => {$( - impl HasDocs for hir::$def {} + ($($def:ty,)*) => {$( + impl HasDocs for $def {} )*}; } impl_has_docs![ - EnumVariant, - Field, - Static, - Const, - Trait, - TypeAlias, - Macro, - Function, - Adt, - Module, - Impl, - Crate, - AssocItem, - Struct, - Union, - Enum, + hir::EnumVariant, + hir::Field, + hir::Static, + hir::Const, + hir::Trait, + hir::TypeAlias, + hir::Macro, + hir::Function<'_>, + hir::Adt, + hir::Module, + hir::Impl<'_>, + hir::Crate, + hir::AssocItem<'_>, + hir::Struct, + hir::Union, + hir::Enum, ]; impl HasDocs for hir::ExternCrateDecl { diff --git a/crates/ide-db/src/famous_defs.rs b/crates/ide-db/src/famous_defs.rs index b5f62c8fd736..457c76b2f5e0 100644 --- a/crates/ide-db/src/famous_defs.rs +++ b/crates/ide-db/src/famous_defs.rs @@ -142,7 +142,7 @@ impl FamousDefs<'_, '_> { self.find_macro("core:macros:builtin:derive") } - pub fn core_mem_drop(&self) -> Option { + pub fn core_mem_drop(&self) -> Option> { self.find_function("core:mem:drop") } @@ -200,7 +200,7 @@ impl FamousDefs<'_, '_> { } } - fn find_function(&self, path: &str) -> Option { + fn find_function(&self, path: &str) -> Option> { match self.find_def(path)? { hir::ScopeDef::ModuleDef(hir::ModuleDef::Function(it)) => Some(it), _ => None, diff --git a/crates/ide-db/src/helpers.rs b/crates/ide-db/src/helpers.rs index 08e4b12176c7..3cb0e353bc3f 100644 --- a/crates/ide-db/src/helpers.rs +++ b/crates/ide-db/src/helpers.rs @@ -16,7 +16,7 @@ use crate::{ generated, }; -pub fn item_name(db: &RootDatabase, item: ItemInNs) -> Option { +pub fn item_name(db: &RootDatabase, item: ItemInNs<'_>) -> Option { match item { ItemInNs::Types(module_def_id) => module_def_id.name(db), ItemInNs::Values(module_def_id) => module_def_id.name(db), diff --git a/crates/ide-db/src/imports/import_assets.rs b/crates/ide-db/src/imports/import_assets.rs index 422648c8d6c5..5b399a35b274 100644 --- a/crates/ide-db/src/imports/import_assets.rs +++ b/crates/ide-db/src/imports/import_assets.rs @@ -307,27 +307,27 @@ pub struct CompleteInFlyimport(pub bool); /// An import (not necessary the only one) that corresponds a certain given [`PathImportCandidate`]. /// (the structure is not entirely correct, since there can be situations requiring two imports, see FIXME below for the details) #[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct LocatedImport { +pub struct LocatedImport<'db> { /// The path to use in the `use` statement for a given candidate to be imported. pub import_path: ModPath, /// An item that will be imported with the import path given. - pub item_to_import: ItemInNs, + pub item_to_import: ItemInNs<'db>, /// The path import candidate, resolved. /// /// Not necessarily matches the import: /// For any associated constant from the trait, we try to access as `some::path::SomeStruct::ASSOC_` /// the original item is the associated constant, but the import has to be a trait that /// defines this constant. - pub original_item: ItemInNs, + pub original_item: ItemInNs<'db>, /// The value of `#[rust_analyzer::completions(...)]`, if existing. pub complete_in_flyimport: CompleteInFlyimport, } -impl LocatedImport { +impl<'db> LocatedImport<'db> { pub fn new( import_path: ModPath, - item_to_import: ItemInNs, - original_item: ItemInNs, + item_to_import: ItemInNs<'db>, + original_item: ItemInNs<'db>, complete_in_flyimport: CompleteInFlyimport, ) -> Self { Self { import_path, item_to_import, original_item, complete_in_flyimport } @@ -335,8 +335,8 @@ impl LocatedImport { pub fn new_no_completion( import_path: ModPath, - item_to_import: ItemInNs, - original_item: ItemInNs, + item_to_import: ItemInNs<'db>, + original_item: ItemInNs<'db>, ) -> Self { Self { import_path, @@ -357,7 +357,7 @@ impl<'db> ImportAssets<'db> { sema: &Semantics<'db, RootDatabase>, cfg: ImportPathConfig, prefix_kind: PrefixKind, - ) -> impl Iterator { + ) -> impl Iterator> { let _p = tracing::info_span!("ImportAssets::search_for_imports").entered(); self.search_for(sema, Some(prefix_kind), cfg) } @@ -367,7 +367,7 @@ impl<'db> ImportAssets<'db> { &self, sema: &Semantics<'db, RootDatabase>, cfg: ImportPathConfig, - ) -> impl Iterator { + ) -> impl Iterator> { let _p = tracing::info_span!("ImportAssets::search_for_relative_paths").entered(); self.search_for(sema, None, cfg) } @@ -407,7 +407,7 @@ impl<'db> ImportAssets<'db> { sema: &Semantics<'db, RootDatabase>, prefixed: Option, cfg: ImportPathConfig, - ) -> impl Iterator { + ) -> impl Iterator> { let _p = tracing::info_span!("ImportAssets::search_for").entered(); let scope = match sema.scope(&self.candidate_node) { @@ -473,14 +473,14 @@ impl<'db> ImportAssets<'db> { } } -fn path_applicable_imports( - db: &RootDatabase, - scope: &SemanticsScope<'_>, +fn path_applicable_imports<'db>( + db: &'db RootDatabase, + scope: &SemanticsScope<'db>, current_crate: Crate, path_candidate: &PathImportCandidate, - mod_path: impl Fn(ItemInNs) -> Option + Copy, - scope_filter: impl Fn(ItemInNs) -> bool + Copy, -) -> FxIndexSet { + mod_path: impl Fn(ItemInNs<'db>) -> Option + Copy, + scope_filter: impl Fn(ItemInNs<'db>) -> bool + Copy, +) -> FxIndexSet> { let _p = tracing::info_span!("ImportAssets::path_applicable_imports").entered(); let mut result = match &*path_candidate.qualifier { @@ -552,7 +552,7 @@ fn path_applicable_imports( fn filter_by_definition_kind( db: &RootDatabase, - item: ItemInNs, + item: ItemInNs<'_>, allowed: &PathDefinitionKinds, ) -> bool { let item = item.into_module_def(); @@ -590,11 +590,11 @@ fn filter_by_definition_kind( } } -fn filter_candidates_by_after_path( - db: &RootDatabase, - scope: &SemanticsScope<'_>, +fn filter_candidates_by_after_path<'db>( + db: &'db RootDatabase, + scope: &SemanticsScope<'db>, path_candidate: &PathImportCandidate, - imports: &mut FxIndexSet, + imports: &mut FxIndexSet>, ) { if imports.len() <= 1 { // Short-circuit, as even if it doesn't match fully we want it. @@ -622,7 +622,7 @@ fn filter_candidates_by_after_path( .collect::>() }; items.into_iter().any(|item| { - let has_last_method = |ty: hir::Type<'_>| { + let has_last_method = |ty: hir::Type<'db>| { ty.iterate_path_candidates(db, scope, &traits_in_scope, Some(last_after), |_| { Some(()) }) @@ -657,16 +657,16 @@ fn filter_candidates_by_after_path( /// Validates and builds an import for `resolved_qualifier` if the `unresolved_qualifier` appended /// to it resolves and there is a validate `candidate` after that. -fn validate_resolvable( - db: &RootDatabase, - scope: &SemanticsScope<'_>, - mod_path: impl Fn(ItemInNs) -> Option, - scope_filter: impl Fn(ItemInNs) -> bool, +fn validate_resolvable<'db>( + db: &'db RootDatabase, + scope: &SemanticsScope<'db>, + mod_path: impl Fn(ItemInNs<'db>) -> Option, + scope_filter: impl Fn(ItemInNs<'db>) -> bool, candidate: &NameToImport, - resolved_qualifier: ItemInNs, + resolved_qualifier: ItemInNs<'db>, unresolved_qualifier: &[Name], complete_in_flyimport: CompleteInFlyimport, -) -> SmallVec<[LocatedImport; 1]> { +) -> SmallVec<[LocatedImport<'db>; 1]> { let _p = tracing::info_span!("ImportAssets::import_for_item").entered(); let qualifier = (|| { @@ -753,7 +753,7 @@ fn validate_resolvable( result } -pub fn item_for_path_search(db: &RootDatabase, item: ItemInNs) -> Option { +pub fn item_for_path_search<'db>(db: &RootDatabase, item: ItemInNs<'db>) -> Option> { Some(match item { ItemInNs::Types(_) | ItemInNs::Values(_) => match item_as_assoc(db, item) { Some(assoc_item) => item_for_path_search_assoc(db, assoc_item)?, @@ -763,7 +763,10 @@ pub fn item_for_path_search(db: &RootDatabase, item: ItemInNs) -> Option Option { +fn item_for_path_search_assoc<'db>( + db: &RootDatabase, + assoc_item: AssocItem<'db>, +) -> Option> { Some(match assoc_item.container(db) { AssocItemContainer::Trait(trait_) => ItemInNs::from(ModuleDef::from(trait_)), AssocItemContainer::Impl(impl_) => { @@ -778,9 +781,9 @@ fn trait_applicable_items<'db>( scope: &SemanticsScope<'db>, trait_candidate: &TraitImportCandidate<'db>, trait_assoc_item: bool, - mod_path: impl Fn(ItemInNs) -> Option, + mod_path: impl Fn(ItemInNs<'db>) -> Option, scope_filter: impl Fn(hir::Trait) -> bool, -) -> FxIndexSet { +) -> FxIndexSet> { let _p = tracing::info_span!("ImportAssets::trait_applicable_items").entered(); let inherent_traits = trait_candidate.receiver_ty.applicable_inherent_traits(db); @@ -935,7 +938,7 @@ fn trait_applicable_items<'db>( located_imports } -fn assoc_to_item(assoc: AssocItem) -> ItemInNs { +fn assoc_to_item<'db>(assoc: AssocItem<'db>) -> ItemInNs<'db> { match assoc { AssocItem::Function(f) => ItemInNs::from(ModuleDef::from(f)), AssocItem::Const(c) => ItemInNs::from(ModuleDef::from(c)), @@ -946,7 +949,7 @@ fn assoc_to_item(assoc: AssocItem) -> ItemInNs { #[tracing::instrument(skip_all)] fn get_mod_path( db: &RootDatabase, - item_to_search: ItemInNs, + item_to_search: ItemInNs<'_>, module_with_candidate: &Module, prefixed: Option, cfg: FindPathConfig, @@ -1073,6 +1076,6 @@ fn path_import_candidate<'db>( }) } -fn item_as_assoc(db: &RootDatabase, item: ItemInNs) -> Option { +fn item_as_assoc<'db>(db: &RootDatabase, item: ItemInNs<'db>) -> Option> { item.into_module_def().as_assoc_item(db) } diff --git a/crates/ide-db/src/items_locator.rs b/crates/ide-db/src/items_locator.rs index af0c69c6856d..d6ce91bc913e 100644 --- a/crates/ide-db/src/items_locator.rs +++ b/crates/ide-db/src/items_locator.rs @@ -20,12 +20,12 @@ pub use import_map::AssocSearchMode; // FIXME: Do callbacks instead to avoid allocations. /// Searches for importable items with the given name in the crate and its dependencies. -pub fn items_with_name( - db: &RootDatabase, +pub fn items_with_name<'db>( + db: &'db RootDatabase, krate: Crate, name: NameToImport, assoc_item_search: AssocSearchMode, -) -> impl Iterator { +) -> impl Iterator, Complete)> { let _p = tracing::info_span!("items_with_name", name = name.text(), assoc_item_search = ?assoc_item_search, crate = ?krate.display_name(db).map(|name| name.to_string())) .entered(); @@ -72,12 +72,12 @@ pub fn items_with_name( } /// Searches for importable items with the given name in the crate and its dependencies. -pub fn items_with_name_in_module( - db: &RootDatabase, +pub fn items_with_name_in_module<'db, T>( + db: &'db RootDatabase, module: Module, name: NameToImport, assoc_item_search: AssocSearchMode, - mut cb: impl FnMut(ItemInNs) -> ControlFlow, + mut cb: impl FnMut(ItemInNs<'db>) -> ControlFlow, ) -> Option { let _p = tracing::info_span!("items_with_name_in", name = name.text(), assoc_item_search = ?assoc_item_search, ?module) .entered(); @@ -118,12 +118,12 @@ pub fn items_with_name_in_module( }) } -fn find_items( - db: &RootDatabase, +fn find_items<'db>( + db: &'db RootDatabase, krate: Crate, local_query: symbol_index::Query, external_query: import_map::Query, -) -> impl Iterator { +) -> impl Iterator, Complete)> { let _p = tracing::info_span!("find_items").entered(); // NOTE: `external_query` includes `assoc_item_search`, so we don't need to diff --git a/crates/ide-db/src/lib.rs b/crates/ide-db/src/lib.rs index e37c2f084560..6ece8b66f9af 100644 --- a/crates/ide-db/src/lib.rs +++ b/crates/ide-db/src/lib.rs @@ -316,7 +316,7 @@ impl From for SymbolKind { } impl SymbolKind { - pub fn from_module_def(db: &dyn HirDatabase, it: hir::ModuleDef) -> Self { + pub fn from_module_def(db: &dyn HirDatabase, it: hir::ModuleDef<'_>) -> Self { match it { hir::ModuleDef::Const(..) => SymbolKind::Const, hir::ModuleDef::EnumVariant(..) => SymbolKind::Variant, diff --git a/crates/ide-db/src/path_transform.rs b/crates/ide-db/src/path_transform.rs index ff32badd7f14..523d23680d2b 100644 --- a/crates/ide-db/src/path_transform.rs +++ b/crates/ide-db/src/path_transform.rs @@ -53,20 +53,20 @@ type DefaultedParam = Either; /// } /// } /// ``` -pub struct PathTransform<'a> { - generic_def: Option, +pub struct PathTransform<'a, 'db> { + generic_def: Option>, substs: AstSubsts, - target_scope: &'a SemanticsScope<'a>, - source_scope: &'a SemanticsScope<'a>, + target_scope: &'a SemanticsScope<'db>, + source_scope: &'a SemanticsScope<'db>, } -impl<'a> PathTransform<'a> { +impl<'a, 'db> PathTransform<'a, 'db> { pub fn trait_impl( - target_scope: &'a SemanticsScope<'a>, - source_scope: &'a SemanticsScope<'a>, + target_scope: &'a SemanticsScope<'db>, + source_scope: &'a SemanticsScope<'db>, trait_: hir::Trait, impl_: ast::Impl, - ) -> PathTransform<'a> { + ) -> PathTransform<'a, 'db> { PathTransform { source_scope, target_scope, @@ -76,11 +76,11 @@ impl<'a> PathTransform<'a> { } pub fn function_call( - target_scope: &'a SemanticsScope<'a>, - source_scope: &'a SemanticsScope<'a>, - function: hir::Function, + target_scope: &'a SemanticsScope<'db>, + source_scope: &'a SemanticsScope<'db>, + function: hir::Function<'db>, generic_arg_list: ast::GenericArgList, - ) -> PathTransform<'a> { + ) -> PathTransform<'a, 'db> { PathTransform { source_scope, target_scope, @@ -90,11 +90,11 @@ impl<'a> PathTransform<'a> { } pub fn impl_transformation( - target_scope: &'a SemanticsScope<'a>, - source_scope: &'a SemanticsScope<'a>, - impl_: hir::Impl, + target_scope: &'a SemanticsScope<'db>, + source_scope: &'a SemanticsScope<'db>, + impl_: hir::Impl<'db>, generic_arg_list: ast::GenericArgList, - ) -> PathTransform<'a> { + ) -> PathTransform<'a, 'db> { PathTransform { source_scope, target_scope, @@ -104,11 +104,11 @@ impl<'a> PathTransform<'a> { } pub fn adt_transformation( - target_scope: &'a SemanticsScope<'a>, - source_scope: &'a SemanticsScope<'a>, + target_scope: &'a SemanticsScope<'db>, + source_scope: &'a SemanticsScope<'db>, adt: hir::Adt, generic_arg_list: ast::GenericArgList, - ) -> PathTransform<'a> { + ) -> PathTransform<'a, 'db> { PathTransform { source_scope, target_scope, @@ -118,9 +118,9 @@ impl<'a> PathTransform<'a> { } pub fn generic_transformation( - target_scope: &'a SemanticsScope<'a>, - source_scope: &'a SemanticsScope<'a>, - ) -> PathTransform<'a> { + target_scope: &'a SemanticsScope<'db>, + source_scope: &'a SemanticsScope<'db>, + ) -> PathTransform<'a, 'db> { PathTransform { source_scope, target_scope, @@ -162,7 +162,7 @@ impl<'a> PathTransform<'a> { N::cast(self.prettify_target_node(node.syntax().clone())).unwrap() } - fn build_ctx(&self) -> Ctx<'a> { + fn build_ctx(&self) -> Ctx<'a, 'db> { let db = self.source_scope.db; let target_module = self.target_scope.module(); let source_module = self.source_scope.module(); @@ -251,12 +251,12 @@ impl<'a> PathTransform<'a> { } } -struct Ctx<'a> { +struct Ctx<'a, 'db> { type_substs: FxHashMap, const_substs: FxHashMap, lifetime_substs: FxHashMap, target_module: hir::Module, - source_scope: &'a SemanticsScope<'a>, + source_scope: &'a SemanticsScope<'db>, same_self_type: bool, target_edition: Edition, } @@ -272,7 +272,7 @@ fn preorder_rev(item: &SyntaxNode) -> impl Iterator { x.into_iter().rev() } -impl Ctx<'_> { +impl Ctx<'_, '_> { fn apply(&self, item: &SyntaxNode) -> SyntaxNode { // `transform_path` may update a node's parent and that would break the // tree traversal. Thus all paths in the tree are collected into a vec diff --git a/crates/ide-db/src/search.rs b/crates/ide-db/src/search.rs index c2cc9d717869..69158482c7a0 100644 --- a/crates/ide-db/src/search.rs +++ b/crates/ide-db/src/search.rs @@ -444,7 +444,7 @@ pub struct FindUsages<'a, 'db> { sema: &'a Semantics<'db, RootDatabase>, scope: Option<&'a SearchScope>, /// The container of our definition should it be an assoc item - assoc_item_container: Option, + assoc_item_container: Option>, /// whether to search for the `Self` type of the definition include_self_kw_refs: Option>, /// whether to search for the `self` module diff --git a/crates/ide-db/src/traits.rs b/crates/ide-db/src/traits.rs index 4a560d30ba3c..006d5728b64d 100644 --- a/crates/ide-db/src/traits.rs +++ b/crates/ide-db/src/traits.rs @@ -24,7 +24,7 @@ pub fn resolve_target_trait( pub fn get_missing_assoc_items( sema: &Semantics<'_, RootDatabase>, impl_def: &ast::Impl, -) -> Vec { +) -> Vec> { let imp = match sema.to_def(impl_def) { Some(it) => it, None => return vec![], @@ -113,7 +113,7 @@ pub(crate) fn as_trait_assoc_def<'db>( fn assoc_item_of_trait<'db>( db: &dyn HirDatabase, - assoc: hir::AssocItem, + assoc: hir::AssocItem<'_>, trait_: hir::Trait, ) -> Option> { use hir::AssocItem::*; diff --git a/crates/ide-diagnostics/src/handlers/elided_lifetimes_in_path.rs b/crates/ide-diagnostics/src/handlers/elided_lifetimes_in_path.rs index 8df99598590f..88964bda5b50 100644 --- a/crates/ide-diagnostics/src/handlers/elided_lifetimes_in_path.rs +++ b/crates/ide-diagnostics/src/handlers/elided_lifetimes_in_path.rs @@ -6,7 +6,7 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; // and a hard error for others. pub(crate) fn elided_lifetimes_in_path( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::ElidedLifetimesInPath, + d: &hir::ElidedLifetimesInPath<'_>, ) -> Diagnostic { if d.hard_error { Diagnostic::new_with_syntax_node_ptr( diff --git a/crates/ide-diagnostics/src/handlers/incorrect_generics_len.rs b/crates/ide-diagnostics/src/handlers/incorrect_generics_len.rs index 5ee02279a20d..4e02fe1fc0c6 100644 --- a/crates/ide-diagnostics/src/handlers/incorrect_generics_len.rs +++ b/crates/ide-diagnostics/src/handlers/incorrect_generics_len.rs @@ -6,7 +6,7 @@ use hir::IncorrectGenericsLenKind; // This diagnostic is triggered if the number of generic arguments does not match their declaration. pub(crate) fn incorrect_generics_len( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::IncorrectGenericsLen, + d: &hir::IncorrectGenericsLen<'_>, ) -> Diagnostic { let owner_description = d.def.description(); let expected = d.expected; diff --git a/crates/ide-diagnostics/src/handlers/missing_lifetime.rs b/crates/ide-diagnostics/src/handlers/missing_lifetime.rs index 760bb7309d68..14e644f6e6c9 100644 --- a/crates/ide-diagnostics/src/handlers/missing_lifetime.rs +++ b/crates/ide-diagnostics/src/handlers/missing_lifetime.rs @@ -5,7 +5,7 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; // This diagnostic is triggered when a lifetime argument is missing. pub(crate) fn missing_lifetime( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::MissingLifetime, + d: &hir::MissingLifetime<'_>, ) -> Diagnostic { Diagnostic::new_with_syntax_node_ptr( ctx, diff --git a/crates/ide-diagnostics/src/handlers/private_assoc_item.rs b/crates/ide-diagnostics/src/handlers/private_assoc_item.rs index 92f3c6961e36..e4a8a742c7da 100644 --- a/crates/ide-diagnostics/src/handlers/private_assoc_item.rs +++ b/crates/ide-diagnostics/src/handlers/private_assoc_item.rs @@ -6,7 +6,7 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; // module. pub(crate) fn private_assoc_item( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::PrivateAssocItem, + d: &hir::PrivateAssocItem<'_>, ) -> Diagnostic { // FIXME: add quickfix let name = d diff --git a/crates/ide-diagnostics/src/handlers/trait_impl_missing_assoc_item.rs b/crates/ide-diagnostics/src/handlers/trait_impl_missing_assoc_item.rs index 1ffef25b5060..5ec49eca32e6 100644 --- a/crates/ide-diagnostics/src/handlers/trait_impl_missing_assoc_item.rs +++ b/crates/ide-diagnostics/src/handlers/trait_impl_missing_assoc_item.rs @@ -9,7 +9,7 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext, adjusted_display_ran // Diagnoses missing trait items in a trait impl. pub(crate) fn trait_impl_missing_assoc_item( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::TraitImplMissingAssocItems, + d: &hir::TraitImplMissingAssocItems<'_>, ) -> Diagnostic { let missing = d.missing.iter().format_with(", ", |(name, item), f| { f(&match *item { diff --git a/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs b/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs index 9374688d0ec6..6de53c9bbb78 100644 --- a/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs +++ b/crates/ide-diagnostics/src/handlers/trait_impl_redundant_assoc_item.rs @@ -17,7 +17,7 @@ use crate::{Diagnostic, DiagnosticCode, DiagnosticsContext}; // Diagnoses redundant trait items in a trait impl. pub(crate) fn trait_impl_redundant_assoc_item( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::TraitImplRedundantAssocItems, + d: &hir::TraitImplRedundantAssocItems<'_>, ) -> Diagnostic { let db = ctx.sema.db; let name = d.assoc_item.0.clone(); @@ -75,7 +75,7 @@ pub(crate) fn trait_impl_redundant_assoc_item( /// add assoc item into the trait def body fn quickfix_for_redundant_assoc_item( ctx: &DiagnosticsContext<'_, '_>, - d: &hir::TraitImplRedundantAssocItems, + d: &hir::TraitImplRedundantAssocItems<'_>, redundant_item_def: String, range: TextRange, ) -> Option> { diff --git a/crates/ide-ssr/src/resolving.rs b/crates/ide-ssr/src/resolving.rs index 9d6079202a5b..d912dbff2ef6 100644 --- a/crates/ide-ssr/src/resolving.rs +++ b/crates/ide-ssr/src/resolving.rs @@ -38,7 +38,7 @@ pub(crate) struct ResolvedPath<'db> { pub(crate) struct UfcsCallInfo<'db> { pub(crate) call_expr: ast::CallExpr, - pub(crate) function: hir::Function, + pub(crate) function: hir::Function<'db>, pub(crate) qualifier_type: Option>, } diff --git a/crates/ide/src/doc_links.rs b/crates/ide/src/doc_links.rs index 2f29fc31f8a8..bbf92b736271 100644 --- a/crates/ide/src/doc_links.rs +++ b/crates/ide/src/doc_links.rs @@ -208,7 +208,7 @@ pub(crate) fn extract_definitions_from_docs( } pub(crate) fn resolve_doc_path_for_def<'db>( - db: &dyn HirDatabase, + db: &'db dyn HirDatabase, def: Definition<'db>, link: &str, ns: Option, @@ -740,7 +740,7 @@ fn filename_and_frag_for_def<'db>( /// https://doc.rust-lang.org/std/iter/trait.Iterator.html#tymethod.next /// ^^^^^^^^^^^^^^ /// ``` -fn get_assoc_item_fragment(db: &dyn HirDatabase, assoc_item: hir::AssocItem) -> Option { +fn get_assoc_item_fragment(db: &dyn HirDatabase, assoc_item: hir::AssocItem<'_>) -> Option { Some(match assoc_item { AssocItem::Function(function) => { let is_trait_method = diff --git a/crates/ide/src/goto_definition.rs b/crates/ide/src/goto_definition.rs index b778066f4272..d7714d27bf46 100644 --- a/crates/ide/src/goto_definition.rs +++ b/crates/ide/src/goto_definition.rs @@ -175,10 +175,10 @@ pub(crate) fn goto_definition( } /// When the `?` operator is used on `Result`, go to the `From` impl if it exists as this provides more value. -fn goto_question_mark_conversions( - sema: &Semantics<'_, RootDatabase>, +fn goto_question_mark_conversions<'db>( + sema: &Semantics<'db, RootDatabase>, node: &SyntaxNode, -) -> Option { +) -> Option> { let node = ast::TryExpr::cast(node.clone())?; let try_expr_ty = sema.type_of_expr(&node.expr()?)?.adjusted(); @@ -653,7 +653,10 @@ fn nav_for_break_points( Some(navs) } -fn def_to_nav(sema: &Semantics<'_, RootDatabase>, def: Definition<'_>) -> Vec { +fn def_to_nav<'db>( + sema: &Semantics<'db, RootDatabase>, + def: Definition<'db>, +) -> Vec { def.try_to_nav(sema).map(|it| it.collect()).unwrap_or_default() } diff --git a/crates/ide/src/goto_type_definition.rs b/crates/ide/src/goto_type_definition.rs index 9de956be5ed1..5d2cb0bd31e5 100644 --- a/crates/ide/src/goto_type_definition.rs +++ b/crates/ide/src/goto_type_definition.rs @@ -13,8 +13,8 @@ use crate::{FilePosition, NavigationTarget, RangeInfo, TryToNav}; // | VS Code | **Go to Type Definition** | // // ![Go to Type Definition](https://user-images.githubusercontent.com/48062697/113020657-b560f500-917a-11eb-9007-0f809733a338.gif) -pub(crate) fn goto_type_definition( - db: &RootDatabase, +pub(crate) fn goto_type_definition<'db>( + db: &'db RootDatabase, FilePosition { file_id, offset }: FilePosition, ) -> Option>> { let sema = hir::Semantics::new(db); @@ -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<'db>| { if let Some(navs) = def.try_to_nav(&sema) { for nav in navs { if !res.contains(&nav) { diff --git a/crates/ide/src/hover.rs b/crates/ide/src/hover.rs index 3d73b5b0f24d..3a56c372ed1c 100644 --- a/crates/ide/src/hover.rs +++ b/crates/ide/src/hover.rs @@ -85,9 +85,9 @@ pub enum HoverAction { } impl HoverAction { - fn goto_type_from_targets( - sema: &Semantics<'_, RootDatabase>, - targets: Vec, + fn goto_type_from_targets<'db>( + sema: &Semantics<'db, RootDatabase>, + targets: Vec>, edition: Edition, ) -> Option { let db = sema.db; @@ -447,10 +447,10 @@ fn hover_ranged( } // FIXME: Why is this pub(crate)? -pub(crate) fn hover_for_definition( - sema: &Semantics<'_, RootDatabase>, +pub(crate) fn hover_for_definition<'db>( + sema: &Semantics<'db, RootDatabase>, file_id: FileId, - def: Definition<'_>, + def: Definition<'db>, subst: Option>, scope_node: &SyntaxNode, macro_arm: Option, @@ -588,9 +588,9 @@ fn show_implementations_action( adt.try_to_nav(sema).map(UpmappingResult::call_site).map(to_action) } -fn show_fn_references_action( - sema: &Semantics<'_, RootDatabase>, - def: Definition<'_>, +fn show_fn_references_action<'db>( + sema: &Semantics<'db, RootDatabase>, + def: Definition<'db>, ) -> Option { match def { Definition::Function(it) => { @@ -626,16 +626,16 @@ fn runnable_action( } } -fn goto_type_action_for_def( - sema: &Semantics<'_, RootDatabase>, +fn goto_type_action_for_def<'db>( + sema: &Semantics<'db, RootDatabase>, def: Definition<'_>, notable_traits: &[(hir::Trait, Vec<(Option>, hir::Name)>)], subst_types: Option)>>, edition: Edition, ) -> Option { let db = sema.db; - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } @@ -683,10 +683,10 @@ fn goto_type_action_for_def( HoverAction::goto_type_from_targets(sema, targets, edition) } -fn walk_and_push_ty( +fn walk_and_push_ty<'db>( db: &RootDatabase, ty: &hir::Type<'_>, - push_new_def: &mut dyn FnMut(hir::ModuleDef), + push_new_def: &mut dyn FnMut(hir::ModuleDef<'db>), ) { ty.walk(db, |t| { if let Some(adt) = t.as_adt() { diff --git a/crates/ide/src/hover/render.rs b/crates/ide/src/hover/render.rs index f70783fd3c0c..4c9034472875 100644 --- a/crates/ide/src/hover/render.rs +++ b/crates/ide/src/hover/render.rs @@ -57,8 +57,8 @@ pub(super) fn closure_expr( closure_ty(sema, config, &TypeInfo { original, adjusted: None }, edition, display_target) } -pub(super) fn try_expr( - sema: &Semantics<'_, RootDatabase>, +pub(super) fn try_expr<'db>( + sema: &Semantics<'db, RootDatabase>, _config: &HoverConfig<'_>, try_expr: &ast::TryExpr, edition: Edition, @@ -119,8 +119,8 @@ pub(super) fn try_expr( let mut res = HoverResult::default(); - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } @@ -152,8 +152,8 @@ pub(super) fn try_expr( Some(res) } -pub(super) fn deref_expr( - sema: &Semantics<'_, RootDatabase>, +pub(super) fn deref_expr<'db>( + sema: &Semantics<'db, RootDatabase>, _config: &HoverConfig<'_>, deref_expr: &ast::PrefixExpr, edition: Edition, @@ -164,8 +164,8 @@ pub(super) fn deref_expr( sema.type_of_expr(&ast::Expr::from(deref_expr.clone()))?; let mut res = HoverResult::default(); - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } @@ -264,8 +264,8 @@ pub(super) fn keyword( /// Returns missing types in a record pattern. /// Only makes sense when there's a rest pattern in the record pattern. /// i.e. `let S {a, ..} = S {a: 1, b: 2}` -pub(super) fn struct_rest_pat( - sema: &Semantics<'_, RootDatabase>, +pub(super) fn struct_rest_pat<'db>( + sema: &Semantics<'db, RootDatabase>, _config: &HoverConfig<'_>, pattern: &ast::RecordPat, edition: Edition, @@ -278,8 +278,8 @@ pub(super) fn struct_rest_pat( // example, S {a: 1, b: 2, ..} when struct S {a: u32, b: u32} let mut res = HoverResult::default(); - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } @@ -948,8 +948,8 @@ fn render_notable_trait( } } -fn type_info( - sema: &Semantics<'_, RootDatabase>, +fn type_info<'db>( + sema: &Semantics<'db, RootDatabase>, config: &HoverConfig<'_>, ty: TypeInfo<'_>, edition: Edition, @@ -961,8 +961,8 @@ fn type_info( let db = sema.db; let TypeInfo { original, adjusted } = ty; let mut res = HoverResult::default(); - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } @@ -1007,8 +1007,8 @@ fn type_info( Some(res) } -fn closure_ty( - sema: &Semantics<'_, RootDatabase>, +fn closure_ty<'db>( + sema: &Semantics<'db, RootDatabase>, config: &HoverConfig<'_>, TypeInfo { original, adjusted }: &TypeInfo<'_>, edition: Edition, @@ -1031,8 +1031,8 @@ fn closure_ty( if captures_rendered.trim().is_empty() { "This closure captures nothing".clone_into(&mut captures_rendered); } - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } @@ -1255,8 +1255,8 @@ impl KeywordHint { } } -fn keyword_hints( - sema: &Semantics<'_, RootDatabase>, +fn keyword_hints<'db>( + sema: &Semantics<'db, RootDatabase>, token: &SyntaxToken, parent: syntax::SyntaxNode, edition: Edition, @@ -1269,8 +1269,8 @@ fn keyword_hints( match ast::Expr::cast(parent).and_then(|site| sema.type_of_expr(&site)) { // ignore the unit type () Some(ty) if !ty.adjusted.as_ref().unwrap_or(&ty.original).is_unit() => { - let mut targets: Vec = Vec::new(); - let mut push_new_def = |item: hir::ModuleDef| { + let mut targets: Vec> = Vec::new(); + let mut push_new_def = |item: hir::ModuleDef<'db>| { if !targets.contains(&item) { targets.push(item); } diff --git a/crates/ide/src/inlay_hints.rs b/crates/ide/src/inlay_hints.rs index 98d5efb0f34d..264468e562d7 100644 --- a/crates/ide/src/inlay_hints.rs +++ b/crates/ide/src/inlay_hints.rs @@ -804,7 +804,7 @@ fn label_of_ty<'db>( }); let module_def_location = |label_builder: &mut InlayHintLabelBuilder<'_, '_>, - def: ModuleDef, + def: ModuleDef<'_>, name| { let def = def.try_into(); if let Ok(def) = def { diff --git a/crates/ide/src/inlay_hints/implicit_drop.rs b/crates/ide/src/inlay_hints/implicit_drop.rs index 9387573cf7ac..cff8ed4a19b8 100644 --- a/crates/ide/src/inlay_hints/implicit_drop.rs +++ b/crates/ide/src/inlay_hints/implicit_drop.rs @@ -33,7 +33,7 @@ pub(super) fn hints( } let def = sema.to_def(node)?; - let def: DefWithBody = def.into(); + let def: DefWithBody<'_> = def.into(); let def = def.try_into().ok()?; let (hir, source_map) = hir::Body::with_source_map(sema.db, def); diff --git a/crates/ide/src/interpret.rs b/crates/ide/src/interpret.rs index f8e8d874492c..518896ae1205 100644 --- a/crates/ide/src/interpret.rs +++ b/crates/ide/src/interpret.rs @@ -28,7 +28,7 @@ fn find_and_interpret(db: &RootDatabase, position: FilePosition) -> Option<(Dura let item = ancestors_at_offset(source_file.syntax(), position.offset) .filter(|it| !ast::MacroCall::can_cast(it.kind())) .find_map(ast::Item::cast)?; - let def: DefWithBody = match item { + let def: DefWithBody<'_> = match item { ast::Item::Fn(it) => sema.to_def(&it)?.into(), ast::Item::Const(it) => sema.to_def(&it)?.into(), ast::Item::Static(it) => sema.to_def(&it)?.into(), diff --git a/crates/ide/src/navigation_target.rs b/crates/ide/src/navigation_target.rs index c3d620a35700..9a530c36e639 100644 --- a/crates/ide/src/navigation_target.rs +++ b/crates/ide/src/navigation_target.rs @@ -114,17 +114,17 @@ pub(crate) trait ToNav { fn to_nav(&self, db: &RootDatabase) -> UpmappingResult; } -pub trait TryToNav { +pub trait TryToNav<'db> { fn try_to_nav( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, ) -> Option>; } -impl TryToNav for Either { +impl<'db, T: TryToNav<'db>, U: TryToNav<'db>> TryToNav<'db> for Either { fn try_to_nav( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, ) -> Option> { match self { Either::Left(it) => it.try_to_nav(sema), @@ -235,7 +235,7 @@ impl NavigationTarget { } } -impl<'db> TryToNav for FileSymbol<'db> { +impl<'db> TryToNav<'_> for FileSymbol<'db> { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -296,10 +296,10 @@ impl<'db> TryToNav for FileSymbol<'db> { } } -impl TryToNav for Definition<'_> { +impl<'db> TryToNav<'db> for Definition<'db> { fn try_to_nav( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, ) -> Option> { match self { Definition::Local(it) => Some(it.to_nav(sema.db)), @@ -331,10 +331,10 @@ impl TryToNav for Definition<'_> { } } -impl TryToNav for hir::ModuleDef { +impl<'db> TryToNav<'db> for hir::ModuleDef<'db> { fn try_to_nav( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, ) -> Option> { match self { hir::ModuleDef::Module(it) => Some(it.to_nav(sema.db)), @@ -359,7 +359,7 @@ pub(crate) trait ToNavFromAst: Sized { } } -fn container_name(db: &RootDatabase, t: impl HasContainer) -> Option { +fn container_name<'db>(db: &RootDatabase, t: impl HasContainer<'db>) -> Option { match t.container(db) { hir::ItemContainer::Trait(it) => Some(it.name(db).symbol().clone()), // FIXME: Handle owners of blocks correctly here @@ -368,7 +368,7 @@ fn container_name(db: &RootDatabase, t: impl HasContainer) -> Option { } } -impl ToNavFromAst for hir::Function { +impl ToNavFromAst for hir::Function<'_> { const KIND: SymbolKind = SymbolKind::Function; fn container_name(self, db: &RootDatabase) -> Option { container_name(db, self) @@ -421,20 +421,14 @@ impl ToNavFromAst for hir::Trait { } } -impl TryToNav for D +impl<'db, D> TryToNav<'db> for D where - D: HasSource - + ToNavFromAst - + Copy - + HasDocs - + for<'db> HirDisplay<'db> - + HasCrate - + hir::HasName, + D: HasSource + ToNavFromAst + Copy + HasDocs + HirDisplay<'db> + HasCrate + hir::HasName, D::Ast: ast::HasName, { fn try_to_nav( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, ) -> Option> { let db = sema.db; let src = self.source_with_range(db)?; @@ -488,7 +482,7 @@ impl ToNav for hir::Crate { } } -impl TryToNav for hir::Impl { +impl TryToNav<'_> for hir::Impl<'_> { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -516,7 +510,7 @@ impl TryToNav for hir::Impl { } } -impl TryToNav for hir::ExternCrateDecl { +impl TryToNav<'_> for hir::ExternCrateDecl { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -547,7 +541,7 @@ impl TryToNav for hir::ExternCrateDecl { } } -impl TryToNav for hir::Field { +impl TryToNav<'_> for hir::Field { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -582,7 +576,7 @@ impl TryToNav for hir::Field { } } -impl TryToNav for hir::Macro { +impl TryToNav<'_> for hir::Macro { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -601,7 +595,7 @@ impl TryToNav for hir::Macro { } } -impl TryToNav for hir::Adt { +impl TryToNav<'_> for hir::Adt { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -614,10 +608,10 @@ impl TryToNav for hir::Adt { } } -impl TryToNav for hir::AssocItem { +impl<'db> TryToNav<'db> for hir::AssocItem<'db> { fn try_to_nav( &self, - sema: &Semantics<'_, RootDatabase>, + sema: &Semantics<'db, RootDatabase>, ) -> Option> { match self { AssocItem::Function(it) => it.try_to_nav(sema), @@ -627,7 +621,7 @@ impl TryToNav for hir::AssocItem { } } -impl TryToNav for hir::GenericParam { +impl TryToNav<'_> for hir::GenericParam { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -681,7 +675,7 @@ impl ToNav for hir::Local<'_> { } } -impl TryToNav for hir::Label { +impl TryToNav<'_> for hir::Label { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -705,7 +699,7 @@ impl TryToNav for hir::Label { } } -impl TryToNav for hir::TypeParam { +impl TryToNav<'_> for hir::TypeParam { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -744,7 +738,7 @@ impl TryToNav for hir::TypeParam { } } -impl TryToNav for hir::TypeOrConstParam { +impl TryToNav<'_> for hir::TypeOrConstParam { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -753,7 +747,7 @@ impl TryToNav for hir::TypeOrConstParam { } } -impl TryToNav for hir::LifetimeParam { +impl TryToNav<'_> for hir::LifetimeParam { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -777,7 +771,7 @@ impl TryToNav for hir::LifetimeParam { } } -impl TryToNav for hir::ConstParam { +impl TryToNav<'_> for hir::ConstParam { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -809,7 +803,7 @@ impl TryToNav for hir::ConstParam { } } -impl TryToNav for hir::InlineAsmOperand { +impl TryToNav<'_> for hir::InlineAsmOperand { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, @@ -833,7 +827,7 @@ impl TryToNav for hir::InlineAsmOperand { } } -impl TryToNav for hir::BuiltinType { +impl TryToNav<'_> for hir::BuiltinType { fn try_to_nav( &self, sema: &Semantics<'_, RootDatabase>, diff --git a/crates/ide/src/rename.rs b/crates/ide/src/rename.rs index 4a2cc5f551b6..c241745f0e47 100644 --- a/crates/ide/src/rename.rs +++ b/crates/ide/src/rename.rs @@ -408,10 +408,10 @@ fn find_definitions<'db>( } } -fn transform_assoc_fn_into_method_call( - sema: &Semantics<'_, RootDatabase>, +fn transform_assoc_fn_into_method_call<'db>( + sema: &Semantics<'db, RootDatabase>, source_change: &mut SourceChange, - f: hir::Function, + f: hir::Function<'db>, ) { let calls = Definition::Function(f).usages(sema).all(); for (_file_id, calls) in calls { @@ -624,10 +624,10 @@ fn method_to_assoc_fn_call_self_adjust( result } -fn transform_method_call_into_assoc_fn( - sema: &Semantics<'_, RootDatabase>, +fn transform_method_call_into_assoc_fn<'db>( + sema: &Semantics<'db, RootDatabase>, source_change: &mut SourceChange, - f: hir::Function, + f: hir::Function<'db>, find_path_config: FindPathConfig, ) { let calls = Definition::Function(f).usages(sema).all(); @@ -753,7 +753,7 @@ fn transform_method_call_into_assoc_fn( fn rename_self_to_param<'db>( sema: &Semantics<'db, RootDatabase>, local: hir::Local<'db>, - self_param: hir::SelfParam, + self_param: hir::SelfParam<'_>, new_name: &Name, identifier_kind: IdentifierKind, find_path_config: FindPathConfig, diff --git a/crates/ide/src/runnables.rs b/crates/ide/src/runnables.rs index 77d1d5a23f5a..80ee80acea14 100644 --- a/crates/ide/src/runnables.rs +++ b/crates/ide/src/runnables.rs @@ -316,7 +316,7 @@ fn parent_test_module(sema: &Semantics<'_, RootDatabase>, fn_def: &ast::Fn) -> O pub(crate) fn runnable_fn( sema: &Semantics<'_, RootDatabase>, - def: hir::Function, + def: hir::Function<'_>, ) -> Option { let edition = def.krate(sema.db).edition(sema.db); let under_cfg_test = has_cfg_test(def.module(sema.db).attrs(sema.db).cfgs(sema.db)); @@ -325,7 +325,7 @@ pub(crate) fn runnable_fn( } else { let test_id = || { let canonical_path = { - let def: hir::ModuleDef = def.into(); + let def: hir::ModuleDef<'_> = def.into(); def.canonical_path(sema.db, edition) }; canonical_path @@ -398,7 +398,7 @@ pub(crate) fn runnable_mod( pub(crate) fn runnable_impl( sema: &Semantics<'_, RootDatabase>, - def: &hir::Impl, + def: &hir::Impl<'_>, ) -> Option { let display_target = def.module(sema.db).krate(sema.db).to_display_target(sema.db); let edition = display_target.edition; @@ -487,7 +487,10 @@ fn runnable_mod_outline_definition( }) } -fn module_def_doctest(sema: &Semantics<'_, RootDatabase>, def: Definition<'_>) -> Option { +fn module_def_doctest<'db>( + sema: &Semantics<'db, RootDatabase>, + def: Definition<'db>, +) -> Option { let db = sema.db; let attrs = match def { Definition::Module(it) => it.attrs(db), diff --git a/crates/ide/src/syntax_highlighting.rs b/crates/ide/src/syntax_highlighting.rs index 9fd3f005ec70..8b3c8d9615e3 100644 --- a/crates/ide/src/syntax_highlighting.rs +++ b/crates/ide/src/syntax_highlighting.rs @@ -258,8 +258,9 @@ fn traverse( let mut inside_attribute = false; // FIXME: accommodate range highlighting - let mut body_stack: Vec> = vec![]; - let mut per_body_cache: FxHashMap> = FxHashMap::default(); + let mut body_stack: Vec>> = vec![]; + let mut per_body_cache: FxHashMap, FxHashSet<_>> = + FxHashMap::default(); // Walk all nodes, keeping track of whether we are inside a macro or not. // If in macro, expand it first and highlight the expanded code. diff --git a/crates/ide/src/view_mir.rs b/crates/ide/src/view_mir.rs index 6ca231c7a81a..18a5ed73bc43 100644 --- a/crates/ide/src/view_mir.rs +++ b/crates/ide/src/view_mir.rs @@ -18,7 +18,7 @@ fn body_mir(db: &RootDatabase, position: FilePosition) -> Option { let item = ancestors_at_offset(source_file.syntax(), position.offset) .filter(|it| !ast::MacroCall::can_cast(it.kind())) .find_map(ast::Item::cast)?; - let def: DefWithBody = match item { + let def: DefWithBody<'_> = match item { ast::Item::Fn(it) => sema.to_def(&it)?.into(), ast::Item::Const(it) => sema.to_def(&it)?.into(), ast::Item::Static(it) => sema.to_def(&it)?.into(), diff --git a/crates/rust-analyzer/src/cli/analysis_stats.rs b/crates/rust-analyzer/src/cli/analysis_stats.rs index 6cbb0c718c3e..61e2245a8753 100644 --- a/crates/rust-analyzer/src/cli/analysis_stats.rs +++ b/crates/rust-analyzer/src/cli/analysis_stats.rs @@ -447,8 +447,8 @@ impl flags::AnalysisStats { fn run_const_eval( &self, db: &RootDatabase, - bodies: &[DefWithBody], - _signatures: &[GenericDef], + bodies: &[DefWithBody<'_>], + _signatures: &[GenericDef<'_>], _variants: &[Variant], verbosity: Verbosity, ) { @@ -725,8 +725,8 @@ impl flags::AnalysisStats { fn run_mir_lowering( &self, db: &RootDatabase, - bodies: &[DefWithBody], - _signatures: &[GenericDef], + bodies: &[DefWithBody<'_>], + _signatures: &[GenericDef<'_>], _variants: &[Variant], verbosity: Verbosity, ) { @@ -779,8 +779,8 @@ impl flags::AnalysisStats { &self, db: &RootDatabase, vfs: &Vfs, - bodies: &[DefWithBody], - signatures: &[GenericDef], + bodies: &[DefWithBody<'_>], + signatures: &[GenericDef<'_>], _variants: &[Variant], verbosity: Verbosity, ) { @@ -1167,8 +1167,8 @@ impl flags::AnalysisStats { &self, db: &RootDatabase, vfs: &Vfs, - bodies: &[DefWithBody], - signatures: &[GenericDef], + bodies: &[DefWithBody<'_>], + signatures: &[GenericDef<'_>], variants: &[Variant], verbosity: Verbosity, ) { diff --git a/crates/span/src/ast_id.rs b/crates/span/src/ast_id.rs index e6b89e712361..7dfefc62c1b7 100644 --- a/crates/span/src/ast_id.rs +++ b/crates/span/src/ast_id.rs @@ -285,6 +285,7 @@ impl ErasedFileAstId { pub trait AstIdNode: AstNode {} /// `AstId` points to an AST node in a specific file. +#[cfg_attr(feature = "salsa", derive(salsa::SalsaValue))] pub struct FileAstId { raw: ErasedFileAstId, _marker: PhantomData N>,