1 //! `hir_def` crate contains everything between macro expansion and type
4 //! It defines various items (structs, enums, traits) which comprises Rust code,
5 //! as well as an algorithm for resolving paths to such entities.
7 //! Note that `hir_def` is a work in progress, so not all of the above is
11 macro_rules! eprintln {
12 ($($tt:tt)*) => { stdx::eprintln!($($tt)*) };
44 pub mod child_by_source;
53 use std::hash::{Hash, Hasher};
56 use base_db::{impl_intern_key, salsa, CrateId};
58 ast_id_map::FileAstId, eager::expand_eager_macro, hygiene::Hygiene, AstId, HirFileId, InFile,
59 MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
63 use crate::builtin_type::BuiltinType;
65 Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
70 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73 pub local_id: LocalModuleId,
76 /// An ID of a module, **local** to a specific crate
77 pub type LocalModuleId = Idx<nameres::ModuleData>;
80 pub struct ItemLoc<N: ItemTreeNode> {
81 pub container: ContainerId,
82 pub id: ItemTreeId<N>,
85 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
86 fn clone(&self) -> Self {
87 Self { container: self.container, id: self.id }
91 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
93 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
94 fn eq(&self, other: &Self) -> bool {
95 self.container == other.container && self.id == other.id
99 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
101 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
102 fn hash<H: Hasher>(&self, state: &mut H) {
103 self.container.hash(state);
109 pub struct AssocItemLoc<N: ItemTreeNode> {
110 pub container: AssocContainerId,
111 pub id: ItemTreeId<N>,
114 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
115 fn clone(&self) -> Self {
116 Self { container: self.container, id: self.id }
120 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
122 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
123 fn eq(&self, other: &Self) -> bool {
124 self.container == other.container && self.id == other.id
128 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
130 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
131 fn hash<H: Hasher>(&self, state: &mut H) {
132 self.container.hash(state);
137 macro_rules! impl_intern {
138 ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
139 impl_intern_key!($id);
141 impl Intern for $loc {
143 fn intern(self, db: &dyn db::DefDatabase) -> $id {
148 impl Lookup for $id {
150 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
157 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
158 pub struct FunctionId(salsa::InternId);
159 type FunctionLoc = AssocItemLoc<Function>;
160 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
162 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
163 pub struct StructId(salsa::InternId);
164 type StructLoc = ItemLoc<Struct>;
165 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
167 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
168 pub struct UnionId(salsa::InternId);
169 pub type UnionLoc = ItemLoc<Union>;
170 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
172 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
173 pub struct EnumId(salsa::InternId);
174 pub type EnumLoc = ItemLoc<Enum>;
175 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
177 // FIXME: rename to `VariantId`, only enums can ave variants
178 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
179 pub struct EnumVariantId {
181 pub local_id: LocalEnumVariantId,
184 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
186 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188 pub parent: VariantId,
189 pub local_id: LocalFieldId,
192 pub type LocalFieldId = Idx<adt::FieldData>;
194 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
195 pub struct ConstId(salsa::InternId);
196 type ConstLoc = AssocItemLoc<Const>;
197 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
199 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
200 pub struct StaticId(salsa::InternId);
201 pub type StaticLoc = ItemLoc<Static>;
202 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
204 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
205 pub struct TraitId(salsa::InternId);
206 pub type TraitLoc = ItemLoc<Trait>;
207 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
209 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210 pub struct TypeAliasId(salsa::InternId);
211 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
212 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
214 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
215 pub struct ImplId(salsa::InternId);
216 type ImplLoc = ItemLoc<Impl>;
217 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
219 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
220 pub struct TypeParamId {
221 pub parent: GenericDefId,
222 pub local_id: LocalTypeParamId,
225 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
227 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228 pub struct LifetimeParamId {
229 pub parent: GenericDefId,
230 pub local_id: LocalLifetimeParamId,
232 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
234 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
235 pub struct ConstParamId {
236 pub parent: GenericDefId,
237 pub local_id: LocalConstParamId,
239 pub type LocalConstParamId = Idx<generics::ConstParamData>;
241 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
242 pub enum ContainerId {
244 DefWithBodyId(DefWithBodyId),
247 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
248 pub enum AssocContainerId {
249 ContainerId(ContainerId),
253 impl_from!(ContainerId for AssocContainerId);
256 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
262 impl_from!(StructId, UnionId, EnumId for AdtId);
264 /// The defs which can be visible in the module.
265 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
266 pub enum ModuleDefId {
268 FunctionId(FunctionId),
270 // Can't be directly declared, but can be imported.
271 EnumVariantId(EnumVariantId),
275 TypeAliasId(TypeAliasId),
276 BuiltinType(BuiltinType),
281 AdtId(StructId, EnumId, UnionId),
291 /// The defs which have a body.
292 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
293 pub enum DefWithBodyId {
294 FunctionId(FunctionId),
299 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
301 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
302 pub enum AssocItemId {
303 FunctionId(FunctionId),
305 TypeAliasId(TypeAliasId),
307 // FIXME: not every function, ... is actually an assoc item. maybe we should make
308 // sure that you can only turn actual assoc items into AssocItemIds. This would
309 // require not implementing From, and instead having some checked way of
310 // casting them, and somehow making the constructors private, which would be annoying.
311 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
313 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
314 pub enum GenericDefId {
315 FunctionId(FunctionId),
318 TypeAliasId(TypeAliasId),
320 // enum variants cannot have generics themselves, but their parent enums
321 // can, and this makes some code easier to write
322 EnumVariantId(EnumVariantId),
323 // consts can have type parameters from their parents (i.e. associated consts of traits)
328 AdtId(StructId, EnumId, UnionId),
337 impl From<AssocItemId> for GenericDefId {
338 fn from(item: AssocItemId) -> Self {
340 AssocItemId::FunctionId(f) => f.into(),
341 AssocItemId::ConstId(c) => c.into(),
342 AssocItemId::TypeAliasId(t) => t.into(),
347 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
352 FunctionId(FunctionId),
353 EnumVariantId(EnumVariantId),
357 TypeAliasId(TypeAliasId),
358 MacroDefId(MacroDefId),
365 AdtId(StructId, EnumId, UnionId),
377 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
379 EnumVariantId(EnumVariantId),
383 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
387 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
392 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
395 pub trait HasModule {
396 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
399 impl HasModule for ContainerId {
400 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
402 ContainerId::ModuleId(it) => it,
403 ContainerId::DefWithBodyId(it) => it.module(db),
408 impl HasModule for AssocContainerId {
409 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
411 AssocContainerId::ContainerId(it) => it.module(db),
412 AssocContainerId::ImplId(it) => it.lookup(db).container.module(db),
413 AssocContainerId::TraitId(it) => it.lookup(db).container.module(db),
418 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
419 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
420 self.container.module(db)
424 impl HasModule for AdtId {
425 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
427 AdtId::StructId(it) => it.lookup(db).container,
428 AdtId::UnionId(it) => it.lookup(db).container,
429 AdtId::EnumId(it) => it.lookup(db).container,
435 impl HasModule for VariantId {
436 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
438 VariantId::EnumVariantId(it) => it.parent.lookup(db).container.module(db),
439 VariantId::StructId(it) => it.lookup(db).container.module(db),
440 VariantId::UnionId(it) => it.lookup(db).container.module(db),
445 impl HasModule for DefWithBodyId {
446 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
448 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
449 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
450 DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
456 pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
458 DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
459 DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
460 DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
465 impl HasModule for GenericDefId {
466 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
468 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
469 GenericDefId::AdtId(it) => it.module(db),
470 GenericDefId::TraitId(it) => it.lookup(db).container.module(db),
471 GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
472 GenericDefId::ImplId(it) => it.lookup(db).container.module(db),
473 GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container.module(db),
474 GenericDefId::ConstId(it) => it.lookup(db).module(db),
479 impl HasModule for StaticLoc {
480 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
481 self.container.module(db)
486 pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
488 AttrDefId::ModuleId(it) => it.krate,
489 AttrDefId::FieldId(it) => it.parent.module(db).krate,
490 AttrDefId::AdtId(it) => it.module(db).krate,
491 AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
492 AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.module(db).krate,
493 AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
494 AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
495 AttrDefId::TraitId(it) => it.lookup(db).container.module(db).krate,
496 AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
497 AttrDefId::ImplId(it) => it.lookup(db).container.module(db).krate,
498 // FIXME: `MacroDefId` should store the defining module, then this can implement
500 AttrDefId::MacroDefId(it) => it.krate,
505 /// A helper trait for converting to MacroCallId
506 pub trait AsMacroCall {
509 db: &dyn db::DefDatabase,
511 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
512 ) -> Option<MacroCallId> {
513 self.as_call_id_with_errors(db, krate, resolver, &mut |_| ())
516 fn as_call_id_with_errors(
518 db: &dyn db::DefDatabase,
520 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
521 error_sink: &mut dyn FnMut(mbe::ExpandError),
522 ) -> Option<MacroCallId>;
525 impl AsMacroCall for InFile<&ast::MacroCall> {
526 fn as_call_id_with_errors(
528 db: &dyn db::DefDatabase,
530 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
531 error_sink: &mut dyn FnMut(mbe::ExpandError),
532 ) -> Option<MacroCallId> {
533 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
534 let h = Hygiene::new(db.upcast(), self.file_id);
535 let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
538 error_sink(mbe::ExpandError::Other("malformed macro invocation".into()));
541 AstIdWithPath::new(ast_id.file_id, ast_id.value, path?)
542 .as_call_id_with_errors(db, krate, resolver, error_sink)
546 /// Helper wrapper for `AstId` with `ModPath`
547 #[derive(Clone, Debug, Eq, PartialEq)]
548 struct AstIdWithPath<T: ast::AstNode> {
553 impl<T: ast::AstNode> AstIdWithPath<T> {
554 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
555 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
559 impl AsMacroCall for AstIdWithPath<ast::MacroCall> {
560 fn as_call_id_with_errors(
562 db: &dyn db::DefDatabase,
564 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
565 error_sink: &mut dyn FnMut(mbe::ExpandError),
566 ) -> Option<MacroCallId> {
567 let def: MacroDefId = resolver(self.path.clone()).or_else(|| {
568 error_sink(mbe::ExpandError::Other(format!("could not resolve macro `{}`", self.path)));
572 if let MacroDefKind::BuiltInEager(_) = def.kind {
573 let macro_call = InFile::new(self.ast_id.file_id, self.ast_id.to_node(db.upcast()));
574 let hygiene = Hygiene::new(db.upcast(), self.ast_id.file_id);
582 &|path: ast::Path| resolver(path::ModPath::from_src(path, &hygiene)?),
589 Some(def.as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike(self.ast_id)).into())
594 impl AsMacroCall for AstIdWithPath<ast::Item> {
595 fn as_call_id_with_errors(
597 db: &dyn db::DefDatabase,
599 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
600 error_sink: &mut dyn FnMut(mbe::ExpandError),
601 ) -> Option<MacroCallId> {
602 let def: MacroDefId = resolver(self.path.clone()).or_else(|| {
603 error_sink(mbe::ExpandError::Other(format!("could not resolve macro `{}`", self.path)));
611 MacroCallKind::Attr(self.ast_id, self.path.segments.last()?.to_string()),