1 //! Maps *syntax* of various definitions to their semantic ids.
3 //! This is a very interesting module, and, in some sense, can be considered the
4 //! heart of the IDE parts of rust-analyzer.
6 //! This module solves the following problem:
8 //! Given a piece of syntax, find the corresponding semantic definition (def).
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.
16 //! Knowing only the syntax gives us relatively little info. For example,
17 //! looking at the syntax of the function we can realise 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
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.
27 //! The actual algorithm to resolve syntax to def is curious in two aspects:
30 //! * It uses the inverse algorithm (what is the syntax for this def?)
32 //! Specifically, the algorithm goes like this:
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
43 //! It's interesting that both Roslyn and Kotlin contain very similar code
46 //! Let's take a look at Roslyn:
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>
51 //! The `GetDeclaredType` takes `Syntax` as input, and returns `Symbol` as
52 //! output. First, it retrieves a `Symbol` for parent `Syntax`:
54 //! * https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1423
56 //! Then, it iterates parent symbol's children, looking for one which has the
57 //! same text span as the original node:
59 //! <https://sourceroslyn.io/#Microsoft.CodeAnalysis.CSharp/Compilation/SyntaxTreeSemanticModel.cs,1786>
61 //! Now, let's look at Kotlin:
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>
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.
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.
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.
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.
90 child_by_source::ChildBySource,
92 expr::{LabelId, PatId},
94 ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId, FieldId, FunctionId, GenericDefId,
95 ImplId, LifetimeParamId, ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId,
98 use hir_expand::{name::AsName, AstId, MacroCallId, MacroDefKind};
99 use rustc_hash::FxHashMap;
100 use smallvec::SmallVec;
103 ast::{self, NameOwner},
104 match_ast, AstNode, SyntaxNode,
107 use crate::{db::HirDatabase, InFile, MacroDefId};
109 pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>;
111 pub(super) struct SourceToDefCtx<'a, 'b> {
112 pub(super) db: &'b dyn HirDatabase,
113 pub(super) cache: &'a mut SourceToDefCache,
116 impl SourceToDefCtx<'_, '_> {
117 pub(super) fn file_to_def(&mut self, file: FileId) -> SmallVec<[ModuleId; 1]> {
118 let _p = profile::span("SourceBinder::to_module_def");
119 let mut mods = SmallVec::new();
120 for &crate_id in self.db.relevant_crates(file).iter() {
121 // FIXME: inner items
122 let crate_def_map = self.db.crate_def_map(crate_id);
125 .modules_for_file(file)
126 .map(|local_id| crate_def_map.module_id(local_id)),
132 pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> {
133 let _p = profile::span("module_to_def");
134 let parent_declaration = src
136 .map(|it| it.syntax())
138 .ancestors_with_macros(self.db.upcast())
141 let m = ast::Module::cast(it.value.clone())?;
142 Some(it.with_value(m))
145 let parent_module = match parent_declaration {
146 Some(parent_declaration) => self.module_to_def(parent_declaration),
148 let file_id = src.file_id.original_file(self.db.upcast());
149 self.file_to_def(file_id).get(0).copied()
153 let child_name = src.value.name()?.as_name();
154 let def_map = parent_module.def_map(self.db.upcast());
155 let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
156 Some(def_map.module_id(child_id))
159 pub(super) fn source_file_to_def(&mut self, src: InFile<ast::SourceFile>) -> Option<ModuleId> {
160 let _p = profile::span("source_file_to_def");
161 let file_id = src.file_id.original_file(self.db.upcast());
162 self.file_to_def(file_id).get(0).copied()
165 pub(super) fn trait_to_def(&mut self, src: InFile<ast::Trait>) -> Option<TraitId> {
166 self.to_def(src, keys::TRAIT)
168 pub(super) fn impl_to_def(&mut self, src: InFile<ast::Impl>) -> Option<ImplId> {
169 self.to_def(src, keys::IMPL)
171 pub(super) fn fn_to_def(&mut self, src: InFile<ast::Fn>) -> Option<FunctionId> {
172 self.to_def(src, keys::FUNCTION)
174 pub(super) fn struct_to_def(&mut self, src: InFile<ast::Struct>) -> Option<StructId> {
175 self.to_def(src, keys::STRUCT)
177 pub(super) fn enum_to_def(&mut self, src: InFile<ast::Enum>) -> Option<EnumId> {
178 self.to_def(src, keys::ENUM)
180 pub(super) fn union_to_def(&mut self, src: InFile<ast::Union>) -> Option<UnionId> {
181 self.to_def(src, keys::UNION)
183 pub(super) fn static_to_def(&mut self, src: InFile<ast::Static>) -> Option<StaticId> {
184 self.to_def(src, keys::STATIC)
186 pub(super) fn const_to_def(&mut self, src: InFile<ast::Const>) -> Option<ConstId> {
187 self.to_def(src, keys::CONST)
189 pub(super) fn type_alias_to_def(&mut self, src: InFile<ast::TypeAlias>) -> Option<TypeAliasId> {
190 self.to_def(src, keys::TYPE_ALIAS)
192 pub(super) fn record_field_to_def(&mut self, src: InFile<ast::RecordField>) -> Option<FieldId> {
193 self.to_def(src, keys::RECORD_FIELD)
195 pub(super) fn tuple_field_to_def(&mut self, src: InFile<ast::TupleField>) -> Option<FieldId> {
196 self.to_def(src, keys::TUPLE_FIELD)
198 pub(super) fn enum_variant_to_def(
200 src: InFile<ast::Variant>,
201 ) -> Option<EnumVariantId> {
202 self.to_def(src, keys::VARIANT)
204 pub(super) fn bind_pat_to_def(
206 src: InFile<ast::IdentPat>,
207 ) -> Option<(DefWithBodyId, PatId)> {
208 let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
209 let (_body, source_map) = self.db.body_with_source_map(container);
210 let src = src.map(ast::Pat::from);
211 let pat_id = source_map.node_pat(src.as_ref())?;
212 Some((container, pat_id))
214 pub(super) fn self_param_to_def(
216 src: InFile<ast::SelfParam>,
217 ) -> Option<(DefWithBodyId, PatId)> {
218 let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
219 let (_body, source_map) = self.db.body_with_source_map(container);
220 let pat_id = source_map.node_self_param(src.as_ref())?;
221 Some((container, pat_id))
223 pub(super) fn label_to_def(
225 src: InFile<ast::Label>,
226 ) -> Option<(DefWithBodyId, LabelId)> {
227 let container = self.find_pat_or_label_container(src.as_ref().map(|it| it.syntax()))?;
228 let (_body, source_map) = self.db.body_with_source_map(container);
229 let label_id = source_map.node_label(src.as_ref())?;
230 Some((container, label_id))
233 pub(super) fn item_to_macro_call(&mut self, src: InFile<ast::Item>) -> Option<MacroCallId> {
234 let map = self.dyn_map(src.as_ref())?;
235 map[keys::ATTR_MACRO].get(&src).copied()
238 fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
243 self.dyn_map(src.as_ref())?[key].get(&src).copied()
246 fn dyn_map<Ast: AstNode + 'static>(&mut self, src: InFile<&Ast>) -> Option<&DynMap> {
247 let container = self.find_container(src.map(|it| it.syntax()))?;
250 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
254 pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
255 let container: ChildContainer =
256 self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
259 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
260 dyn_map[keys::TYPE_PARAM].get(&src).copied()
263 pub(super) fn lifetime_param_to_def(
265 src: InFile<ast::LifetimeParam>,
266 ) -> Option<LifetimeParamId> {
267 let container: ChildContainer =
268 self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
271 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
272 dyn_map[keys::LIFETIME_PARAM].get(&src).copied()
275 pub(super) fn const_param_to_def(
277 src: InFile<ast::ConstParam>,
278 ) -> Option<ConstParamId> {
279 let container: ChildContainer =
280 self.find_generic_param_container(src.as_ref().map(|it| it.syntax()))?.into();
283 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
284 dyn_map[keys::CONST_PARAM].get(&src).copied()
287 // FIXME: use DynMap as well?
288 pub(super) fn macro_to_def(&mut self, src: InFile<ast::Macro>) -> Option<MacroDefId> {
289 let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
290 let ast_id = AstId::new(src.file_id, file_ast_id.upcast());
291 let kind = MacroDefKind::Declarative(ast_id);
292 let file_id = src.file_id.original_file(self.db.upcast());
293 let krate = self.file_to_def(file_id).get(0).copied()?.krate();
294 Some(MacroDefId { krate, kind, local_inner: false })
297 pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
298 for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
299 if let Some(res) = self.container_to_def(container) {
304 let def = self.file_to_def(src.file_id.original_file(self.db.upcast())).get(0).copied()?;
308 fn container_to_def(&mut self, container: InFile<SyntaxNode>) -> Option<ChildContainer> {
309 let cont = match_ast! {
310 match (container.value) {
312 let def = self.module_to_def(container.with_value(it))?;
316 let def = self.trait_to_def(container.with_value(it))?;
320 let def = self.impl_to_def(container.with_value(it))?;
324 let def = self.fn_to_def(container.with_value(it))?;
325 DefWithBodyId::from(def).into()
328 let def = self.struct_to_def(container.with_value(it))?;
329 VariantId::from(def).into()
332 let def = self.enum_to_def(container.with_value(it))?;
336 let def = self.union_to_def(container.with_value(it))?;
337 VariantId::from(def).into()
340 let def = self.static_to_def(container.with_value(it))?;
341 DefWithBodyId::from(def).into()
344 let def = self.const_to_def(container.with_value(it))?;
345 DefWithBodyId::from(def).into()
347 ast::TypeAlias(it) => {
348 let def = self.type_alias_to_def(container.with_value(it))?;
351 ast::Variant(it) => {
352 let def = self.enum_variant_to_def(container.with_value(it))?;
353 VariantId::from(def).into()
361 fn find_generic_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
362 for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
363 let res: GenericDefId = match_ast! {
364 match (container.value) {
365 ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
366 ast::Struct(it) => self.struct_to_def(container.with_value(it))?.into(),
367 ast::Enum(it) => self.enum_to_def(container.with_value(it))?.into(),
368 ast::Trait(it) => self.trait_to_def(container.with_value(it))?.into(),
369 ast::TypeAlias(it) => self.type_alias_to_def(container.with_value(it))?.into(),
370 ast::Impl(it) => self.impl_to_def(container.with_value(it))?.into(),
379 fn find_pat_or_label_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
380 for container in src.cloned().ancestors_with_macros(self.db.upcast()).skip(1) {
381 let res: DefWithBodyId = match_ast! {
382 match (container.value) {
383 ast::Const(it) => self.const_to_def(container.with_value(it))?.into(),
384 ast::Static(it) => self.static_to_def(container.with_value(it))?.into(),
385 ast::Fn(it) => self.fn_to_def(container.with_value(it))?.into(),
395 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
396 pub(crate) enum ChildContainer {
397 DefWithBodyId(DefWithBodyId),
402 VariantId(VariantId),
403 TypeAliasId(TypeAliasId),
404 /// XXX: this might be the same def as, for example an `EnumId`. However,
405 /// here the children are generic parameters, and not, eg enum variants.
406 GenericDefId(GenericDefId),
420 impl ChildContainer {
421 fn child_by_source(self, db: &dyn HirDatabase) -> DynMap {
422 let db = db.upcast();
424 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
425 ChildContainer::ModuleId(it) => it.child_by_source(db),
426 ChildContainer::TraitId(it) => it.child_by_source(db),
427 ChildContainer::ImplId(it) => it.child_by_source(db),
428 ChildContainer::EnumId(it) => it.child_by_source(db),
429 ChildContainer::VariantId(it) => it.child_by_source(db),
430 ChildContainer::TypeAliasId(_) => DynMap::default(),
431 ChildContainer::GenericDefId(it) => it.child_by_source(db),