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)*) };
45 pub mod child_by_source;
60 use base_db::{impl_intern_key, salsa, CrateId};
62 ast_id_map::FileAstId,
63 eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
65 AstId, AttrId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
71 use crate::builtin_type::BuiltinType;
73 Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
78 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
81 /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
82 /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
83 /// `DefMap` of `krate`.
84 block: Option<BlockId>,
85 /// The module's ID in its originating `DefMap`.
86 pub local_id: LocalModuleId,
90 pub fn def_map(&self, db: &dyn db::DefDatabase) -> Arc<DefMap> {
93 db.block_def_map(block).unwrap_or_else(|| {
94 // NOTE: This should be unreachable - all `ModuleId`s come from their `DefMap`s,
95 // so the `DefMap` here must exist.
96 unreachable!("no `block_def_map` for `ModuleId` {:?}", self);
99 None => db.crate_def_map(self.krate),
103 pub fn krate(&self) -> CrateId {
107 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
108 self.def_map(db).containing_module(self.local_id)
112 /// An ID of a module, **local** to a specific crate
113 pub type LocalModuleId = Idx<nameres::ModuleData>;
116 pub struct ItemLoc<N: ItemTreeNode> {
117 pub container: ModuleId,
118 pub id: ItemTreeId<N>,
121 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
122 fn clone(&self) -> Self {
123 Self { container: self.container, id: self.id }
127 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
129 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
130 fn eq(&self, other: &Self) -> bool {
131 self.container == other.container && self.id == other.id
135 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
137 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
138 fn hash<H: Hasher>(&self, state: &mut H) {
139 self.container.hash(state);
145 pub struct AssocItemLoc<N: ItemTreeNode> {
146 pub container: AssocContainerId,
147 pub id: ItemTreeId<N>,
150 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
151 fn clone(&self) -> Self {
152 Self { container: self.container, id: self.id }
156 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
158 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
159 fn eq(&self, other: &Self) -> bool {
160 self.container == other.container && self.id == other.id
164 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
166 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
167 fn hash<H: Hasher>(&self, state: &mut H) {
168 self.container.hash(state);
173 macro_rules! impl_intern {
174 ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
175 impl_intern_key!($id);
177 impl Intern for $loc {
179 fn intern(self, db: &dyn db::DefDatabase) -> $id {
184 impl Lookup for $id {
186 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
193 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
194 pub struct FunctionId(salsa::InternId);
195 type FunctionLoc = AssocItemLoc<Function>;
196 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
198 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
199 pub struct StructId(salsa::InternId);
200 type StructLoc = ItemLoc<Struct>;
201 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
203 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
204 pub struct UnionId(salsa::InternId);
205 pub type UnionLoc = ItemLoc<Union>;
206 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
208 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
209 pub struct EnumId(salsa::InternId);
210 pub type EnumLoc = ItemLoc<Enum>;
211 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
213 // FIXME: rename to `VariantId`, only enums can ave variants
214 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
215 pub struct EnumVariantId {
217 pub local_id: LocalEnumVariantId,
220 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
222 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
224 pub parent: VariantId,
225 pub local_id: LocalFieldId,
228 pub type LocalFieldId = Idx<adt::FieldData>;
230 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231 pub struct ConstId(salsa::InternId);
232 type ConstLoc = AssocItemLoc<Const>;
233 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
235 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
236 pub struct StaticId(salsa::InternId);
237 pub type StaticLoc = ItemLoc<Static>;
238 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
240 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
241 pub struct TraitId(salsa::InternId);
242 pub type TraitLoc = ItemLoc<Trait>;
243 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
245 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
246 pub struct TypeAliasId(salsa::InternId);
247 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
248 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
250 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
251 pub struct ImplId(salsa::InternId);
252 type ImplLoc = ItemLoc<Impl>;
253 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
255 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
256 pub struct BlockId(salsa::InternId);
257 #[derive(Debug, Hash, PartialEq, Eq, Clone)]
258 pub struct BlockLoc {
259 ast_id: AstId<ast::BlockExpr>,
260 /// The containing module.
263 impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
265 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
266 pub struct TypeParamId {
267 pub parent: GenericDefId,
268 pub local_id: LocalTypeParamId,
271 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
273 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
274 pub struct LifetimeParamId {
275 pub parent: GenericDefId,
276 pub local_id: LocalLifetimeParamId,
278 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
280 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
281 pub struct ConstParamId {
282 pub parent: GenericDefId,
283 pub local_id: LocalConstParamId,
285 pub type LocalConstParamId = Idx<generics::ConstParamData>;
287 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
288 pub enum AssocContainerId {
293 impl_from!(ModuleId for AssocContainerId);
296 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
302 impl_from!(StructId, UnionId, EnumId for AdtId);
305 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
306 pub enum GenericParamId {
307 TypeParamId(TypeParamId),
308 LifetimeParamId(LifetimeParamId),
309 ConstParamId(ConstParamId),
311 impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
313 /// The defs which can be visible in the module.
314 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
315 pub enum ModuleDefId {
317 FunctionId(FunctionId),
319 // Can't be directly declared, but can be imported.
320 EnumVariantId(EnumVariantId),
324 TypeAliasId(TypeAliasId),
325 BuiltinType(BuiltinType),
330 AdtId(StructId, EnumId, UnionId),
340 /// The defs which have a body.
341 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
342 pub enum DefWithBodyId {
343 FunctionId(FunctionId),
348 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
351 pub fn as_generic_def_id(self) -> Option<GenericDefId> {
353 DefWithBodyId::FunctionId(f) => Some(f.into()),
354 DefWithBodyId::StaticId(_) => None,
355 DefWithBodyId::ConstId(c) => Some(c.into()),
360 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
361 pub enum AssocItemId {
362 FunctionId(FunctionId),
364 TypeAliasId(TypeAliasId),
366 // FIXME: not every function, ... is actually an assoc item. maybe we should make
367 // sure that you can only turn actual assoc items into AssocItemIds. This would
368 // require not implementing From, and instead having some checked way of
369 // casting them, and somehow making the constructors private, which would be annoying.
370 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
372 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
373 pub enum GenericDefId {
374 FunctionId(FunctionId),
377 TypeAliasId(TypeAliasId),
379 // enum variants cannot have generics themselves, but their parent enums
380 // can, and this makes some code easier to write
381 EnumVariantId(EnumVariantId),
382 // consts can have type parameters from their parents (i.e. associated consts of traits)
387 AdtId(StructId, EnumId, UnionId),
396 impl From<AssocItemId> for GenericDefId {
397 fn from(item: AssocItemId) -> Self {
399 AssocItemId::FunctionId(f) => f.into(),
400 AssocItemId::ConstId(c) => c.into(),
401 AssocItemId::TypeAliasId(t) => t.into(),
406 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
411 FunctionId(FunctionId),
412 EnumVariantId(EnumVariantId),
416 TypeAliasId(TypeAliasId),
417 MacroDefId(MacroDefId),
419 GenericParamId(GenericParamId),
425 AdtId(StructId, EnumId, UnionId),
438 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
440 EnumVariantId(EnumVariantId),
444 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
447 pub fn variant_data(self, db: &dyn db::DefDatabase) -> Arc<VariantData> {
449 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
450 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
451 VariantId::EnumVariantId(it) => {
452 db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
457 pub fn file_id(self, db: &dyn db::DefDatabase) -> HirFileId {
459 VariantId::EnumVariantId(it) => it.parent.lookup(db).id.file_id(),
460 VariantId::StructId(it) => it.lookup(db).id.file_id(),
461 VariantId::UnionId(it) => it.lookup(db).id.file_id(),
468 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
473 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
476 pub trait HasModule {
477 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
480 impl HasModule for AssocContainerId {
481 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
483 AssocContainerId::ModuleId(it) => it,
484 AssocContainerId::ImplId(it) => it.lookup(db).container,
485 AssocContainerId::TraitId(it) => it.lookup(db).container,
490 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
491 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
492 self.container.module(db)
496 impl HasModule for AdtId {
497 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
499 AdtId::StructId(it) => it.lookup(db).container,
500 AdtId::UnionId(it) => it.lookup(db).container,
501 AdtId::EnumId(it) => it.lookup(db).container,
506 impl HasModule for VariantId {
507 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
509 VariantId::EnumVariantId(it) => it.parent.lookup(db).container,
510 VariantId::StructId(it) => it.lookup(db).container,
511 VariantId::UnionId(it) => it.lookup(db).container,
516 impl HasModule for DefWithBodyId {
517 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
519 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
520 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
521 DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
527 pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
529 DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
530 DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
531 DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
536 impl HasModule for GenericDefId {
537 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
539 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
540 GenericDefId::AdtId(it) => it.module(db),
541 GenericDefId::TraitId(it) => it.lookup(db).container,
542 GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
543 GenericDefId::ImplId(it) => it.lookup(db).container,
544 GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container,
545 GenericDefId::ConstId(it) => it.lookup(db).module(db),
550 impl HasModule for StaticLoc {
551 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
557 /// Returns the module containing `self` (or `self`, if `self` is itself a module).
559 /// Returns `None` if `self` refers to a primitive type.
560 pub fn module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
562 ModuleDefId::ModuleId(id) => *id,
563 ModuleDefId::FunctionId(id) => id.lookup(db).module(db),
564 ModuleDefId::AdtId(id) => id.module(db),
565 ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container,
566 ModuleDefId::ConstId(id) => id.lookup(db).container.module(db),
567 ModuleDefId::StaticId(id) => id.lookup(db).container,
568 ModuleDefId::TraitId(id) => id.lookup(db).container,
569 ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db),
570 ModuleDefId::BuiltinType(_) => return None,
576 pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
578 AttrDefId::ModuleId(it) => it.krate,
579 AttrDefId::FieldId(it) => it.parent.module(db).krate,
580 AttrDefId::AdtId(it) => it.module(db).krate,
581 AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
582 AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.krate,
583 AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
584 AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
585 AttrDefId::TraitId(it) => it.lookup(db).container.krate,
586 AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
587 AttrDefId::ImplId(it) => it.lookup(db).container.krate,
588 AttrDefId::GenericParamId(it) => {
590 GenericParamId::TypeParamId(it) => it.parent,
591 GenericParamId::LifetimeParamId(it) => it.parent,
592 GenericParamId::ConstParamId(it) => it.parent,
597 // FIXME: `MacroDefId` should store the defining module, then this can implement
599 AttrDefId::MacroDefId(it) => it.krate,
604 /// A helper trait for converting to MacroCallId
605 pub trait AsMacroCall {
608 db: &dyn db::DefDatabase,
610 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
611 ) -> Option<MacroCallId> {
612 self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
615 fn as_call_id_with_errors(
617 db: &dyn db::DefDatabase,
619 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
620 error_sink: &mut dyn FnMut(mbe::ExpandError),
621 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
624 impl AsMacroCall for InFile<&ast::MacroCall> {
625 fn as_call_id_with_errors(
627 db: &dyn db::DefDatabase,
629 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
630 mut error_sink: &mut dyn FnMut(mbe::ExpandError),
631 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
632 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
633 let h = Hygiene::new(db.upcast(), self.file_id);
634 let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
636 let path = match error_sink
637 .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
641 return Ok(Err(error));
645 macro_call_as_call_id(
646 &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
655 /// Helper wrapper for `AstId` with `ModPath`
656 #[derive(Clone, Debug, Eq, PartialEq)]
657 struct AstIdWithPath<T: ast::AstNode> {
662 impl<T: ast::AstNode> AstIdWithPath<T> {
663 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
664 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
668 pub struct UnresolvedMacro;
670 fn macro_call_as_call_id(
671 call: &AstIdWithPath<ast::MacroCall>,
672 db: &dyn db::DefDatabase,
674 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
675 error_sink: &mut dyn FnMut(mbe::ExpandError),
676 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
677 let def: MacroDefId = resolver(call.path.clone()).ok_or(UnresolvedMacro)?;
679 let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
680 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
681 let hygiene = Hygiene::new(db.upcast(), call.ast_id.file_id);
688 &|path: ast::Path| resolver(path::ModPath::from_src(path, &hygiene)?),
691 .map(MacroCallId::from)
694 .as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike { ast_id: call.ast_id })
700 fn derive_macro_as_call_id(
701 item_attr: &AstIdWithPath<ast::Item>,
703 db: &dyn db::DefDatabase,
705 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
706 ) -> Result<MacroCallId, UnresolvedMacro> {
707 let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?;
708 let last_segment = item_attr.path.segments().last().ok_or(UnresolvedMacro)?;
713 MacroCallKind::Derive {
714 ast_id: item_attr.ast_id,
715 derive_name: last_segment.to_string(),