aboutsummaryrefslogtreecommitdiff
path: root/crates/ra_hir
diff options
context:
space:
mode:
Diffstat (limited to 'crates/ra_hir')
-rw-r--r--crates/ra_hir/src/code_model.rs6
-rw-r--r--crates/ra_hir/src/from_id.rs12
-rw-r--r--crates/ra_hir/src/lib.rs1
-rw-r--r--crates/ra_hir/src/semantics.rs102
-rw-r--r--crates/ra_hir/src/semantics/source_to_def.rs276
-rw-r--r--crates/ra_hir/src/source_binder.rs278
6 files changed, 329 insertions, 346 deletions
diff --git a/crates/ra_hir/src/code_model.rs b/crates/ra_hir/src/code_model.rs
index efc3502d0..034fb7cfa 100644
--- a/crates/ra_hir/src/code_model.rs
+++ b/crates/ra_hir/src/code_model.rs
@@ -778,7 +778,7 @@ impl GenericDef {
778 778
779#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] 779#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
780pub struct Local { 780pub struct Local {
781 pub(crate) parent: DefWithBody, 781 pub(crate) parent: DefWithBodyId,
782 pub(crate) pat_id: PatId, 782 pub(crate) pat_id: PatId,
783} 783}
784 784
@@ -807,11 +807,11 @@ impl Local {
807 } 807 }
808 808
809 pub fn parent(self, _db: &impl HirDatabase) -> DefWithBody { 809 pub fn parent(self, _db: &impl HirDatabase) -> DefWithBody {
810 self.parent 810 self.parent.into()
811 } 811 }
812 812
813 pub fn module(self, db: &impl HirDatabase) -> Module { 813 pub fn module(self, db: &impl HirDatabase) -> Module {
814 self.parent.module(db) 814 self.parent(db).module(db)
815 } 815 }
816 816
817 pub fn ty(self, db: &impl HirDatabase) -> Type { 817 pub fn ty(self, db: &impl HirDatabase) -> Type {
diff --git a/crates/ra_hir/src/from_id.rs b/crates/ra_hir/src/from_id.rs
index 3aa7c4870..cbfa91d6c 100644
--- a/crates/ra_hir/src/from_id.rs
+++ b/crates/ra_hir/src/from_id.rs
@@ -4,12 +4,12 @@
4//! are splitting the hir. 4//! are splitting the hir.
5 5
6use hir_def::{ 6use hir_def::{
7 AdtId, AssocItemId, AttrDefId, DefWithBodyId, EnumVariantId, GenericDefId, ModuleDefId, 7 expr::PatId, AdtId, AssocItemId, AttrDefId, DefWithBodyId, EnumVariantId, GenericDefId,
8 StructFieldId, VariantId, 8 ModuleDefId, StructFieldId, VariantId,
9}; 9};
10 10
11use crate::{ 11use crate::{
12 Adt, AssocItem, AttrDef, DefWithBody, EnumVariant, GenericDef, ModuleDef, StructField, 12 Adt, AssocItem, AttrDef, DefWithBody, EnumVariant, GenericDef, Local, ModuleDef, StructField,
13 VariantDef, 13 VariantDef,
14}; 14};
15 15
@@ -222,3 +222,9 @@ impl From<AssocItem> for GenericDefId {
222 } 222 }
223 } 223 }
224} 224}
225
226impl From<(DefWithBodyId, PatId)> for Local {
227 fn from((parent, pat_id): (DefWithBodyId, PatId)) -> Self {
228 Local { parent, pat_id }
229 }
230}
diff --git a/crates/ra_hir/src/lib.rs b/crates/ra_hir/src/lib.rs
index 3aa964fb6..cefbd80e6 100644
--- a/crates/ra_hir/src/lib.rs
+++ b/crates/ra_hir/src/lib.rs
@@ -29,7 +29,6 @@ macro_rules! impl_froms {
29mod semantics; 29mod semantics;
30pub mod db; 30pub mod db;
31mod source_analyzer; 31mod source_analyzer;
32mod source_binder;
33 32
34pub mod diagnostics; 33pub mod diagnostics;
35 34
diff --git a/crates/ra_hir/src/semantics.rs b/crates/ra_hir/src/semantics.rs
index 4a9cb7b3e..74901e318 100644
--- a/crates/ra_hir/src/semantics.rs
+++ b/crates/ra_hir/src/semantics.rs
@@ -1,32 +1,33 @@
1//! See `Semantics`. 1//! See `Semantics`.
2 2
3mod source_to_def;
4
3use std::{cell::RefCell, fmt, iter::successors}; 5use std::{cell::RefCell, fmt, iter::successors};
4 6
5use hir_def::{ 7use hir_def::{
6 resolver::{self, HasResolver, Resolver}, 8 resolver::{self, HasResolver, Resolver},
7 DefWithBodyId, TraitId, 9 TraitId,
8}; 10};
11use hir_expand::ExpansionInfo;
9use ra_db::{FileId, FileRange}; 12use ra_db::{FileId, FileRange};
13use ra_prof::profile;
10use ra_syntax::{ 14use ra_syntax::{
11 algo::skip_trivia_token, ast, match_ast, AstNode, Direction, SyntaxNode, SyntaxToken, 15 algo::skip_trivia_token, ast, AstNode, Direction, SyntaxNode, SyntaxToken, TextRange, TextUnit,
12 TextRange, TextUnit,
13}; 16};
14use rustc_hash::{FxHashMap, FxHashSet}; 17use rustc_hash::{FxHashMap, FxHashSet};
15 18
16use crate::{ 19use crate::{
17 db::HirDatabase, 20 db::HirDatabase,
21 semantics::source_to_def::{ChildContainer, SourceToDefCache, SourceToDefCtx},
18 source_analyzer::{resolve_hir_path, ReferenceDescriptor, SourceAnalyzer}, 22 source_analyzer::{resolve_hir_path, ReferenceDescriptor, SourceAnalyzer},
19 source_binder::{ChildContainer, SourceBinder},
20 Function, HirFileId, InFile, Local, MacroDef, Module, ModuleDef, Name, Origin, Path, 23 Function, HirFileId, InFile, Local, MacroDef, Module, ModuleDef, Name, Origin, Path,
21 PathResolution, ScopeDef, StructField, Trait, Type, TypeParam, VariantDef, 24 PathResolution, ScopeDef, StructField, Trait, Type, TypeParam, VariantDef,
22}; 25};
23use hir_expand::ExpansionInfo;
24use ra_prof::profile;
25 26
26/// Primary API to get semantic information, like types, from syntax trees. 27/// Primary API to get semantic information, like types, from syntax trees.
27pub struct Semantics<'db, DB> { 28pub struct Semantics<'db, DB> {
28 pub db: &'db DB, 29 pub db: &'db DB,
29 sb: RefCell<SourceBinder>, 30 s2d_cache: RefCell<SourceToDefCache>,
30 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>, 31 cache: RefCell<FxHashMap<SyntaxNode, HirFileId>>,
31} 32}
32 33
@@ -38,8 +39,7 @@ impl<DB> fmt::Debug for Semantics<'_, DB> {
38 39
39impl<'db, DB: HirDatabase> Semantics<'db, DB> { 40impl<'db, DB: HirDatabase> Semantics<'db, DB> {
40 pub fn new(db: &DB) -> Semantics<DB> { 41 pub fn new(db: &DB) -> Semantics<DB> {
41 let sb = RefCell::new(SourceBinder::new()); 42 Semantics { db, s2d_cache: Default::default(), cache: Default::default() }
42 Semantics { db, sb, cache: RefCell::default() }
43 } 43 }
44 44
45 pub fn parse(&self, file_id: FileId) -> ast::SourceFile { 45 pub fn parse(&self, file_id: FileId) -> ast::SourceFile {
@@ -136,13 +136,19 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
136 // FIXME: use this instead? 136 // FIXME: use this instead?
137 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>; 137 // pub fn resolve_name_ref(&self, name_ref: &ast::NameRef) -> Option<???>;
138 138
139 pub fn to_def<T: ToDef + Clone>(&self, src: &T) -> Option<T::Def> { 139 pub fn to_def<T: ToDef>(&self, src: &T) -> Option<T::Def> {
140 let src = self.find_file(src.syntax().clone()).with_value(src).cloned();
140 T::to_def(self, src) 141 T::to_def(self, src)
141 } 142 }
142 143
144 fn with_ctx<F: FnOnce(&mut SourceToDefCtx<&DB>) -> T, T>(&self, f: F) -> T {
145 let mut cache = self.s2d_cache.borrow_mut();
146 let mut ctx = SourceToDefCtx { db: self.db, cache: &mut *cache };
147 f(&mut ctx)
148 }
149
143 pub fn to_module_def(&self, file: FileId) -> Option<Module> { 150 pub fn to_module_def(&self, file: FileId) -> Option<Module> {
144 let mut sb = self.sb.borrow_mut(); 151 self.with_ctx(|ctx| ctx.file_to_def(file)).map(Module::from)
145 sb.to_module_def(self.db, file)
146 } 152 }
147 153
148 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db, DB> { 154 pub fn scope(&self, node: &SyntaxNode) -> SemanticsScope<'db, DB> {
@@ -176,7 +182,7 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
176 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextUnit>) -> SourceAnalyzer { 182 fn analyze2(&self, src: InFile<&SyntaxNode>, offset: Option<TextUnit>) -> SourceAnalyzer {
177 let _p = profile("Semantics::analyze2"); 183 let _p = profile("Semantics::analyze2");
178 184
179 let container = match self.sb.borrow_mut().find_container(self.db, src) { 185 let container = match self.with_ctx(|ctx| ctx.find_container(src)) {
180 Some(it) => it, 186 Some(it) => it,
181 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src), 187 None => return SourceAnalyzer::new_for_resolver(Resolver::default(), src),
182 }; 188 };
@@ -233,68 +239,42 @@ impl<'db, DB: HirDatabase> Semantics<'db, DB> {
233 } 239 }
234} 240}
235 241
236pub trait ToDef: Sized + AstNode + 'static { 242pub trait ToDef: AstNode + Clone {
237 type Def; 243 type Def;
238 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: &Self) -> Option<Self::Def>; 244
245 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: InFile<Self>) -> Option<Self::Def>;
239} 246}
240 247
241macro_rules! to_def_impls { 248macro_rules! to_def_impls {
242 ($(($def:path, $ast:path)),* ,) => {$( 249 ($(($def:path, $ast:path, $meth:ident)),* ,) => {$(
243 impl ToDef for $ast { 250 impl ToDef for $ast {
244 type Def = $def; 251 type Def = $def;
245 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: &Self) 252 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: InFile<Self>) -> Option<Self::Def> {
246 -> Option<Self::Def> 253 sema.with_ctx(|ctx| ctx.$meth(src)).map(<$def>::from)
247 {
248 let src = sema.find_file(src.syntax().clone()).with_value(src);
249 sema.sb.borrow_mut().to_id(sema.db, src.cloned()).map(Into::into)
250 } 254 }
251 } 255 }
252 )*} 256 )*}
253} 257}
254 258
255to_def_impls![ 259to_def_impls![
256 (crate::Module, ast::Module), 260 (crate::Module, ast::Module, module_to_def),
257 (crate::Struct, ast::StructDef), 261 (crate::Struct, ast::StructDef, struct_to_def),
258 (crate::Enum, ast::EnumDef), 262 (crate::Enum, ast::EnumDef, enum_to_def),
259 (crate::Union, ast::UnionDef), 263 (crate::Union, ast::UnionDef, union_to_def),
260 (crate::Trait, ast::TraitDef), 264 (crate::Trait, ast::TraitDef, trait_to_def),
261 (crate::ImplBlock, ast::ImplBlock), 265 (crate::ImplBlock, ast::ImplBlock, impl_to_def),
262 (crate::TypeAlias, ast::TypeAliasDef), 266 (crate::TypeAlias, ast::TypeAliasDef, type_alias_to_def),
263 (crate::Const, ast::ConstDef), 267 (crate::Const, ast::ConstDef, const_to_def),
264 (crate::Static, ast::StaticDef), 268 (crate::Static, ast::StaticDef, static_to_def),
265 (crate::Function, ast::FnDef), 269 (crate::Function, ast::FnDef, fn_to_def),
266 (crate::StructField, ast::RecordFieldDef), 270 (crate::StructField, ast::RecordFieldDef, record_field_to_def),
267 (crate::EnumVariant, ast::EnumVariant), 271 (crate::StructField, ast::TupleFieldDef, tuple_field_to_def),
268 (crate::TypeParam, ast::TypeParam), 272 (crate::EnumVariant, ast::EnumVariant, enum_variant_to_def),
269 (crate::MacroDef, ast::MacroCall), // this one is dubious, not all calls are macros 273 (crate::TypeParam, ast::TypeParam, type_param_to_def),
274 (crate::MacroDef, ast::MacroCall, macro_call_to_def), // this one is dubious, not all calls are macros
275 (crate::Local, ast::BindPat, bind_pat_to_def),
270]; 276];
271 277
272impl ToDef for ast::BindPat {
273 type Def = Local;
274
275 fn to_def<DB: HirDatabase>(sema: &Semantics<DB>, src: &Self) -> Option<Local> {
276 let src = sema.find_file(src.syntax().clone()).with_value(src);
277 let file_id = src.file_id;
278 let mut sb = sema.sb.borrow_mut();
279 let db = sema.db;
280 let parent: DefWithBodyId = src.value.syntax().ancestors().find_map(|it| {
281 let res = match_ast! {
282 match it {
283 ast::ConstDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
284 ast::StaticDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
285 ast::FnDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
286 _ => return None,
287 }
288 };
289 Some(res)
290 })?;
291 let (_body, source_map) = db.body_with_source_map(parent);
292 let src = src.cloned().map(ast::Pat::from);
293 let pat_id = source_map.node_pat(src.as_ref())?;
294 Some(Local { parent: parent.into(), pat_id })
295 }
296}
297
298fn find_root(node: &SyntaxNode) -> SyntaxNode { 278fn find_root(node: &SyntaxNode) -> SyntaxNode {
299 node.ancestors().last().unwrap() 279 node.ancestors().last().unwrap()
300} 280}
diff --git a/crates/ra_hir/src/semantics/source_to_def.rs b/crates/ra_hir/src/semantics/source_to_def.rs
new file mode 100644
index 000000000..884b535b2
--- /dev/null
+++ b/crates/ra_hir/src/semantics/source_to_def.rs
@@ -0,0 +1,276 @@
1//! Maps *syntax* of various definitions to their semantic ids.
2
3use hir_def::{
4 child_by_source::ChildBySource,
5 dyn_map::DynMap,
6 expr::PatId,
7 keys::{self, Key},
8 ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, ImplId, ModuleId,
9 StaticId, StructFieldId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, VariantId,
10};
11use hir_expand::{name::AsName, AstId, MacroDefKind};
12use ra_db::FileId;
13use ra_prof::profile;
14use ra_syntax::{
15 ast::{self, NameOwner},
16 match_ast, AstNode, SyntaxNode,
17};
18use rustc_hash::FxHashMap;
19
20use crate::{db::HirDatabase, InFile, MacroDefId};
21
22pub(super) type SourceToDefCache = FxHashMap<ChildContainer, DynMap>;
23
24pub(super) struct SourceToDefCtx<'a, DB> {
25 pub(super) db: DB,
26 pub(super) cache: &'a mut SourceToDefCache,
27}
28
29impl<DB: HirDatabase> SourceToDefCtx<'_, &'_ DB> {
30 pub(super) fn file_to_def(&mut self, file: FileId) -> Option<ModuleId> {
31 let _p = profile("SourceBinder::to_module_def");
32 let (krate, local_id) = self.db.relevant_crates(file).iter().find_map(|&crate_id| {
33 let crate_def_map = self.db.crate_def_map(crate_id);
34 let local_id = crate_def_map.modules_for_file(file).next()?;
35 Some((crate_id, local_id))
36 })?;
37 Some(ModuleId { krate, local_id })
38 }
39
40 pub(super) fn module_to_def(&mut self, src: InFile<ast::Module>) -> Option<ModuleId> {
41 let _p = profile("module_to_def");
42 let parent_declaration = src
43 .as_ref()
44 .map(|it| it.syntax())
45 .cloned()
46 .ancestors_with_macros(self.db)
47 .skip(1)
48 .find_map(|it| {
49 let m = ast::Module::cast(it.value.clone())?;
50 Some(it.with_value(m))
51 });
52
53 let parent_module = match parent_declaration {
54 Some(parent_declaration) => self.module_to_def(parent_declaration),
55 None => {
56 let file_id = src.file_id.original_file(self.db);
57 self.file_to_def(file_id)
58 }
59 }?;
60
61 let child_name = src.value.name()?.as_name();
62 let def_map = self.db.crate_def_map(parent_module.krate);
63 let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
64 Some(ModuleId { krate: parent_module.krate, local_id: child_id })
65 }
66
67 pub(super) fn trait_to_def(&mut self, src: InFile<ast::TraitDef>) -> Option<TraitId> {
68 self.to_def(src, keys::TRAIT)
69 }
70 pub(super) fn impl_to_def(&mut self, src: InFile<ast::ImplBlock>) -> Option<ImplId> {
71 self.to_def(src, keys::IMPL)
72 }
73 pub(super) fn fn_to_def(&mut self, src: InFile<ast::FnDef>) -> Option<FunctionId> {
74 self.to_def(src, keys::FUNCTION)
75 }
76 pub(super) fn struct_to_def(&mut self, src: InFile<ast::StructDef>) -> Option<StructId> {
77 self.to_def(src, keys::STRUCT)
78 }
79 pub(super) fn enum_to_def(&mut self, src: InFile<ast::EnumDef>) -> Option<EnumId> {
80 self.to_def(src, keys::ENUM)
81 }
82 pub(super) fn union_to_def(&mut self, src: InFile<ast::UnionDef>) -> Option<UnionId> {
83 self.to_def(src, keys::UNION)
84 }
85 pub(super) fn static_to_def(&mut self, src: InFile<ast::StaticDef>) -> Option<StaticId> {
86 self.to_def(src, keys::STATIC)
87 }
88 pub(super) fn const_to_def(&mut self, src: InFile<ast::ConstDef>) -> Option<ConstId> {
89 self.to_def(src, keys::CONST)
90 }
91 pub(super) fn type_alias_to_def(
92 &mut self,
93 src: InFile<ast::TypeAliasDef>,
94 ) -> Option<TypeAliasId> {
95 self.to_def(src, keys::TYPE_ALIAS)
96 }
97 pub(super) fn record_field_to_def(
98 &mut self,
99 src: InFile<ast::RecordFieldDef>,
100 ) -> Option<StructFieldId> {
101 self.to_def(src, keys::RECORD_FIELD)
102 }
103 pub(super) fn tuple_field_to_def(
104 &mut self,
105 src: InFile<ast::TupleFieldDef>,
106 ) -> Option<StructFieldId> {
107 self.to_def(src, keys::TUPLE_FIELD)
108 }
109 pub(super) fn enum_variant_to_def(
110 &mut self,
111 src: InFile<ast::EnumVariant>,
112 ) -> Option<EnumVariantId> {
113 self.to_def(src, keys::ENUM_VARIANT)
114 }
115 pub(super) fn bind_pat_to_def(
116 &mut self,
117 src: InFile<ast::BindPat>,
118 ) -> Option<(DefWithBodyId, PatId)> {
119 let container = self.find_pat_container(src.as_ref().map(|it| it.syntax()))?;
120 let (_body, source_map) = self.db.body_with_source_map(container);
121 let src = src.map(ast::Pat::from);
122 let pat_id = source_map.node_pat(src.as_ref())?;
123 Some((container, pat_id))
124 }
125
126 fn to_def<Ast: AstNode + 'static, ID: Copy + 'static>(
127 &mut self,
128 src: InFile<Ast>,
129 key: Key<Ast, ID>,
130 ) -> Option<ID> {
131 let container = self.find_container(src.as_ref().map(|it| it.syntax()))?;
132 let db = self.db;
133 let dyn_map =
134 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
135 dyn_map[key].get(&src).copied()
136 }
137
138 pub(super) fn type_param_to_def(&mut self, src: InFile<ast::TypeParam>) -> Option<TypeParamId> {
139 let container: ChildContainer =
140 self.find_type_param_container(src.as_ref().map(|it| it.syntax()))?.into();
141 let db = self.db;
142 let dyn_map =
143 &*self.cache.entry(container).or_insert_with(|| container.child_by_source(db));
144 dyn_map[keys::TYPE_PARAM].get(&src).copied()
145 }
146
147 // FIXME: use DynMap as well?
148 pub(super) fn macro_call_to_def(&mut self, src: InFile<ast::MacroCall>) -> Option<MacroDefId> {
149 let kind = MacroDefKind::Declarative;
150 let file_id = src.file_id.original_file(self.db);
151 let krate = self.file_to_def(file_id)?.krate;
152 let file_ast_id = self.db.ast_id_map(src.file_id).ast_id(&src.value);
153 let ast_id = Some(AstId::new(src.file_id, file_ast_id));
154 Some(MacroDefId { krate: Some(krate), ast_id, kind })
155 }
156
157 pub(super) fn find_container(&mut self, src: InFile<&SyntaxNode>) -> Option<ChildContainer> {
158 for container in src.cloned().ancestors_with_macros(self.db).skip(1) {
159 let res: ChildContainer = match_ast! {
160 match (container.value) {
161 ast::Module(it) => {
162 let def = self.module_to_def(container.with_value(it))?;
163 def.into()
164 },
165 ast::TraitDef(it) => {
166 let def = self.trait_to_def(container.with_value(it))?;
167 def.into()
168 },
169 ast::ImplBlock(it) => {
170 let def = self.impl_to_def(container.with_value(it))?;
171 def.into()
172 },
173 ast::FnDef(it) => {
174 let def = self.fn_to_def(container.with_value(it))?;
175 DefWithBodyId::from(def).into()
176 },
177 ast::StructDef(it) => {
178 let def = self.struct_to_def(container.with_value(it))?;
179 VariantId::from(def).into()
180 },
181 ast::EnumDef(it) => {
182 let def = self.enum_to_def(container.with_value(it))?;
183 def.into()
184 },
185 ast::UnionDef(it) => {
186 let def = self.union_to_def(container.with_value(it))?;
187 VariantId::from(def).into()
188 },
189 ast::StaticDef(it) => {
190 let def = self.static_to_def(container.with_value(it))?;
191 DefWithBodyId::from(def).into()
192 },
193 ast::ConstDef(it) => {
194 let def = self.const_to_def(container.with_value(it))?;
195 DefWithBodyId::from(def).into()
196 },
197 _ => continue,
198 }
199 };
200 return Some(res);
201 }
202
203 let def = self.file_to_def(src.file_id.original_file(self.db))?;
204 Some(def.into())
205 }
206
207 fn find_type_param_container(&mut self, src: InFile<&SyntaxNode>) -> Option<GenericDefId> {
208 for container in src.cloned().ancestors_with_macros(self.db).skip(1) {
209 let res: GenericDefId = match_ast! {
210 match (container.value) {
211 ast::FnDef(it) => { self.fn_to_def(container.with_value(it))?.into() },
212 ast::StructDef(it) => { self.struct_to_def(container.with_value(it))?.into() },
213 ast::EnumDef(it) => { self.enum_to_def(container.with_value(it))?.into() },
214 ast::TraitDef(it) => { self.trait_to_def(container.with_value(it))?.into() },
215 ast::TypeAliasDef(it) => { self.type_alias_to_def(container.with_value(it))?.into() },
216 ast::ImplBlock(it) => { self.impl_to_def(container.with_value(it))?.into() },
217 _ => continue,
218 }
219 };
220 return Some(res);
221 }
222 None
223 }
224
225 fn find_pat_container(&mut self, src: InFile<&SyntaxNode>) -> Option<DefWithBodyId> {
226 for container in src.cloned().ancestors_with_macros(self.db).skip(1) {
227 let res: DefWithBodyId = match_ast! {
228 match (container.value) {
229 ast::ConstDef(it) => { self.const_to_def(container.with_value(it))?.into() },
230 ast::StaticDef(it) => { self.static_to_def(container.with_value(it))?.into() },
231 ast::FnDef(it) => { self.fn_to_def(container.with_value(it))?.into() },
232 _ => continue,
233 }
234 };
235 return Some(res);
236 }
237 None
238 }
239}
240
241#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
242pub(crate) enum ChildContainer {
243 DefWithBodyId(DefWithBodyId),
244 ModuleId(ModuleId),
245 TraitId(TraitId),
246 ImplId(ImplId),
247 EnumId(EnumId),
248 VariantId(VariantId),
249 /// XXX: this might be the same def as, for example an `EnumId`. However,
250 /// here the children generic parameters, and not, eg enum variants.
251 GenericDefId(GenericDefId),
252}
253impl_froms! {
254 ChildContainer:
255 DefWithBodyId,
256 ModuleId,
257 TraitId,
258 ImplId,
259 EnumId,
260 VariantId,
261 GenericDefId
262}
263
264impl ChildContainer {
265 fn child_by_source(self, db: &impl HirDatabase) -> DynMap {
266 match self {
267 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
268 ChildContainer::ModuleId(it) => it.child_by_source(db),
269 ChildContainer::TraitId(it) => it.child_by_source(db),
270 ChildContainer::ImplId(it) => it.child_by_source(db),
271 ChildContainer::EnumId(it) => it.child_by_source(db),
272 ChildContainer::VariantId(it) => it.child_by_source(db),
273 ChildContainer::GenericDefId(it) => it.child_by_source(db),
274 }
275 }
276}
diff --git a/crates/ra_hir/src/source_binder.rs b/crates/ra_hir/src/source_binder.rs
deleted file mode 100644
index 4353e25ac..000000000
--- a/crates/ra_hir/src/source_binder.rs
+++ /dev/null
@@ -1,278 +0,0 @@
1//! `SourceBinder` is the main entry point for getting info about source code.
2//! It's main task is to map source syntax trees to hir-level IDs.
3
4use hir_def::{
5 child_by_source::ChildBySource,
6 dyn_map::DynMap,
7 keys::{self, Key},
8 ConstId, DefWithBodyId, EnumId, EnumVariantId, FunctionId, GenericDefId, ImplId, ModuleId,
9 StaticId, StructFieldId, StructId, TraitId, TypeAliasId, TypeParamId, UnionId, VariantId,
10};
11use hir_expand::{name::AsName, AstId, InFile, MacroDefId, MacroDefKind};
12use ra_db::FileId;
13use ra_prof::profile;
14use ra_syntax::{
15 ast::{self, NameOwner},
16 match_ast, AstNode, SyntaxNode,
17};
18use rustc_hash::FxHashMap;
19
20use crate::{db::HirDatabase, Module};
21
22pub(crate) struct SourceBinder {
23 child_by_source_cache: FxHashMap<ChildContainer, DynMap>,
24}
25
26impl SourceBinder {
27 pub(crate) fn new() -> SourceBinder {
28 SourceBinder { child_by_source_cache: FxHashMap::default() }
29 }
30
31 pub(crate) fn to_module_def(&mut self, db: &impl HirDatabase, file: FileId) -> Option<Module> {
32 let _p = profile("SourceBinder::to_module_def");
33 let (krate, local_id) = db.relevant_crates(file).iter().find_map(|&crate_id| {
34 let crate_def_map = db.crate_def_map(crate_id);
35 let local_id = crate_def_map.modules_for_file(file).next()?;
36 Some((crate_id, local_id))
37 })?;
38 Some(Module { id: ModuleId { krate, local_id } })
39 }
40
41 pub(crate) fn to_id<T: ToId>(
42 &mut self,
43 db: &impl HirDatabase,
44 src: InFile<T>,
45 ) -> Option<T::ID> {
46 T::to_id(db, self, src)
47 }
48
49 pub(crate) fn find_container(
50 &mut self,
51 db: &impl HirDatabase,
52 src: InFile<&SyntaxNode>,
53 ) -> Option<ChildContainer> {
54 for container in src.cloned().ancestors_with_macros(db).skip(1) {
55 let res: ChildContainer = match_ast! {
56 match (container.value) {
57 ast::TraitDef(it) => {
58 let def: TraitId = self.to_id(db, container.with_value(it))?;
59 def.into()
60 },
61 ast::ImplBlock(it) => {
62 let def: ImplId = self.to_id(db, container.with_value(it))?;
63 def.into()
64 },
65 ast::FnDef(it) => {
66 let def: FunctionId = self.to_id(db, container.with_value(it))?;
67 DefWithBodyId::from(def).into()
68 },
69 ast::StaticDef(it) => {
70 let def: StaticId = self.to_id(db, container.with_value(it))?;
71 DefWithBodyId::from(def).into()
72 },
73 ast::ConstDef(it) => {
74 let def: ConstId = self.to_id(db, container.with_value(it))?;
75 DefWithBodyId::from(def).into()
76 },
77 ast::EnumDef(it) => {
78 let def: EnumId = self.to_id(db, container.with_value(it))?;
79 def.into()
80 },
81 ast::StructDef(it) => {
82 let def: StructId = self.to_id(db, container.with_value(it))?;
83 VariantId::from(def).into()
84 },
85 ast::UnionDef(it) => {
86 let def: UnionId = self.to_id(db, container.with_value(it))?;
87 VariantId::from(def).into()
88 },
89 ast::Module(it) => {
90 let def: ModuleId = self.to_id(db, container.with_value(it))?;
91 def.into()
92 },
93 _ => { continue },
94 }
95 };
96 return Some(res);
97 }
98
99 let c = self.to_module_def(db, src.file_id.original_file(db))?;
100 Some(c.id.into())
101 }
102
103 fn child_by_source(&mut self, db: &impl HirDatabase, container: ChildContainer) -> &DynMap {
104 self.child_by_source_cache.entry(container).or_insert_with(|| match container {
105 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
106 ChildContainer::ModuleId(it) => it.child_by_source(db),
107 ChildContainer::TraitId(it) => it.child_by_source(db),
108 ChildContainer::ImplId(it) => it.child_by_source(db),
109 ChildContainer::EnumId(it) => it.child_by_source(db),
110 ChildContainer::VariantId(it) => it.child_by_source(db),
111 ChildContainer::GenericDefId(it) => it.child_by_source(db),
112 })
113 }
114}
115
116pub(crate) trait ToId: Sized {
117 type ID: Sized + Copy + 'static;
118 fn to_id<DB: HirDatabase>(
119 db: &DB,
120 sb: &mut SourceBinder,
121 src: InFile<Self>,
122 ) -> Option<Self::ID>;
123}
124
125#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
126pub(crate) enum ChildContainer {
127 DefWithBodyId(DefWithBodyId),
128 ModuleId(ModuleId),
129 TraitId(TraitId),
130 ImplId(ImplId),
131 EnumId(EnumId),
132 VariantId(VariantId),
133 /// XXX: this might be the same def as, for example an `EnumId`. However,
134 /// here the children generic parameters, and not, eg enum variants.
135 GenericDefId(GenericDefId),
136}
137impl_froms! {
138 ChildContainer:
139 DefWithBodyId,
140 ModuleId,
141 TraitId,
142 ImplId,
143 EnumId,
144 VariantId,
145 GenericDefId
146}
147
148pub(crate) trait ToIdByKey: Sized + AstNode + 'static {
149 type ID: Sized + Copy + 'static;
150 const KEY: Key<Self, Self::ID>;
151}
152
153impl<T: ToIdByKey> ToId for T {
154 type ID = <T as ToIdByKey>::ID;
155 fn to_id<DB: HirDatabase>(
156 db: &DB,
157 sb: &mut SourceBinder,
158 src: InFile<Self>,
159 ) -> Option<Self::ID> {
160 let container = sb.find_container(db, src.as_ref().map(|it| it.syntax()))?;
161 let dyn_map =
162 &*sb.child_by_source_cache.entry(container).or_insert_with(|| match container {
163 ChildContainer::DefWithBodyId(it) => it.child_by_source(db),
164 ChildContainer::ModuleId(it) => it.child_by_source(db),
165 ChildContainer::TraitId(it) => it.child_by_source(db),
166 ChildContainer::ImplId(it) => it.child_by_source(db),
167 ChildContainer::EnumId(it) => it.child_by_source(db),
168 ChildContainer::VariantId(it) => it.child_by_source(db),
169 ChildContainer::GenericDefId(it) => it.child_by_source(db),
170 });
171 dyn_map[T::KEY].get(&src).copied()
172 }
173}
174
175macro_rules! to_id_key_impls {
176 ($(($id:ident, $ast:path, $key:path)),* ,) => {$(
177 impl ToIdByKey for $ast {
178 type ID = $id;
179 const KEY: Key<Self, Self::ID> = $key;
180 }
181 )*}
182}
183
184to_id_key_impls![
185 (StructId, ast::StructDef, keys::STRUCT),
186 (UnionId, ast::UnionDef, keys::UNION),
187 (EnumId, ast::EnumDef, keys::ENUM),
188 (TraitId, ast::TraitDef, keys::TRAIT),
189 (FunctionId, ast::FnDef, keys::FUNCTION),
190 (StaticId, ast::StaticDef, keys::STATIC),
191 (ConstId, ast::ConstDef, keys::CONST),
192 (TypeAliasId, ast::TypeAliasDef, keys::TYPE_ALIAS),
193 (ImplId, ast::ImplBlock, keys::IMPL),
194 (StructFieldId, ast::RecordFieldDef, keys::RECORD_FIELD),
195 (EnumVariantId, ast::EnumVariant, keys::ENUM_VARIANT),
196];
197
198// FIXME: use DynMap as well?
199impl ToId for ast::MacroCall {
200 type ID = MacroDefId;
201 fn to_id<DB: HirDatabase>(
202 db: &DB,
203 sb: &mut SourceBinder,
204 src: InFile<Self>,
205 ) -> Option<Self::ID> {
206 let kind = MacroDefKind::Declarative;
207
208 let krate = sb.to_module_def(db, src.file_id.original_file(db))?.id.krate;
209
210 let ast_id = Some(AstId::new(src.file_id, db.ast_id_map(src.file_id).ast_id(&src.value)));
211
212 Some(MacroDefId { krate: Some(krate), ast_id, kind })
213 }
214}
215
216impl ToId for ast::TypeParam {
217 type ID = TypeParamId;
218
219 fn to_id<DB: HirDatabase>(
220 db: &DB,
221 sb: &mut SourceBinder,
222 src: InFile<Self>,
223 ) -> Option<Self::ID> {
224 let file_id = src.file_id;
225 let parent: GenericDefId = src.value.syntax().ancestors().find_map(|it| {
226 let res = match_ast! {
227 match it {
228 ast::FnDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
229 ast::StructDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
230 ast::EnumDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
231 ast::TraitDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
232 ast::TypeAliasDef(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
233 ast::ImplBlock(value) => { sb.to_id(db, InFile { value, file_id})?.into() },
234 _ => return None,
235 }
236 };
237 Some(res)
238 })?;
239 sb.child_by_source(db, parent.into())[keys::TYPE_PARAM].get(&src).copied()
240 }
241}
242
243impl ToId for ast::Module {
244 type ID = ModuleId;
245
246 fn to_id<DB: HirDatabase>(
247 db: &DB,
248 sb: &mut SourceBinder,
249 src: InFile<ast::Module>,
250 ) -> Option<ModuleId> {
251 {
252 let _p = profile("ast::Module::to_def");
253 let parent_declaration = src
254 .as_ref()
255 .map(|it| it.syntax())
256 .cloned()
257 .ancestors_with_macros(db)
258 .skip(1)
259 .find_map(|it| {
260 let m = ast::Module::cast(it.value.clone())?;
261 Some(it.with_value(m))
262 });
263
264 let parent_module = match parent_declaration {
265 Some(parent_declaration) => sb.to_id(db, parent_declaration)?,
266 None => {
267 let file_id = src.file_id.original_file(db);
268 sb.to_module_def(db, file_id)?.id
269 }
270 };
271
272 let child_name = src.value.name()?.as_name();
273 let def_map = db.crate_def_map(parent_module.krate);
274 let child_id = *def_map[parent_module.local_id].children.get(&child_name)?;
275 Some(ModuleId { krate: parent_module.krate, local_id: child_id })
276 }
277 }
278}