Skip to main content

hir/semantics/
source_to_def.rs

1//! Maps *syntax* of various definitions to their semantic ids.
2//!
3//! This is a very interesting module, and, in some sense, can be considered the
4//! heart of the IDE parts of rust-analyzer.
5//!
6//! This module solves the following problem:
7//!
8//! > Given a piece of syntax, find the corresponding semantic definition (def).
9//!
10//! This problem is a part of more-or-less every IDE feature implemented. Every
11//! IDE functionality (like goto to definition), conceptually starts with a
12//! specific cursor position in a file. Starting with this text offset, we first
13//! figure out what syntactic construct are we at: is this a pattern, an
14//! expression, an item definition.
15//!
16//! Knowing only the syntax gives us relatively little info. For example,
17//! looking at the syntax of the function we can realize that it is a part of an
18//! `impl` block, but we won't be able to tell what trait function the current
19//! function overrides, and whether it does that correctly. For that, we need to
20//! go from [`ast::Fn`] to [`crate::Function`], and that's exactly what this
21//! module does.
22//!
23//! As syntax trees are values and don't know their place of origin/identity,
24//! this module also requires [`InFile`] wrappers to understand which specific
25//! real or macro-expanded file the tree comes from.
26//!
27//! The actual algorithm to resolve syntax to def is curious in two aspects:
28//!
29//! * It is recursive
30//! * It uses the inverse algorithm (what is the syntax for this def?)
31//!
32//! Specifically, the algorithm goes like this:
33//!
34//! 1. Find the syntactic container for the syntax. For example, field's
35//!    container is the struct, and structs container is a module.
36//! 2. Recursively get the def corresponding to container.
37//! 3. Ask the container def for all child defs. These child defs contain
38//!    the answer and answer's siblings.
39//! 4. For each child def, ask for it's source.
40//! 5. The child def whose source is the syntax node we've started with
41//!    is the answer.
42//!
43//! It's interesting that both Roslyn and Kotlin contain very similar code
44//! shape.
45//!
46//! Let's take a look at Roslyn:
47//!
48//!   <https://github.com/dotnet/roslyn/blob/36a0c338d6621cc5fe34b79d414074a95a6a489c/src/Compilers/CSharp/Portable/Compilation/SyntaxTreeSemanticModel.cs#L1403-L1429>
49//!   <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1403>
50//!
51//! The `GetDeclaredType` takes `Syntax` as input, and returns `Symbol` as
52//! output. First, it retrieves a `Symbol` for parent `Syntax`:
53//!
54//! * <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1423>
55//!
56//! Then, it iterates parent symbol's children, looking for one which has the
57//! same text span as the original node:
58//!
59//!   <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1786>
60//!
61//! Now, let's look at Kotlin:
62//!
63//!   <https://github.com/JetBrains/kotlin/blob/a288b8b00e4754a1872b164999c6d3f3b8c8994a/idea/idea-frontend-fir/idea-fir-low-level-api/src/org/jetbrains/kotlin/idea/fir/low/level/api/FirModuleResolveStateImpl.kt#L93-L125>
64//!
65//! This function starts with a syntax node (`KtExpression` is syntax, like all
66//! `Kt` nodes), and returns a def. It uses
67//! `getNonLocalContainingOrThisDeclaration` to get syntactic container for a
68//! current node. Then, `findSourceNonLocalFirDeclaration` gets `Fir` for this
69//! parent. Finally, `findElementIn` function traverses `Fir` children to find
70//! one with the same source we originally started with.
71//!
72//! One question is left though -- where does the recursion stops? This happens
73//! when we get to the file syntax node, which doesn't have a syntactic parent.
74//! In that case, we loop through all the crates that might contain this file
75//! and look for a module whose source is the given file.
76//!
77//! Note that the logic in this module is somewhat fundamentally imprecise --
78//! due to conditional compilation and `#[path]` attributes, there's no
79//! injective mapping from syntax nodes to defs. This is not an edge case --
80//! more or less every item in a `lib.rs` is a part of two distinct crates: a
81//! library with `--cfg test` and a library without.
82//!
83//! At the moment, we don't really handle this well and return the first answer
84//! that works. Ideally, we should first let the caller to pick a specific
85//! active crate for a given position, and then provide an API to resolve all
86//! syntax nodes against this specific crate.
87
88use base_db::relevant_crates;
89use either::Either;
90use hir_def::{
91    AdtId, BlockId, BuiltinDeriveImplId, ConstId, ConstParamId, DefWithBodyId, EnumId,
92    EnumVariantId, ExpressionStoreOwnerId, ExternBlockId, ExternCrateId, FieldId, FunctionId,
93    GenericDefId, GenericParamId, ImplId, LifetimeParamId, Lookup, MacroId, ModuleId, StaticId,
94    StructId, TraitId, TypeAliasId, TypeParamId, UnionId, UseId, VariantId,
95    dyn_map::{
96        DynMap,
97        keys::{self, Key},
98    },
99    expr_store::{Body, ExpressionStore},
100    hir::{BindingId, Expr, LabelId},
101    nameres::{block_def_map, crate_def_map},
102};
103use hir_expand::{
104    EditionedFileId, ExpansionInfo, HirFileId, InMacroFile, MacroCallId, attrs::AttrId,
105    name::AsName,
106};
107use rustc_hash::FxHashMap;
108use smallvec::SmallVec;
109use span::FileId;
110use stdx::impl_from;
111use syntax::{
112    AstNode, AstPtr, SyntaxNode,
113    ast::{self, HasAttrs, HasName},
114};
115use tt::TextRange;
116
117use crate::{
118    InFile, InlineAsmOperand, SemanticsImpl, db::HirDatabase,
119    semantics::child_by_source::ChildBySource,
120};
121
122#[derive(Default)]
123pub(super) struct SourceToDefCache<'db> {
124    pub(super) dynmap_cache: FxHashMap<(ChildContainer, HirFileId), DynMap>,
125    expansion_info_cache: FxHashMap<MacroCallId, ExpansionInfo<'db>>,
126    pub(super) file_to_def_cache: FxHashMap<FileId, SmallVec<[ModuleId; 1]>>,
127    pub(super) included_file_cache: FxHashMap<EditionedFileId, Option<MacroCallId>>,
128    /// Rootnode to HirFileId cache
129    pub(super) root_to_file_cache: FxHashMap<SyntaxNode, HirFileId>,
130}
131
132impl<'db> SourceToDefCache<'db> {
133    pub(super) fn cache(
134        root_to_file_cache: &mut FxHashMap<SyntaxNode, HirFileId>,
135        root_node: SyntaxNode,
136        file_id: HirFileId,
137    ) {
138        assert!(root_node.parent().is_none());
139        let prev = root_to_file_cache.insert(root_node, file_id);
140        assert!(prev.is_none() || prev == Some(file_id));
141    }
142
143    pub(super) fn get_or_insert_include_for(
144        &mut self,
145        db: &dyn HirDatabase,
146        file: EditionedFileId,
147    ) -> Option<MacroCallId> {
148        if let Some(&m) = self.included_file_cache.get(&file) {
149            return m;
150        }
151        self.included_file_cache.insert(file, None);
152        for &crate_id in relevant_crates(db, file.file_id(db)) {
153            for &(macro_call_id, file_id) in hir_def::include_macro_invoc(db, crate_id) {
154                self.included_file_cache.insert(file_id, Some(macro_call_id));
155            }
156        }
157        self.included_file_cache.get(&file).copied().flatten()
158    }
159
160    pub(super) fn get_or_insert_expansion(
161        &mut self,
162        db: &'db dyn HirDatabase,
163        macro_file: MacroCallId,
164    ) -> &ExpansionInfo<'db> {
165        self.expansion_info_cache.entry(macro_file).or_insert_with(|| {
166            let exp_info = macro_file.expansion_info(db);
167
168            let InMacroFile { file_id, value } = exp_info.expanded();
169            Self::cache(&mut self.root_to_file_cache, value, file_id.into());
170
171            exp_info
172        })
173    }
174}
175
176pub(super) struct SourceToDefCtx<'db, 'cache> {
177    pub(super) db: &'db dyn HirDatabase,
178    pub(super) cache: &'cache mut SourceToDefCache<'db>,
179}
180
181impl<'db> SourceToDefCtx<'db, '_> {
182    pub(super) fn file_to_def(&mut self, file: FileId) -> &SmallVec<[ModuleId; 1]> {
183        let _p = tracing::info_span!("SourceToDefCtx::file_to_def").entered();
184        self.cache.file_to_def_cache.entry(file).or_insert_with(|| {
185            let mut mods = SmallVec::new();
186
187            for &crate_id in relevant_crates(self.db, file) {
188                // Note: `mod` declarations in block modules cannot be supported here
189                let crate_def_map = crate_def_map(self.db, crate_id);
190                let n_mods = mods.len();
191                let modules = |file| crate_def_map.modules_for_file(self.db, file);
192                mods.extend(modules(file));
193                if mods.len() == n_mods {
194                    mods.extend(
195                        hir_def::include_macro_invoc(self.db, crate_id)
196                            .iter()
197                            .filter(|&&(_, file_id)| file_id.file_id(self.db) == file)
198                            .flat_map(|&(macro_call_id, file_id)| {
199                                self.cache.included_file_cache.insert(file_id, Some(macro_call_id));
200                                modules(
201                                    macro_call_id
202                                        .lookup(self.db)
203                                        .kind
204                                        .file_id()
205                                        .original_file(self.db)
206                                        .file_id(self.db),
207                                )
208                            }),
209                    );
210                }
211            }
212            if mods.is_empty() {
213                // FIXME: detached file
214            }
215            mods
216        })
217    }
218
219    pub(super) fn module_to_def(&mut self, src: InFile<&ast::Module>) -> Option<ModuleId> {
220        let _p = tracing::info_span!("module_to_def").entered();
221        let parent_declaration = self
222            .parent_ancestors_with_macros(src.syntax_ref(), |_, ancestor, _| {
223                ancestor.map(Either::<ast::Module, ast::BlockExpr>::cast).transpose()
224            })
225            .map(|it| it.transpose());
226
227        let parent_module = match parent_declaration {
228            Some(Either::Right(parent_block)) => self
229                .block_to_def(parent_block.as_ref())
230                .map(|block| block_def_map(self.db, block).root_module_id()),
231            Some(Either::Left(parent_declaration)) => {
232                self.module_to_def(parent_declaration.as_ref())
233            }
234            None => {
235                let file_id = src.file_id.original_file(self.db);
236                self.file_to_def(file_id.file_id(self.db)).first().copied()
237            }
238        }?;
239
240        let child_name = src.value.name()?.as_name();
241        let def_map = parent_module.def_map(self.db);
242        let &child_id = def_map[parent_module].children.get(&child_name)?;
243        Some(child_id)
244    }
245
246    pub(super) fn source_file_to_def(&mut self, src: InFile<&ast::SourceFile>) -> Option<ModuleId> {
247        let _p = tracing::info_span!("source_file_to_def").entered();
248        let file_id = src.file_id.original_file(self.db);
249        self.file_to_def(file_id.file_id(self.db)).first().copied()
250    }
251
252    pub(super) fn trait_to_def(&mut self, src: InFile<&ast::Trait>) -> Option<TraitId> {
253        self.to_def(src, keys::TRAIT)
254    }
255    pub(super) fn impl_to_def(&mut self, src: InFile<&ast::Impl>) -> Option<ImplId> {
256        self.to_def(src, keys::IMPL)
257    }
258    pub(super) fn fn_to_def(&mut self, src: InFile<&ast::Fn>) -> Option<FunctionId> {
259        self.to_def(src, keys::FUNCTION)
260    }
261    pub(super) fn struct_to_def(&mut self, src: InFile<&ast::Struct>) -> Option<StructId> {
262        self.to_def(src, keys::STRUCT)
263    }
264    pub(super) fn enum_to_def(&mut self, src: InFile<&ast::Enum>) -> Option<EnumId> {
265        self.to_def(src, keys::ENUM)
266    }
267    pub(super) fn union_to_def(&mut self, src: InFile<&ast::Union>) -> Option<UnionId> {
268        self.to_def(src, keys::UNION)
269    }
270    pub(super) fn static_to_def(&mut self, src: InFile<&ast::Static>) -> Option<StaticId> {
271        self.to_def(src, keys::STATIC)
272    }
273    pub(super) fn const_to_def(&mut self, src: InFile<&ast::Const>) -> Option<ConstId> {
274        self.to_def(src, keys::CONST)
275    }
276    pub(super) fn type_alias_to_def(
277        &mut self,
278        src: InFile<&ast::TypeAlias>,
279    ) -> Option<TypeAliasId> {
280        self.to_def(src, keys::TYPE_ALIAS)
281    }
282    pub(super) fn record_field_to_def(
283        &mut self,
284        src: InFile<&ast::RecordField>,
285    ) -> Option<FieldId> {
286        self.to_def(src, keys::RECORD_FIELD)
287    }
288    pub(super) fn tuple_field_to_def(&mut self, src: InFile<&ast::TupleField>) -> Option<FieldId> {
289        self.to_def(src, keys::TUPLE_FIELD)
290    }
291    pub(super) fn block_to_def(&mut self, src: InFile<&ast::BlockExpr>) -> Option<BlockId> {
292        self.to_def(src, keys::BLOCK)
293    }
294    pub(super) fn enum_variant_to_def(
295        &mut self,
296        src: InFile<&ast::Variant>,
297    ) -> Option<EnumVariantId> {
298        self.to_def(src, keys::ENUM_VARIANT)
299    }
300    pub(super) fn extern_crate_to_def(
301        &mut self,
302        src: InFile<&ast::ExternCrate>,
303    ) -> Option<ExternCrateId> {
304        self.to_def(src, keys::EXTERN_CRATE)
305    }
306    pub(super) fn extern_block_to_def(
307        &mut self,
308        src: InFile<&ast::ExternBlock>,
309    ) -> Option<ExternBlockId> {
310        self.to_def(src, keys::EXTERN_BLOCK)
311    }
312    #[allow(dead_code)]
313    pub(super) fn use_to_def(&mut self, src: InFile<&ast::Use>) -> Option<UseId> {
314        self.to_def(src, keys::USE)
315    }
316    pub(super) fn adt_to_def(
317        &mut self,
318        InFile { file_id, value }: InFile<&ast::Adt>,
319    ) -> Option<AdtId> {
320        match value {
321            ast::Adt::Enum(it) => self.enum_to_def(InFile::new(file_id, it)).map(AdtId::EnumId),
322            ast::Adt::Struct(it) => {
323                self.struct_to_def(InFile::new(file_id, it)).map(AdtId::StructId)
324            }
325            ast::Adt::Union(it) => self.union_to_def(InFile::new(file_id, it)).map(AdtId::UnionId),
326        }
327    }
328
329    pub(super) fn asm_operand_to_def(
330        &mut self,
331        src: InFile<&ast::AsmOperandNamed>,
332    ) -> Option<InlineAsmOperand> {
333        let asm = src.value.syntax().parent().and_then(ast::AsmExpr::cast)?;
334        let index = asm
335            .asm_pieces()
336            .filter_map(|it| match it {
337                ast::AsmPiece::AsmOperandNamed(it) => Some(it),
338                _ => None,
339            })
340            .position(|it| it == *src.value)?;
341        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
342        let (_, source_map) = ExpressionStore::with_source_map(self.db, container);
343        let expr = source_map.node_expr(src.with_value(&ast::Expr::AsmExpr(asm)))?.as_expr()?;
344        Some(InlineAsmOperand { owner: container, expr, index })
345    }
346
347    pub(super) fn bind_pat_to_def(
348        &mut self,
349        src: InFile<&ast::IdentPat>,
350        semantics: &SemanticsImpl<'db>,
351    ) -> Option<crate::Local<'db>> {
352        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
353        let (store, source_map) = ExpressionStore::with_source_map(self.db, container);
354        let src = src.cloned().map(ast::Pat::from);
355        let pat_id = source_map.node_pat(src.as_ref())?;
356        // the pattern could resolve to a constant, verify that this is not the case
357        let pat_id = pat_id.as_pat()?;
358        if let crate::Pat::Bind { id, .. } = store[pat_id] {
359            let parent_infer =
360                semantics.infer_body_for_expr_or_pat(container, store, pat_id.into())?;
361            Some(crate::Local { parent: container, parent_infer, binding_id: id })
362        } else {
363            None
364        }
365    }
366    pub(super) fn self_param_to_def(
367        &mut self,
368        src: InFile<&ast::SelfParam>,
369    ) -> Option<(DefWithBodyId, BindingId)> {
370        let container = self
371            .find_container(src.syntax_ref())?
372            .as_expression_store_owner()?
373            .as_def_with_body()?;
374        let body = Body::of(self.db, container);
375        Some((container, body.self_param?.user_written))
376    }
377    pub(super) fn label_to_def(
378        &mut self,
379        src: InFile<&ast::Label>,
380    ) -> Option<(ExpressionStoreOwnerId, LabelId)> {
381        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
382        let (_, source_map) = ExpressionStore::with_source_map(self.db, container);
383        let label_id = source_map.node_label(src)?;
384        Some((container, label_id))
385    }
386
387    pub(super) fn label_ref_to_def(
388        &mut self,
389        src: InFile<&ast::Lifetime>,
390    ) -> Option<(ExpressionStoreOwnerId, LabelId)> {
391        let break_or_continue = ast::Expr::cast(src.value.syntax().parent()?)?;
392        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
393        let (store, source_map) = ExpressionStore::with_source_map(self.db, container);
394        let break_or_continue =
395            source_map.node_expr(src.with_value(&break_or_continue))?.as_expr()?;
396        let (Expr::Break { label, .. } | Expr::Continue { label }) = store[break_or_continue]
397        else {
398            return None;
399        };
400        Some((container, label?))
401    }
402
403    /// (AttrId, derive attribute call id, derive call ids)
404    pub(super) fn attr_to_derive_macro_call(
405        &mut self,
406        item: InFile<&ast::Adt>,
407        src: InFile<ast::Meta>,
408    ) -> Option<(AttrId, MacroCallId, &[Option<Either<MacroCallId, BuiltinDeriveImplId>>])> {
409        let map = self.dyn_map(item)?;
410        map[keys::DERIVE_MACRO_CALL]
411            .get(&AstPtr::new(&src.value))
412            .map(|&(attr_id, call_id, ref ids)| (attr_id, call_id, &**ids))
413    }
414
415    // FIXME: Make this more fine grained! This should be a `adt_has_derives`!
416    pub(super) fn file_of_adt_has_derives(&mut self, adt: InFile<&ast::Adt>) -> bool {
417        self.dyn_map(adt).as_ref().is_some_and(|map| !map[keys::DERIVE_MACRO_CALL].is_empty())
418    }
419
420    pub(super) fn derive_macro_calls<'slf>(
421        &'slf mut self,
422        adt: InFile<&ast::Adt>,
423    ) -> Option<
424        impl Iterator<
425            Item = (AttrId, MacroCallId, &'slf [Option<Either<MacroCallId, BuiltinDeriveImplId>>]),
426        > + use<'slf>,
427    > {
428        self.dyn_map(adt).as_ref().map(|&map| {
429            let dyn_map = &map[keys::DERIVE_MACRO_CALL];
430            adt.value
431                .attrs()
432                .flat_map(|attr| attr.skip_cfg_attrs())
433                .filter_map(move |attr| dyn_map.get(&AstPtr::new(&attr)))
434                .map(|&(attr_id, call_id, ref ids)| (attr_id, call_id, &**ids))
435        })
436    }
437
438    fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
439        &mut self,
440        src: InFile<&Ast>,
441        key: Key<Ast, ID>,
442    ) -> Option<ID> {
443        self.dyn_map(src)?[key].get(&AstPtr::new(src.value)).copied()
444    }
445
446    fn dyn_map<Ast: AstNode + 'static>(&mut self, src: InFile<&Ast>) -> Option<&DynMap> {
447        let container = self.find_container(src.map(|it| it.syntax()))?;
448        Some(self.cache_for(container, src.file_id))
449    }
450
451    fn cache_for(&mut self, container: ChildContainer, file_id: HirFileId) -> &DynMap {
452        let db = self.db;
453        self.cache
454            .dynmap_cache
455            .entry((container, file_id))
456            .or_insert_with(|| container.child_by_source(db, file_id))
457    }
458
459    pub(super) fn item_to_macro_call(&mut self, src: InFile<&ast::Item>) -> Option<MacroCallId> {
460        self.to_def(src, keys::ATTR_MACRO_CALL)
461    }
462
463    pub(super) fn macro_call_to_macro_call(
464        &mut self,
465        src: InFile<&ast::MacroCall>,
466    ) -> Option<MacroCallId> {
467        self.to_def(src, keys::MACRO_CALL)
468    }
469
470    pub(super) fn type_param_to_def(
471        &mut self,
472        src: InFile<&ast::TypeParam>,
473    ) -> Option<TypeParamId> {
474        let container: ChildContainer = self.find_generic_param_container(src.syntax_ref())?.into();
475        let dyn_map = self.cache_for(container, src.file_id);
476        dyn_map[keys::TYPE_PARAM]
477            .get(&AstPtr::new(src.value))
478            .copied()
479            .map(TypeParamId::from_unchecked)
480    }
481
482    pub(super) fn lifetime_param_to_def(
483        &mut self,
484        src: InFile<&ast::LifetimeParam>,
485    ) -> Option<LifetimeParamId> {
486        let container: ChildContainer = self.find_generic_param_container(src.syntax_ref())?.into();
487        let dyn_map = self.cache_for(container, src.file_id);
488        dyn_map[keys::LIFETIME_PARAM].get(&AstPtr::new(src.value)).copied()
489    }
490
491    pub(super) fn const_param_to_def(
492        &mut self,
493        src: InFile<&ast::ConstParam>,
494    ) -> Option<ConstParamId> {
495        let container: ChildContainer = self.find_generic_param_container(src.syntax_ref())?.into();
496        let dyn_map = self.cache_for(container, src.file_id);
497        dyn_map[keys::CONST_PARAM]
498            .get(&AstPtr::new(src.value))
499            .copied()
500            .map(ConstParamId::from_unchecked)
501    }
502
503    pub(super) fn generic_param_to_def(
504        &mut self,
505        InFile { file_id, value }: InFile<&ast::GenericParam>,
506    ) -> Option<GenericParamId> {
507        match value {
508            ast::GenericParam::ConstParam(it) => {
509                self.const_param_to_def(InFile::new(file_id, it)).map(GenericParamId::ConstParamId)
510            }
511            ast::GenericParam::LifetimeParam(it) => self
512                .lifetime_param_to_def(InFile::new(file_id, it))
513                .map(GenericParamId::LifetimeParamId),
514            ast::GenericParam::TypeParam(it) => {
515                self.type_param_to_def(InFile::new(file_id, it)).map(GenericParamId::TypeParamId)
516            }
517        }
518    }
519
520    pub(super) fn macro_to_def(&mut self, src: InFile<&ast::Macro>) -> Option<MacroId> {
521        self.dyn_map(src).and_then(|it| match src.value {
522            ast::Macro::MacroRules(value) => {
523                it[keys::MACRO_RULES].get(&AstPtr::new(value)).copied().map(MacroId::from)
524            }
525            ast::Macro::MacroDef(value) => {
526                it[keys::MACRO2].get(&AstPtr::new(value)).copied().map(MacroId::from)
527            }
528        })
529    }
530
531    pub(super) fn proc_macro_to_def(&mut self, src: InFile<&ast::Fn>) -> Option<MacroId> {
532        self.dyn_map(src).and_then(|it| {
533            it[keys::PROC_MACRO].get(&AstPtr::new(src.value)).copied().map(MacroId::from)
534        })
535    }
536
537    pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
538        let _p = tracing::info_span!("find_container").entered();
539        let def = self.parent_ancestors_with_macros(src, |this, container, child| {
540            this.container_to_def(container, child)
541        });
542        if let Some(def) = def {
543            return Some(def);
544        }
545
546        let def = self
547            .file_to_def(src.file_id.original_file(self.db).file_id(self.db))
548            .first()
549            .copied()?;
550        Some(def.into())
551    }
552
553    fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
554        self.parent_ancestors_with_macros(src, |this, InFile { file_id, value }, _| {
555            let item = ast::Item::cast(value)?;
556            match &item {
557                ast::Item::Fn(it) => this.fn_to_def(InFile::new(file_id, it)).map(Into::into),
558                ast::Item::Struct(it) => {
559                    this.struct_to_def(InFile::new(file_id, it)).map(Into::into)
560                }
561                ast::Item::Enum(it) => this.enum_to_def(InFile::new(file_id, it)).map(Into::into),
562                ast::Item::Trait(it) => this.trait_to_def(InFile::new(file_id, it)).map(Into::into),
563                ast::Item::TypeAlias(it) => {
564                    this.type_alias_to_def(InFile::new(file_id, it)).map(Into::into)
565                }
566                ast::Item::Impl(it) => this.impl_to_def(InFile::new(file_id, it)).map(Into::into),
567                _ => None,
568            }
569        })
570    }
571
572    /// Skips the attributed item that caused the macro invocation we are climbing up
573    fn parent_ancestors_with_macros<T>(
574        &mut self,
575        node: InFile<&SyntaxNode>,
576        mut cb: impl FnMut(
577            &mut Self,
578            /*parent: */ InFile<SyntaxNode>,
579            /*child: */ &SyntaxNode,
580        ) -> Option<T>,
581    ) -> Option<T> {
582        let parent = |this: &mut Self, node: InFile<&SyntaxNode>| match node.value.parent() {
583            Some(parent) => Some(node.with_value(parent)),
584            None => {
585                let macro_file = node.file_id.macro_file()?;
586                let expansion_info = this.cache.get_or_insert_expansion(this.db, macro_file);
587                expansion_info.arg().map(|node| node?.parent()).transpose()
588            }
589        };
590        let mut deepest_child_in_same_file = node.cloned();
591        let mut node = node.cloned();
592        while let Some(parent) = parent(self, node.as_ref()) {
593            if parent.file_id != node.file_id {
594                deepest_child_in_same_file = parent.clone();
595            }
596            if let Some(res) = cb(self, parent.clone(), &deepest_child_in_same_file.value) {
597                return Some(res);
598            }
599            node = parent;
600        }
601        None
602    }
603
604    fn container_to_def(
605        &mut self,
606        container: InFile<SyntaxNode>,
607        child: &SyntaxNode,
608    ) -> Option<ChildContainer> {
609        let cont = if let Some(item) = ast::Item::cast(container.value.clone()) {
610            match &item {
611                ast::Item::Module(it) => self.module_to_def(container.with_value(it))?.into(),
612                ast::Item::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
613                ast::Item::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
614                ast::Item::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
615                ast::Item::TypeAlias(it) => ChildContainer::GenericDefId(
616                    self.type_alias_to_def(container.with_value(it))?.into(),
617                ),
618                ast::Item::Struct(it) => {
619                    let def = self.struct_to_def(container.with_value(it))?;
620                    let is_in_body = it.field_list().is_some_and(|it| {
621                        it.syntax().text_range().contains(child.text_range().start())
622                    });
623                    if is_in_body {
624                        VariantId::from(def).into()
625                    } else {
626                        ChildContainer::GenericDefId(def.into())
627                    }
628                }
629                ast::Item::Union(it) => {
630                    let def = self.union_to_def(container.with_value(it))?;
631                    let is_in_body = it.record_field_list().is_some_and(|it| {
632                        it.syntax().text_range().contains(child.text_range().start())
633                    });
634                    if is_in_body {
635                        VariantId::from(def).into()
636                    } else {
637                        ChildContainer::GenericDefId(def.into())
638                    }
639                }
640                ast::Item::Fn(it) => {
641                    let def = self.fn_to_def(container.with_value(it))?;
642                    let child_offset = child.text_range().start();
643                    let is_in_body =
644                        it.body().is_some_and(|it| it.syntax().text_range().contains(child_offset));
645                    let in_param_pat = || {
646                        it.param_list().is_some_and(|it| {
647                            it.self_param()
648                                .and_then(|it| {
649                                    Some(TextRange::new(
650                                        it.syntax().text_range().start(),
651                                        it.name()?.syntax().text_range().end(),
652                                    ))
653                                })
654                                .is_some_and(|r| r.contains_inclusive(child_offset))
655                                || it
656                                    .params()
657                                    .filter_map(|it| it.pat())
658                                    .any(|it| it.syntax().text_range().contains(child_offset))
659                        })
660                    };
661                    if is_in_body || in_param_pat() {
662                        DefWithBodyId::from(def).into()
663                    } else {
664                        ChildContainer::GenericDefId(def.into())
665                    }
666                }
667                ast::Item::Static(it) => {
668                    let def = self.static_to_def(container.with_value(it))?;
669                    let is_in_body = it.body().is_some_and(|it| {
670                        it.syntax().text_range().contains(child.text_range().start())
671                    });
672                    if is_in_body {
673                        DefWithBodyId::from(def).into()
674                    } else {
675                        ChildContainer::GenericDefId(def.into())
676                    }
677                }
678                ast::Item::Const(it) => {
679                    let def = self.const_to_def(container.with_value(it))?;
680                    let is_in_body = it.body().is_some_and(|it| {
681                        it.syntax().text_range().contains(child.text_range().start())
682                    });
683                    if is_in_body {
684                        DefWithBodyId::from(def).into()
685                    } else {
686                        ChildContainer::GenericDefId(def.into())
687                    }
688                }
689                _ => return None,
690            }
691        } else if let Some(it) = ast::Variant::cast(container.value.clone()) {
692            let def = self.enum_variant_to_def(InFile::new(container.file_id, &it))?;
693            let is_in_body =
694                it.eq_token().is_some_and(|it| it.text_range().end() < child.text_range().start());
695            if is_in_body { DefWithBodyId::from(def).into() } else { VariantId::from(def).into() }
696        } else {
697            let it = match Either::<ast::Pat, ast::Name>::cast(container.value)? {
698                Either::Left(it) => ast::Param::cast(it.syntax().parent()?)?.syntax().parent(),
699                Either::Right(it) => ast::SelfParam::cast(it.syntax().parent()?)?.syntax().parent(),
700            }
701            .and_then(ast::ParamList::cast)?
702            .syntax()
703            .parent()
704            .and_then(ast::Fn::cast)?;
705            let def = self.fn_to_def(InFile::new(container.file_id, &it))?;
706            DefWithBodyId::from(def).into()
707        };
708        Some(cont)
709    }
710}
711
712#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
713pub(crate) enum ChildContainer {
714    DefWithBodyId(DefWithBodyId),
715    ModuleId(ModuleId),
716    TraitId(TraitId),
717    ImplId(ImplId),
718    EnumId(EnumId),
719    VariantId(VariantId),
720    /// XXX: this might be the same def as, for example an `EnumId`. However,
721    /// here the children are generic parameters, and not, eg enum variants.
722    GenericDefId(GenericDefId),
723}
724impl_from! {
725    DefWithBodyId,
726    ModuleId,
727    TraitId,
728    ImplId,
729    EnumId,
730    VariantId,
731    GenericDefId
732    for ChildContainer
733}
734
735impl ChildContainer {
736    fn child_by_source(self, db: &dyn HirDatabase, file_id: HirFileId) -> DynMap {
737        let _p = tracing::info_span!("ChildContainer::child_by_source").entered();
738        match self {
739            ChildContainer::DefWithBodyId(it) => it.child_by_source(db, file_id),
740            ChildContainer::ModuleId(it) => it.child_by_source(db, file_id),
741            ChildContainer::TraitId(it) => it.child_by_source(db, file_id),
742            ChildContainer::ImplId(it) => it.child_by_source(db, file_id),
743            ChildContainer::EnumId(it) => it.child_by_source(db, file_id),
744            ChildContainer::VariantId(it) => it.child_by_source(db, file_id),
745            ChildContainer::GenericDefId(it) => it.child_by_source(db, file_id),
746        }
747    }
748
749    pub(crate) fn as_expression_store_owner(self) -> Option<ExpressionStoreOwnerId> {
750        match self {
751            ChildContainer::DefWithBodyId(it) => Some(it.into()),
752            ChildContainer::ModuleId(_) => None,
753            ChildContainer::TraitId(it) => {
754                Some(ExpressionStoreOwnerId::Signature(GenericDefId::TraitId(it)))
755            }
756            ChildContainer::EnumId(it) => {
757                Some(ExpressionStoreOwnerId::Signature(GenericDefId::AdtId(it.into())))
758            }
759            ChildContainer::ImplId(it) => {
760                Some(ExpressionStoreOwnerId::Signature(GenericDefId::ImplId(it)))
761            }
762            ChildContainer::VariantId(_) => None,
763            ChildContainer::GenericDefId(it) => Some(it.into()),
764        }
765    }
766}