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 we are 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 the struct's 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 its 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            // Ensure that the cache contains syntax nodes from expanded macros,
169            // whose root may be in another file.
170            let InMacroFile { file_id, value } = exp_info.expanded();
171            Self::cache(&mut self.root_to_file_cache, value, file_id.into());
172
173            // include!("foo.rs") invocations are awkward: in addition to the
174            // expansion site there's the included file (foo.rs), so we need to
175            // ensure that it exists in the cache too.
176            if macro_file.is_include_macro(db) {
177                let arg = exp_info.arg();
178                if let Some(arg_node) = arg.value {
179                    Self::cache(&mut self.root_to_file_cache, arg_node.tree_top(), arg.file_id);
180                }
181            }
182
183            exp_info
184        })
185    }
186}
187
188pub(super) struct SourceToDefCtx<'db, 'cache> {
189    pub(super) db: &'db dyn HirDatabase,
190    pub(super) cache: &'cache mut SourceToDefCache<'db>,
191}
192
193impl<'db> SourceToDefCtx<'db, '_> {
194    pub(super) fn file_to_def(&mut self, file: FileId) -> &SmallVec<[ModuleId; 1]> {
195        let _p = tracing::info_span!("SourceToDefCtx::file_to_def").entered();
196        self.cache.file_to_def_cache.entry(file).or_insert_with(|| {
197            let mut mods = SmallVec::new();
198
199            for &crate_id in relevant_crates(self.db, file) {
200                // Note: `mod` declarations in block modules cannot be supported here
201                let crate_def_map = crate_def_map(self.db, crate_id);
202                let n_mods = mods.len();
203                let modules = |file| crate_def_map.modules_for_file(self.db, file);
204                mods.extend(modules(file));
205                if mods.len() == n_mods {
206                    mods.extend(
207                        hir_def::include_macro_invoc(self.db, crate_id)
208                            .iter()
209                            .filter(|&&(_, file_id)| file_id.file_id(self.db) == file)
210                            .flat_map(|&(macro_call_id, file_id)| {
211                                self.cache.included_file_cache.insert(file_id, Some(macro_call_id));
212                                modules(
213                                    macro_call_id
214                                        .lookup(self.db)
215                                        .kind
216                                        .file_id()
217                                        .original_file(self.db)
218                                        .file_id(self.db),
219                                )
220                            }),
221                    );
222                }
223            }
224            if mods.is_empty() {
225                // FIXME: detached file
226            }
227            mods
228        })
229    }
230
231    pub(super) fn module_to_def(&mut self, src: InFile<&ast::Module>) -> Option<ModuleId> {
232        let _p = tracing::info_span!("module_to_def").entered();
233        let parent_declaration = self
234            .parent_ancestors_with_macros(src.syntax_ref(), |_, ancestor, _| {
235                ancestor.map(Either::<ast::Module, ast::BlockExpr>::cast).transpose()
236            })
237            .map(|it| it.transpose());
238
239        let parent_module = match parent_declaration {
240            Some(Either::Right(parent_block)) => self
241                .block_to_def(parent_block.as_ref())
242                .map(|block| block_def_map(self.db, block).root_module_id()),
243            Some(Either::Left(parent_declaration)) => {
244                self.module_to_def(parent_declaration.as_ref())
245            }
246            None => {
247                let file_id = src.file_id.original_file(self.db);
248                self.file_to_def(file_id.file_id(self.db)).first().copied()
249            }
250        }?;
251
252        let child_name = src.value.name()?.as_name();
253        let def_map = parent_module.def_map(self.db);
254        let &child_id = def_map[parent_module].children.get(&child_name)?;
255        Some(child_id)
256    }
257
258    pub(super) fn source_file_to_def(&mut self, src: InFile<&ast::SourceFile>) -> Option<ModuleId> {
259        let _p = tracing::info_span!("source_file_to_def").entered();
260        let file_id = src.file_id.original_file(self.db);
261        self.file_to_def(file_id.file_id(self.db)).first().copied()
262    }
263
264    pub(super) fn trait_to_def(&mut self, src: InFile<&ast::Trait>) -> Option<TraitId> {
265        self.to_def(src, keys::TRAIT)
266    }
267    pub(super) fn impl_to_def(&mut self, src: InFile<&ast::Impl>) -> Option<ImplId> {
268        self.to_def(src, keys::IMPL)
269    }
270    pub(super) fn fn_to_def(&mut self, src: InFile<&ast::Fn>) -> Option<FunctionId> {
271        self.to_def(src, keys::FUNCTION)
272    }
273    pub(super) fn struct_to_def(&mut self, src: InFile<&ast::Struct>) -> Option<StructId> {
274        self.to_def(src, keys::STRUCT)
275    }
276    pub(super) fn enum_to_def(&mut self, src: InFile<&ast::Enum>) -> Option<EnumId> {
277        self.to_def(src, keys::ENUM)
278    }
279    pub(super) fn union_to_def(&mut self, src: InFile<&ast::Union>) -> Option<UnionId> {
280        self.to_def(src, keys::UNION)
281    }
282    pub(super) fn static_to_def(&mut self, src: InFile<&ast::Static>) -> Option<StaticId> {
283        self.to_def(src, keys::STATIC)
284    }
285    pub(super) fn const_to_def(&mut self, src: InFile<&ast::Const>) -> Option<ConstId> {
286        self.to_def(src, keys::CONST)
287    }
288    pub(super) fn type_alias_to_def(
289        &mut self,
290        src: InFile<&ast::TypeAlias>,
291    ) -> Option<TypeAliasId> {
292        self.to_def(src, keys::TYPE_ALIAS)
293    }
294    pub(super) fn record_field_to_def(
295        &mut self,
296        src: InFile<&ast::RecordField>,
297    ) -> Option<FieldId> {
298        self.to_def(src, keys::RECORD_FIELD)
299    }
300    pub(super) fn tuple_field_to_def(&mut self, src: InFile<&ast::TupleField>) -> Option<FieldId> {
301        self.to_def(src, keys::TUPLE_FIELD)
302    }
303    pub(super) fn block_to_def(&mut self, src: InFile<&ast::BlockExpr>) -> Option<BlockId> {
304        self.to_def(src, keys::BLOCK)
305    }
306    pub(super) fn enum_variant_to_def(
307        &mut self,
308        src: InFile<&ast::Variant>,
309    ) -> Option<EnumVariantId> {
310        self.to_def(src, keys::ENUM_VARIANT)
311    }
312    pub(super) fn extern_crate_to_def(
313        &mut self,
314        src: InFile<&ast::ExternCrate>,
315    ) -> Option<ExternCrateId> {
316        self.to_def(src, keys::EXTERN_CRATE)
317    }
318    pub(super) fn extern_block_to_def(
319        &mut self,
320        src: InFile<&ast::ExternBlock>,
321    ) -> Option<ExternBlockId> {
322        self.to_def(src, keys::EXTERN_BLOCK)
323    }
324    #[allow(dead_code)]
325    pub(super) fn use_to_def(&mut self, src: InFile<&ast::Use>) -> Option<UseId> {
326        self.to_def(src, keys::USE)
327    }
328    pub(super) fn adt_to_def(
329        &mut self,
330        InFile { file_id, value }: InFile<&ast::Adt>,
331    ) -> Option<AdtId> {
332        match value {
333            ast::Adt::Enum(it) => self.enum_to_def(InFile::new(file_id, it)).map(AdtId::EnumId),
334            ast::Adt::Struct(it) => {
335                self.struct_to_def(InFile::new(file_id, it)).map(AdtId::StructId)
336            }
337            ast::Adt::Union(it) => self.union_to_def(InFile::new(file_id, it)).map(AdtId::UnionId),
338        }
339    }
340
341    pub(super) fn asm_operand_to_def(
342        &mut self,
343        src: InFile<&ast::AsmOperandNamed>,
344    ) -> Option<InlineAsmOperand> {
345        let asm = src.value.syntax().parent().and_then(ast::AsmExpr::cast)?;
346        let index = asm
347            .asm_pieces()
348            .filter_map(|it| match it {
349                ast::AsmPiece::AsmOperandNamed(it) => Some(it),
350                _ => None,
351            })
352            .position(|it| it == *src.value)?;
353        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
354        let (_, source_map) = ExpressionStore::with_source_map(self.db, container);
355        let expr = source_map.node_expr(src.with_value(&ast::Expr::AsmExpr(asm)))?.as_expr()?;
356        Some(InlineAsmOperand { owner: container, expr, index })
357    }
358
359    pub(super) fn bind_pat_to_def(
360        &mut self,
361        src: InFile<&ast::IdentPat>,
362        semantics: &SemanticsImpl<'db>,
363    ) -> Option<crate::Local<'db>> {
364        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
365        let (store, source_map) = ExpressionStore::with_source_map(self.db, container);
366        let src = src.cloned().map(ast::Pat::from);
367        let pat_id = source_map.node_pat(src.as_ref())?;
368        // the pattern could resolve to a constant, verify that this is not the case
369        let pat_id = pat_id.as_pat()?;
370        if let crate::Pat::Bind { id, .. } = store[pat_id] {
371            let parent_infer =
372                semantics.infer_body_for_expr_or_pat(container, store, pat_id.into())?;
373            Some(crate::Local { parent: container, parent_infer, binding_id: id })
374        } else {
375            None
376        }
377    }
378    pub(super) fn self_param_to_def(
379        &mut self,
380        src: InFile<&ast::SelfParam>,
381    ) -> Option<(DefWithBodyId, BindingId)> {
382        let container = self
383            .find_container(src.syntax_ref())?
384            .as_expression_store_owner()?
385            .as_def_with_body()?;
386        let body = Body::of(self.db, container);
387        Some((container, body.self_param?.user_written))
388    }
389    pub(super) fn label_to_def(
390        &mut self,
391        src: InFile<&ast::Label>,
392    ) -> Option<(ExpressionStoreOwnerId, LabelId)> {
393        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
394        let (_, source_map) = ExpressionStore::with_source_map(self.db, container);
395        let label_id = source_map.node_label(src)?;
396        Some((container, label_id))
397    }
398
399    pub(super) fn label_ref_to_def(
400        &mut self,
401        src: InFile<&ast::Lifetime>,
402    ) -> Option<(ExpressionStoreOwnerId, LabelId)> {
403        let break_or_continue = ast::Expr::cast(src.value.syntax().parent()?)?;
404        let container = self.find_container(src.syntax_ref())?.as_expression_store_owner()?;
405        let (store, source_map) = ExpressionStore::with_source_map(self.db, container);
406        let break_or_continue =
407            source_map.node_expr(src.with_value(&break_or_continue))?.as_expr()?;
408        let (Expr::Break { label, .. } | Expr::Continue { label }) = store[break_or_continue]
409        else {
410            return None;
411        };
412        Some((container, label?))
413    }
414
415    /// (AttrId, derive attribute call id, derive call ids)
416    pub(super) fn attr_to_derive_macro_call(
417        &mut self,
418        item: InFile<&ast::Adt>,
419        src: InFile<ast::Meta>,
420    ) -> Option<(AttrId, MacroCallId, &[Option<Either<MacroCallId, BuiltinDeriveImplId>>])> {
421        let map = self.dyn_map(item)?;
422        map[keys::DERIVE_MACRO_CALL]
423            .get(&AstPtr::new(&src.value))
424            .map(|&(attr_id, call_id, ref ids)| (attr_id, call_id, &**ids))
425    }
426
427    // FIXME: Make this more fine grained! This should be a `adt_has_derives`!
428    pub(super) fn file_of_adt_has_derives(&mut self, adt: InFile<&ast::Adt>) -> bool {
429        self.dyn_map(adt).as_ref().is_some_and(|map| !map[keys::DERIVE_MACRO_CALL].is_empty())
430    }
431
432    pub(super) fn derive_macro_calls<'slf>(
433        &'slf mut self,
434        adt: InFile<&ast::Adt>,
435    ) -> Option<
436        impl Iterator<
437            Item = (AttrId, MacroCallId, &'slf [Option<Either<MacroCallId, BuiltinDeriveImplId>>]),
438        > + use<'slf>,
439    > {
440        self.dyn_map(adt).as_ref().map(|&map| {
441            let dyn_map = &map[keys::DERIVE_MACRO_CALL];
442            adt.value
443                .attrs()
444                .flat_map(|attr| attr.skip_cfg_attrs())
445                .filter_map(move |attr| dyn_map.get(&AstPtr::new(&attr)))
446                .map(|&(attr_id, call_id, ref ids)| (attr_id, call_id, &**ids))
447        })
448    }
449
450    fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
451        &mut self,
452        src: InFile<&Ast>,
453        key: Key<Ast, ID>,
454    ) -> Option<ID> {
455        self.dyn_map(src)?[key].get(&AstPtr::new(src.value)).copied()
456    }
457
458    fn dyn_map<Ast: AstNode + 'static>(&mut self, src: InFile<&Ast>) -> Option<&DynMap> {
459        let container = self.find_container(src.map(|it| it.syntax()))?;
460        Some(self.cache_for(container, src.file_id))
461    }
462
463    fn cache_for(&mut self, container: ChildContainer, file_id: HirFileId) -> &DynMap {
464        let db = self.db;
465        self.cache
466            .dynmap_cache
467            .entry((container, file_id))
468            .or_insert_with(|| container.child_by_source(db, file_id))
469    }
470
471    pub(super) fn item_to_macro_call(&mut self, src: InFile<&ast::Item>) -> Option<MacroCallId> {
472        self.to_def(src, keys::ATTR_MACRO_CALL)
473    }
474
475    pub(super) fn macro_call_to_macro_call(
476        &mut self,
477        src: InFile<&ast::MacroCall>,
478    ) -> Option<MacroCallId> {
479        self.to_def(src, keys::MACRO_CALL)
480    }
481
482    pub(super) fn type_param_to_def(
483        &mut self,
484        src: InFile<&ast::TypeParam>,
485    ) -> Option<TypeParamId> {
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::TYPE_PARAM]
489            .get(&AstPtr::new(src.value))
490            .copied()
491            .map(TypeParamId::from_unchecked)
492    }
493
494    pub(super) fn lifetime_param_to_def(
495        &mut self,
496        src: InFile<&ast::LifetimeParam>,
497    ) -> Option<LifetimeParamId> {
498        let container: ChildContainer = self.find_generic_param_container(src.syntax_ref())?.into();
499        let dyn_map = self.cache_for(container, src.file_id);
500        dyn_map[keys::LIFETIME_PARAM].get(&AstPtr::new(src.value)).copied()
501    }
502
503    pub(super) fn const_param_to_def(
504        &mut self,
505        src: InFile<&ast::ConstParam>,
506    ) -> Option<ConstParamId> {
507        let container: ChildContainer = self.find_generic_param_container(src.syntax_ref())?.into();
508        let dyn_map = self.cache_for(container, src.file_id);
509        dyn_map[keys::CONST_PARAM]
510            .get(&AstPtr::new(src.value))
511            .copied()
512            .map(ConstParamId::from_unchecked)
513    }
514
515    pub(super) fn generic_param_to_def(
516        &mut self,
517        InFile { file_id, value }: InFile<&ast::GenericParam>,
518    ) -> Option<GenericParamId> {
519        match value {
520            ast::GenericParam::ConstParam(it) => {
521                self.const_param_to_def(InFile::new(file_id, it)).map(GenericParamId::ConstParamId)
522            }
523            ast::GenericParam::LifetimeParam(it) => self
524                .lifetime_param_to_def(InFile::new(file_id, it))
525                .map(GenericParamId::LifetimeParamId),
526            ast::GenericParam::TypeParam(it) => {
527                self.type_param_to_def(InFile::new(file_id, it)).map(GenericParamId::TypeParamId)
528            }
529        }
530    }
531
532    pub(super) fn macro_to_def(&mut self, src: InFile<&ast::Macro>) -> Option<MacroId> {
533        self.dyn_map(src).and_then(|it| match src.value {
534            ast::Macro::MacroRules(value) => {
535                it[keys::MACRO_RULES].get(&AstPtr::new(value)).copied().map(MacroId::from)
536            }
537            ast::Macro::MacroDef(value) => {
538                it[keys::MACRO2].get(&AstPtr::new(value)).copied().map(MacroId::from)
539            }
540        })
541    }
542
543    pub(super) fn proc_macro_to_def(&mut self, src: InFile<&ast::Fn>) -> Option<MacroId> {
544        self.dyn_map(src).and_then(|it| {
545            it[keys::PROC_MACRO].get(&AstPtr::new(src.value)).copied().map(MacroId::from)
546        })
547    }
548
549    pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
550        let _p = tracing::info_span!("find_container").entered();
551        let def = self.parent_ancestors_with_macros(src, |this, container, child| {
552            this.container_to_def(container, child)
553        });
554        if let Some(def) = def {
555            return Some(def);
556        }
557
558        let def = self
559            .file_to_def(src.file_id.original_file(self.db).file_id(self.db))
560            .first()
561            .copied()?;
562        Some(def.into())
563    }
564
565    fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
566        self.parent_ancestors_with_macros(src, |this, InFile { file_id, value }, _| {
567            let item = ast::Item::cast(value)?;
568            match &item {
569                ast::Item::Fn(it) => this.fn_to_def(InFile::new(file_id, it)).map(Into::into),
570                ast::Item::Struct(it) => {
571                    this.struct_to_def(InFile::new(file_id, it)).map(Into::into)
572                }
573                ast::Item::Enum(it) => this.enum_to_def(InFile::new(file_id, it)).map(Into::into),
574                ast::Item::Trait(it) => this.trait_to_def(InFile::new(file_id, it)).map(Into::into),
575                ast::Item::TypeAlias(it) => {
576                    this.type_alias_to_def(InFile::new(file_id, it)).map(Into::into)
577                }
578                ast::Item::Impl(it) => this.impl_to_def(InFile::new(file_id, it)).map(Into::into),
579                _ => None,
580            }
581        })
582    }
583
584    /// Skips the attributed item that caused the macro invocation we are climbing up
585    fn parent_ancestors_with_macros<T>(
586        &mut self,
587        node: InFile<&SyntaxNode>,
588        mut cb: impl FnMut(
589            &mut Self,
590            /*parent: */ InFile<SyntaxNode>,
591            /*child: */ &SyntaxNode,
592        ) -> Option<T>,
593    ) -> Option<T> {
594        let parent = |this: &mut Self, node: InFile<&SyntaxNode>| match node.value.parent() {
595            Some(parent) => Some(node.with_value(parent)),
596            None => {
597                let macro_file = node.file_id.macro_file()?;
598                let expansion_info = this.cache.get_or_insert_expansion(this.db, macro_file);
599                expansion_info.arg().map(|node| node?.parent()).transpose()
600            }
601        };
602        let mut deepest_child_in_same_file = node.cloned();
603        let mut node = node.cloned();
604        while let Some(parent) = parent(self, node.as_ref()) {
605            if parent.file_id != node.file_id {
606                deepest_child_in_same_file = parent.clone();
607            }
608            if let Some(res) = cb(self, parent.clone(), &deepest_child_in_same_file.value) {
609                return Some(res);
610            }
611            node = parent;
612        }
613        None
614    }
615
616    fn container_to_def(
617        &mut self,
618        container: InFile<SyntaxNode>,
619        child: &SyntaxNode,
620    ) -> Option<ChildContainer> {
621        let cont = if let Some(item) = ast::Item::cast(container.value.clone()) {
622            match &item {
623                ast::Item::Module(it) => self.module_to_def(container.with_value(it))?.into(),
624                ast::Item::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
625                ast::Item::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
626                ast::Item::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
627                ast::Item::TypeAlias(it) => ChildContainer::GenericDefId(
628                    self.type_alias_to_def(container.with_value(it))?.into(),
629                ),
630                ast::Item::Struct(it) => {
631                    let def = self.struct_to_def(container.with_value(it))?;
632                    let is_in_body = it.field_list().is_some_and(|it| {
633                        it.syntax().text_range().contains(child.text_range().start())
634                    });
635                    if is_in_body {
636                        VariantId::from(def).into()
637                    } else {
638                        ChildContainer::GenericDefId(def.into())
639                    }
640                }
641                ast::Item::Union(it) => {
642                    let def = self.union_to_def(container.with_value(it))?;
643                    let is_in_body = it.record_field_list().is_some_and(|it| {
644                        it.syntax().text_range().contains(child.text_range().start())
645                    });
646                    if is_in_body {
647                        VariantId::from(def).into()
648                    } else {
649                        ChildContainer::GenericDefId(def.into())
650                    }
651                }
652                ast::Item::Fn(it) => {
653                    let def = self.fn_to_def(container.with_value(it))?;
654                    let child_offset = child.text_range().start();
655                    let is_in_body =
656                        it.body().is_some_and(|it| it.syntax().text_range().contains(child_offset));
657                    let in_param_pat = || {
658                        it.param_list().is_some_and(|it| {
659                            it.self_param()
660                                .and_then(|it| {
661                                    Some(TextRange::new(
662                                        it.syntax().text_range().start(),
663                                        it.name()?.syntax().text_range().end(),
664                                    ))
665                                })
666                                .is_some_and(|r| r.contains_inclusive(child_offset))
667                                || it
668                                    .params()
669                                    .filter_map(|it| it.pat())
670                                    .any(|it| it.syntax().text_range().contains(child_offset))
671                        })
672                    };
673                    if is_in_body || in_param_pat() {
674                        DefWithBodyId::from(def).into()
675                    } else {
676                        ChildContainer::GenericDefId(def.into())
677                    }
678                }
679                ast::Item::Static(it) => {
680                    let def = self.static_to_def(container.with_value(it))?;
681                    let is_in_body = it.body().is_some_and(|it| {
682                        it.syntax().text_range().contains(child.text_range().start())
683                    });
684                    if is_in_body {
685                        DefWithBodyId::from(def).into()
686                    } else {
687                        ChildContainer::GenericDefId(def.into())
688                    }
689                }
690                ast::Item::Const(it) => {
691                    let def = self.const_to_def(container.with_value(it))?;
692                    let is_in_body = it.body().is_some_and(|it| {
693                        it.syntax().text_range().contains(child.text_range().start())
694                    });
695                    if is_in_body {
696                        DefWithBodyId::from(def).into()
697                    } else {
698                        ChildContainer::GenericDefId(def.into())
699                    }
700                }
701                _ => return None,
702            }
703        } else if let Some(it) = ast::Variant::cast(container.value.clone()) {
704            let def = self.enum_variant_to_def(InFile::new(container.file_id, &it))?;
705            let is_in_body =
706                it.eq_token().is_some_and(|it| it.text_range().end() < child.text_range().start());
707            if is_in_body { DefWithBodyId::from(def).into() } else { VariantId::from(def).into() }
708        } else {
709            let it = match Either::<ast::Pat, ast::Name>::cast(container.value)? {
710                Either::Left(it) => ast::Param::cast(it.syntax().parent()?)?.syntax().parent(),
711                Either::Right(it) => ast::SelfParam::cast(it.syntax().parent()?)?.syntax().parent(),
712            }
713            .and_then(ast::ParamList::cast)?
714            .syntax()
715            .parent()
716            .and_then(ast::Fn::cast)?;
717            let def = self.fn_to_def(InFile::new(container.file_id, &it))?;
718            DefWithBodyId::from(def).into()
719        };
720        Some(cont)
721    }
722}
723
724#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
725pub(crate) enum ChildContainer {
726    DefWithBodyId(DefWithBodyId),
727    ModuleId(ModuleId),
728    TraitId(TraitId),
729    ImplId(ImplId),
730    EnumId(EnumId),
731    VariantId(VariantId),
732    /// XXX: this might be the same def as, for example an `EnumId`. However,
733    /// here the children are generic parameters, and not, eg enum variants.
734    GenericDefId(GenericDefId),
735}
736impl_from! {
737    DefWithBodyId,
738    ModuleId,
739    TraitId,
740    ImplId,
741    EnumId,
742    VariantId,
743    GenericDefId
744    for ChildContainer
745}
746
747impl ChildContainer {
748    fn child_by_source(self, db: &dyn HirDatabase, file_id: HirFileId) -> DynMap {
749        let _p = tracing::info_span!("ChildContainer::child_by_source").entered();
750        match self {
751            ChildContainer::DefWithBodyId(it) => it.child_by_source(db, file_id),
752            ChildContainer::ModuleId(it) => it.child_by_source(db, file_id),
753            ChildContainer::TraitId(it) => it.child_by_source(db, file_id),
754            ChildContainer::ImplId(it) => it.child_by_source(db, file_id),
755            ChildContainer::EnumId(it) => it.child_by_source(db, file_id),
756            ChildContainer::VariantId(it) => it.child_by_source(db, file_id),
757            ChildContainer::GenericDefId(it) => it.child_by_source(db, file_id),
758        }
759    }
760
761    pub(crate) fn as_expression_store_owner(self) -> Option<ExpressionStoreOwnerId> {
762        match self {
763            ChildContainer::DefWithBodyId(it) => Some(it.into()),
764            ChildContainer::ModuleId(_) => None,
765            ChildContainer::TraitId(it) => {
766                Some(ExpressionStoreOwnerId::Signature(GenericDefId::TraitId(it)))
767            }
768            ChildContainer::EnumId(it) => {
769                Some(ExpressionStoreOwnerId::Signature(GenericDefId::AdtId(it.into())))
770            }
771            ChildContainer::ImplId(it) => {
772                Some(ExpressionStoreOwnerId::Signature(GenericDefId::ImplId(it)))
773            }
774            ChildContainer::VariantId(_) => None,
775            ChildContainer::GenericDefId(it) => Some(it.into()),
776        }
777    }
778}