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;
59 use base_db::{impl_intern_key, salsa, CrateId};
61 ast_id_map::FileAstId,
62 eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
64 AstId, FragmentKind, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
75 builtin_type::BuiltinType,
77 Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
82 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
85 /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
86 /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
87 /// `DefMap` of `krate`.
88 block: Option<BlockId>,
89 /// The module's ID in its originating `DefMap`.
90 pub local_id: LocalModuleId,
94 pub fn def_map(&self, db: &dyn db::DefDatabase) -> Arc<DefMap> {
97 db.block_def_map(block).unwrap_or_else(|| {
98 // NOTE: This should be unreachable - all `ModuleId`s come from their `DefMap`s,
99 // so the `DefMap` here must exist.
100 unreachable!("no `block_def_map` for `ModuleId` {:?}", self);
103 None => db.crate_def_map(self.krate),
107 pub fn krate(&self) -> CrateId {
111 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
112 self.def_map(db).containing_module(self.local_id)
115 /// Returns `true` if this module represents a block expression.
117 /// Returns `false` if this module is a submodule *inside* a block expression
118 /// (eg. `m` in `{ mod m {} }`).
119 pub fn is_block_root(&self, db: &dyn db::DefDatabase) -> bool {
120 if self.block.is_none() {
124 self.def_map(db)[self.local_id].parent.is_none()
128 /// An ID of a module, **local** to a specific crate
129 pub type LocalModuleId = Idx<nameres::ModuleData>;
132 pub struct ItemLoc<N: ItemTreeNode> {
133 pub container: ModuleId,
134 pub id: ItemTreeId<N>,
137 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
138 fn clone(&self) -> Self {
139 Self { container: self.container, id: self.id }
143 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
145 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
146 fn eq(&self, other: &Self) -> bool {
147 self.container == other.container && self.id == other.id
151 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
153 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
154 fn hash<H: Hasher>(&self, state: &mut H) {
155 self.container.hash(state);
161 pub struct AssocItemLoc<N: ItemTreeNode> {
162 pub container: AssocContainerId,
163 pub id: ItemTreeId<N>,
166 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
167 fn clone(&self) -> Self {
168 Self { container: self.container, id: self.id }
172 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
174 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
175 fn eq(&self, other: &Self) -> bool {
176 self.container == other.container && self.id == other.id
180 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
182 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
183 fn hash<H: Hasher>(&self, state: &mut H) {
184 self.container.hash(state);
189 macro_rules! impl_intern {
190 ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
191 impl_intern_key!($id);
193 impl Intern for $loc {
195 fn intern(self, db: &dyn db::DefDatabase) -> $id {
200 impl Lookup for $id {
202 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
209 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
210 pub struct FunctionId(salsa::InternId);
211 type FunctionLoc = AssocItemLoc<Function>;
212 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
214 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
215 pub struct StructId(salsa::InternId);
216 type StructLoc = ItemLoc<Struct>;
217 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
219 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
220 pub struct UnionId(salsa::InternId);
221 pub type UnionLoc = ItemLoc<Union>;
222 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
224 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
225 pub struct EnumId(salsa::InternId);
226 pub type EnumLoc = ItemLoc<Enum>;
227 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
229 // FIXME: rename to `VariantId`, only enums can ave variants
230 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
231 pub struct EnumVariantId {
233 pub local_id: LocalEnumVariantId,
236 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
238 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240 pub parent: VariantId,
241 pub local_id: LocalFieldId,
244 pub type LocalFieldId = Idx<adt::FieldData>;
246 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
247 pub struct ConstId(salsa::InternId);
248 type ConstLoc = AssocItemLoc<Const>;
249 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
251 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
252 pub struct StaticId(salsa::InternId);
253 pub type StaticLoc = ItemLoc<Static>;
254 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
256 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
257 pub struct TraitId(salsa::InternId);
258 pub type TraitLoc = ItemLoc<Trait>;
259 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
261 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
262 pub struct TypeAliasId(salsa::InternId);
263 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
264 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
266 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
267 pub struct ImplId(salsa::InternId);
268 type ImplLoc = ItemLoc<Impl>;
269 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
271 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
272 pub struct BlockId(salsa::InternId);
273 #[derive(Debug, Hash, PartialEq, Eq, Clone)]
274 pub struct BlockLoc {
275 ast_id: AstId<ast::BlockExpr>,
276 /// The containing module.
279 impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
281 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
282 pub struct TypeParamId {
283 pub parent: GenericDefId,
284 pub local_id: LocalTypeParamId,
287 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
289 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
290 pub struct LifetimeParamId {
291 pub parent: GenericDefId,
292 pub local_id: LocalLifetimeParamId,
294 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
296 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
297 pub struct ConstParamId {
298 pub parent: GenericDefId,
299 pub local_id: LocalConstParamId,
301 pub type LocalConstParamId = Idx<generics::ConstParamData>;
303 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
304 pub enum AssocContainerId {
309 impl_from!(ModuleId for AssocContainerId);
312 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
318 impl_from!(StructId, UnionId, EnumId for AdtId);
321 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
322 pub enum GenericParamId {
323 TypeParamId(TypeParamId),
324 LifetimeParamId(LifetimeParamId),
325 ConstParamId(ConstParamId),
327 impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
329 /// The defs which can be visible in the module.
330 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
331 pub enum ModuleDefId {
333 FunctionId(FunctionId),
335 // Can't be directly declared, but can be imported.
336 EnumVariantId(EnumVariantId),
340 TypeAliasId(TypeAliasId),
341 BuiltinType(BuiltinType),
346 AdtId(StructId, EnumId, UnionId),
356 /// The defs which have a body.
357 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
358 pub enum DefWithBodyId {
359 FunctionId(FunctionId),
364 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
367 pub fn as_generic_def_id(self) -> Option<GenericDefId> {
369 DefWithBodyId::FunctionId(f) => Some(f.into()),
370 DefWithBodyId::StaticId(_) => None,
371 DefWithBodyId::ConstId(c) => Some(c.into()),
376 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
377 pub enum AssocItemId {
378 FunctionId(FunctionId),
380 TypeAliasId(TypeAliasId),
382 // FIXME: not every function, ... is actually an assoc item. maybe we should make
383 // sure that you can only turn actual assoc items into AssocItemIds. This would
384 // require not implementing From, and instead having some checked way of
385 // casting them, and somehow making the constructors private, which would be annoying.
386 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
388 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
389 pub enum GenericDefId {
390 FunctionId(FunctionId),
393 TypeAliasId(TypeAliasId),
395 // enum variants cannot have generics themselves, but their parent enums
396 // can, and this makes some code easier to write
397 EnumVariantId(EnumVariantId),
398 // consts can have type parameters from their parents (i.e. associated consts of traits)
403 AdtId(StructId, EnumId, UnionId),
412 impl From<AssocItemId> for GenericDefId {
413 fn from(item: AssocItemId) -> Self {
415 AssocItemId::FunctionId(f) => f.into(),
416 AssocItemId::ConstId(c) => c.into(),
417 AssocItemId::TypeAliasId(t) => t.into(),
422 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
427 FunctionId(FunctionId),
428 EnumVariantId(EnumVariantId),
432 TypeAliasId(TypeAliasId),
433 MacroDefId(MacroDefId),
435 GenericParamId(GenericParamId),
441 AdtId(StructId, EnumId, UnionId),
454 impl From<AssocContainerId> for AttrDefId {
455 fn from(acid: AssocContainerId) -> Self {
457 AssocContainerId::ModuleId(mid) => AttrDefId::ModuleId(mid),
458 AssocContainerId::ImplId(iid) => AttrDefId::ImplId(iid),
459 AssocContainerId::TraitId(tid) => AttrDefId::TraitId(tid),
464 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
466 EnumVariantId(EnumVariantId),
470 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
473 pub fn variant_data(self, db: &dyn db::DefDatabase) -> Arc<VariantData> {
475 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
476 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
477 VariantId::EnumVariantId(it) => {
478 db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
483 pub fn file_id(self, db: &dyn db::DefDatabase) -> HirFileId {
485 VariantId::EnumVariantId(it) => it.parent.lookup(db).id.file_id(),
486 VariantId::StructId(it) => it.lookup(db).id.file_id(),
487 VariantId::UnionId(it) => it.lookup(db).id.file_id(),
491 pub fn adt_id(self) -> AdtId {
493 VariantId::EnumVariantId(it) => it.parent.into(),
494 VariantId::StructId(it) => it.into(),
495 VariantId::UnionId(it) => it.into(),
502 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
507 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
510 pub trait HasModule {
511 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
514 impl HasModule for AssocContainerId {
515 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
517 AssocContainerId::ModuleId(it) => it,
518 AssocContainerId::ImplId(it) => it.lookup(db).container,
519 AssocContainerId::TraitId(it) => it.lookup(db).container,
524 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
525 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
526 self.container.module(db)
530 impl HasModule for AdtId {
531 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
533 AdtId::StructId(it) => it.lookup(db).container,
534 AdtId::UnionId(it) => it.lookup(db).container,
535 AdtId::EnumId(it) => it.lookup(db).container,
540 impl HasModule for VariantId {
541 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
543 VariantId::EnumVariantId(it) => it.parent.lookup(db).container,
544 VariantId::StructId(it) => it.lookup(db).container,
545 VariantId::UnionId(it) => it.lookup(db).container,
550 impl HasModule for DefWithBodyId {
551 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
553 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
554 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
555 DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
561 pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
563 DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
564 DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
565 DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
570 impl HasModule for GenericDefId {
571 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
573 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
574 GenericDefId::AdtId(it) => it.module(db),
575 GenericDefId::TraitId(it) => it.lookup(db).container,
576 GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
577 GenericDefId::ImplId(it) => it.lookup(db).container,
578 GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container,
579 GenericDefId::ConstId(it) => it.lookup(db).module(db),
584 impl HasModule for StaticLoc {
585 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
591 /// Returns the module containing `self` (or `self`, if `self` is itself a module).
593 /// Returns `None` if `self` refers to a primitive type.
594 pub fn module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
596 ModuleDefId::ModuleId(id) => *id,
597 ModuleDefId::FunctionId(id) => id.lookup(db).module(db),
598 ModuleDefId::AdtId(id) => id.module(db),
599 ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container,
600 ModuleDefId::ConstId(id) => id.lookup(db).container.module(db),
601 ModuleDefId::StaticId(id) => id.lookup(db).container,
602 ModuleDefId::TraitId(id) => id.lookup(db).container,
603 ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db),
604 ModuleDefId::BuiltinType(_) => return None,
610 pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
612 AttrDefId::ModuleId(it) => it.krate,
613 AttrDefId::FieldId(it) => it.parent.module(db).krate,
614 AttrDefId::AdtId(it) => it.module(db).krate,
615 AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
616 AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.krate,
617 AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
618 AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
619 AttrDefId::TraitId(it) => it.lookup(db).container.krate,
620 AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
621 AttrDefId::ImplId(it) => it.lookup(db).container.krate,
622 AttrDefId::GenericParamId(it) => {
624 GenericParamId::TypeParamId(it) => it.parent,
625 GenericParamId::LifetimeParamId(it) => it.parent,
626 GenericParamId::ConstParamId(it) => it.parent,
631 // FIXME: `MacroDefId` should store the defining module, then this can implement
633 AttrDefId::MacroDefId(it) => it.krate,
638 /// A helper trait for converting to MacroCallId
639 pub trait AsMacroCall {
642 db: &dyn db::DefDatabase,
644 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
645 ) -> Option<MacroCallId> {
646 self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
649 fn as_call_id_with_errors(
651 db: &dyn db::DefDatabase,
653 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
654 error_sink: &mut dyn FnMut(mbe::ExpandError),
655 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
658 impl AsMacroCall for InFile<&ast::MacroCall> {
659 fn as_call_id_with_errors(
661 db: &dyn db::DefDatabase,
663 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
664 mut error_sink: &mut dyn FnMut(mbe::ExpandError),
665 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
666 let fragment = hir_expand::to_fragment_kind(self.value);
667 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
668 let h = Hygiene::new(db.upcast(), self.file_id);
669 let path = self.value.path().and_then(|path| path::ModPath::from_src(db, path, &h));
671 let path = match error_sink
672 .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
676 return Ok(Err(error));
680 macro_call_as_call_id(
681 &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
691 /// Helper wrapper for `AstId` with `ModPath`
692 #[derive(Clone, Debug, Eq, PartialEq)]
693 struct AstIdWithPath<T: ast::AstNode> {
698 impl<T: ast::AstNode> AstIdWithPath<T> {
699 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
700 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
705 pub struct UnresolvedMacro {
709 fn macro_call_as_call_id(
710 call: &AstIdWithPath<ast::MacroCall>,
711 fragment: FragmentKind,
712 db: &dyn db::DefDatabase,
714 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
715 error_sink: &mut dyn FnMut(mbe::ExpandError),
716 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
717 let def: MacroDefId =
718 resolver(call.path.clone()).ok_or_else(|| UnresolvedMacro { path: call.path.clone() })?;
720 let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
721 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
722 let hygiene = Hygiene::new(db.upcast(), call.ast_id.file_id);
729 &|path: ast::Path| resolver(path::ModPath::from_src(db, path, &hygiene)?),
732 .map(MacroCallId::from)
738 MacroCallKind::FnLike { ast_id: call.ast_id, fragment },
744 fn derive_macro_as_call_id(
745 item_attr: &AstIdWithPath<ast::Item>,
747 db: &dyn db::DefDatabase,
749 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
750 ) -> Result<MacroCallId, UnresolvedMacro> {
751 let def: MacroDefId = resolver(item_attr.path.clone())
752 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
753 let last_segment = item_attr
757 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
762 MacroCallKind::Derive {
763 ast_id: item_attr.ast_id,
764 derive_name: last_segment.to_string(),
765 derive_attr_index: derive_attr.ast_index,
771 fn attr_macro_as_call_id(
772 item_attr: &AstIdWithPath<ast::Item>,
774 db: &dyn db::DefDatabase,
776 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
777 ) -> Result<MacroCallId, UnresolvedMacro> {
778 let def: MacroDefId = resolver(item_attr.path.clone())
779 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
780 let last_segment = item_attr
784 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
785 let mut arg = match ¯o_attr.input {
786 Some(input) => match &**input {
787 attr::AttrInput::Literal(_) => tt::Subtree::default(),
788 attr::AttrInput::TokenTree(tt) => tt.clone(),
790 None => tt::Subtree::default(),
792 // The parentheses are always disposed here.
793 arg.delimiter = None;
799 MacroCallKind::Attr {
800 ast_id: item_attr.ast_id,
801 attr_name: last_segment.to_string(),
803 invoc_attr_index: macro_attr.id.ast_index,