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,
72 use crate::builtin_type::BuiltinType;
74 Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
79 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82 /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
83 /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
84 /// `DefMap` of `krate`.
85 block: Option<BlockId>,
86 /// The module's ID in its originating `DefMap`.
87 pub local_id: LocalModuleId,
91 pub fn def_map(&self, db: &dyn db::DefDatabase) -> Arc<DefMap> {
94 db.block_def_map(block).unwrap_or_else(|| {
95 // NOTE: This should be unreachable - all `ModuleId`s come from their `DefMap`s,
96 // so the `DefMap` here must exist.
97 unreachable!("no `block_def_map` for `ModuleId` {:?}", self);
100 None => db.crate_def_map(self.krate),
104 pub fn krate(&self) -> CrateId {
108 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
109 self.def_map(db).containing_module(self.local_id)
112 /// Returns `true` if this module represents a block expression.
114 /// Returns `false` if this module is a submodule *inside* a block expression
115 /// (eg. `m` in `{ mod m {} }`).
116 pub fn is_block_root(&self, db: &dyn db::DefDatabase) -> bool {
117 if self.block.is_none() {
121 self.def_map(db)[self.local_id].parent.is_none()
125 /// An ID of a module, **local** to a specific crate
126 pub type LocalModuleId = Idx<nameres::ModuleData>;
129 pub struct ItemLoc<N: ItemTreeNode> {
130 pub container: ModuleId,
131 pub id: ItemTreeId<N>,
134 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
135 fn clone(&self) -> Self {
136 Self { container: self.container, id: self.id }
140 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
142 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
143 fn eq(&self, other: &Self) -> bool {
144 self.container == other.container && self.id == other.id
148 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
150 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
151 fn hash<H: Hasher>(&self, state: &mut H) {
152 self.container.hash(state);
158 pub struct AssocItemLoc<N: ItemTreeNode> {
159 pub container: AssocContainerId,
160 pub id: ItemTreeId<N>,
163 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
164 fn clone(&self) -> Self {
165 Self { container: self.container, id: self.id }
169 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
171 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
172 fn eq(&self, other: &Self) -> bool {
173 self.container == other.container && self.id == other.id
177 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
179 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
180 fn hash<H: Hasher>(&self, state: &mut H) {
181 self.container.hash(state);
186 macro_rules! impl_intern {
187 ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
188 impl_intern_key!($id);
190 impl Intern for $loc {
192 fn intern(self, db: &dyn db::DefDatabase) -> $id {
197 impl Lookup for $id {
199 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
206 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
207 pub struct FunctionId(salsa::InternId);
208 type FunctionLoc = AssocItemLoc<Function>;
209 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
211 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
212 pub struct StructId(salsa::InternId);
213 type StructLoc = ItemLoc<Struct>;
214 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
216 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
217 pub struct UnionId(salsa::InternId);
218 pub type UnionLoc = ItemLoc<Union>;
219 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
221 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
222 pub struct EnumId(salsa::InternId);
223 pub type EnumLoc = ItemLoc<Enum>;
224 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
226 // FIXME: rename to `VariantId`, only enums can ave variants
227 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
228 pub struct EnumVariantId {
230 pub local_id: LocalEnumVariantId,
233 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
235 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
237 pub parent: VariantId,
238 pub local_id: LocalFieldId,
241 pub type LocalFieldId = Idx<adt::FieldData>;
243 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
244 pub struct ConstId(salsa::InternId);
245 type ConstLoc = AssocItemLoc<Const>;
246 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
248 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
249 pub struct StaticId(salsa::InternId);
250 pub type StaticLoc = ItemLoc<Static>;
251 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
253 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
254 pub struct TraitId(salsa::InternId);
255 pub type TraitLoc = ItemLoc<Trait>;
256 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
258 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
259 pub struct TypeAliasId(salsa::InternId);
260 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
261 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
263 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
264 pub struct ImplId(salsa::InternId);
265 type ImplLoc = ItemLoc<Impl>;
266 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
268 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
269 pub struct BlockId(salsa::InternId);
270 #[derive(Debug, Hash, PartialEq, Eq, Clone)]
271 pub struct BlockLoc {
272 ast_id: AstId<ast::BlockExpr>,
273 /// The containing module.
276 impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
278 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
279 pub struct TypeParamId {
280 pub parent: GenericDefId,
281 pub local_id: LocalTypeParamId,
284 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
286 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
287 pub struct LifetimeParamId {
288 pub parent: GenericDefId,
289 pub local_id: LocalLifetimeParamId,
291 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
293 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
294 pub struct ConstParamId {
295 pub parent: GenericDefId,
296 pub local_id: LocalConstParamId,
298 pub type LocalConstParamId = Idx<generics::ConstParamData>;
300 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
301 pub enum AssocContainerId {
306 impl_from!(ModuleId for AssocContainerId);
309 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
315 impl_from!(StructId, UnionId, EnumId for AdtId);
318 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
319 pub enum GenericParamId {
320 TypeParamId(TypeParamId),
321 LifetimeParamId(LifetimeParamId),
322 ConstParamId(ConstParamId),
324 impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
326 /// The defs which can be visible in the module.
327 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
328 pub enum ModuleDefId {
330 FunctionId(FunctionId),
332 // Can't be directly declared, but can be imported.
333 EnumVariantId(EnumVariantId),
337 TypeAliasId(TypeAliasId),
338 BuiltinType(BuiltinType),
343 AdtId(StructId, EnumId, UnionId),
353 /// The defs which have a body.
354 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
355 pub enum DefWithBodyId {
356 FunctionId(FunctionId),
361 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
364 pub fn as_generic_def_id(self) -> Option<GenericDefId> {
366 DefWithBodyId::FunctionId(f) => Some(f.into()),
367 DefWithBodyId::StaticId(_) => None,
368 DefWithBodyId::ConstId(c) => Some(c.into()),
373 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
374 pub enum AssocItemId {
375 FunctionId(FunctionId),
377 TypeAliasId(TypeAliasId),
379 // FIXME: not every function, ... is actually an assoc item. maybe we should make
380 // sure that you can only turn actual assoc items into AssocItemIds. This would
381 // require not implementing From, and instead having some checked way of
382 // casting them, and somehow making the constructors private, which would be annoying.
383 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
385 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
386 pub enum GenericDefId {
387 FunctionId(FunctionId),
390 TypeAliasId(TypeAliasId),
392 // enum variants cannot have generics themselves, but their parent enums
393 // can, and this makes some code easier to write
394 EnumVariantId(EnumVariantId),
395 // consts can have type parameters from their parents (i.e. associated consts of traits)
400 AdtId(StructId, EnumId, UnionId),
409 impl From<AssocItemId> for GenericDefId {
410 fn from(item: AssocItemId) -> Self {
412 AssocItemId::FunctionId(f) => f.into(),
413 AssocItemId::ConstId(c) => c.into(),
414 AssocItemId::TypeAliasId(t) => t.into(),
419 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
424 FunctionId(FunctionId),
425 EnumVariantId(EnumVariantId),
429 TypeAliasId(TypeAliasId),
430 MacroDefId(MacroDefId),
432 GenericParamId(GenericParamId),
438 AdtId(StructId, EnumId, UnionId),
451 impl From<AssocContainerId> for AttrDefId {
452 fn from(acid: AssocContainerId) -> Self {
454 AssocContainerId::ModuleId(mid) => AttrDefId::ModuleId(mid),
455 AssocContainerId::ImplId(iid) => AttrDefId::ImplId(iid),
456 AssocContainerId::TraitId(tid) => AttrDefId::TraitId(tid),
461 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
463 EnumVariantId(EnumVariantId),
467 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
470 pub fn variant_data(self, db: &dyn db::DefDatabase) -> Arc<VariantData> {
472 VariantId::StructId(it) => db.struct_data(it).variant_data.clone(),
473 VariantId::UnionId(it) => db.union_data(it).variant_data.clone(),
474 VariantId::EnumVariantId(it) => {
475 db.enum_data(it.parent).variants[it.local_id].variant_data.clone()
480 pub fn file_id(self, db: &dyn db::DefDatabase) -> HirFileId {
482 VariantId::EnumVariantId(it) => it.parent.lookup(db).id.file_id(),
483 VariantId::StructId(it) => it.lookup(db).id.file_id(),
484 VariantId::UnionId(it) => it.lookup(db).id.file_id(),
491 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
496 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
499 pub trait HasModule {
500 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
503 impl HasModule for AssocContainerId {
504 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
506 AssocContainerId::ModuleId(it) => it,
507 AssocContainerId::ImplId(it) => it.lookup(db).container,
508 AssocContainerId::TraitId(it) => it.lookup(db).container,
513 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
514 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
515 self.container.module(db)
519 impl HasModule for AdtId {
520 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
522 AdtId::StructId(it) => it.lookup(db).container,
523 AdtId::UnionId(it) => it.lookup(db).container,
524 AdtId::EnumId(it) => it.lookup(db).container,
529 impl HasModule for VariantId {
530 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
532 VariantId::EnumVariantId(it) => it.parent.lookup(db).container,
533 VariantId::StructId(it) => it.lookup(db).container,
534 VariantId::UnionId(it) => it.lookup(db).container,
539 impl HasModule for DefWithBodyId {
540 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
542 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
543 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
544 DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
550 pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
552 DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
553 DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
554 DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
559 impl HasModule for GenericDefId {
560 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
562 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
563 GenericDefId::AdtId(it) => it.module(db),
564 GenericDefId::TraitId(it) => it.lookup(db).container,
565 GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
566 GenericDefId::ImplId(it) => it.lookup(db).container,
567 GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container,
568 GenericDefId::ConstId(it) => it.lookup(db).module(db),
573 impl HasModule for StaticLoc {
574 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
580 /// Returns the module containing `self` (or `self`, if `self` is itself a module).
582 /// Returns `None` if `self` refers to a primitive type.
583 pub fn module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
585 ModuleDefId::ModuleId(id) => *id,
586 ModuleDefId::FunctionId(id) => id.lookup(db).module(db),
587 ModuleDefId::AdtId(id) => id.module(db),
588 ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container,
589 ModuleDefId::ConstId(id) => id.lookup(db).container.module(db),
590 ModuleDefId::StaticId(id) => id.lookup(db).container,
591 ModuleDefId::TraitId(id) => id.lookup(db).container,
592 ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db),
593 ModuleDefId::BuiltinType(_) => return None,
599 pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
601 AttrDefId::ModuleId(it) => it.krate,
602 AttrDefId::FieldId(it) => it.parent.module(db).krate,
603 AttrDefId::AdtId(it) => it.module(db).krate,
604 AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
605 AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.krate,
606 AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
607 AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
608 AttrDefId::TraitId(it) => it.lookup(db).container.krate,
609 AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
610 AttrDefId::ImplId(it) => it.lookup(db).container.krate,
611 AttrDefId::GenericParamId(it) => {
613 GenericParamId::TypeParamId(it) => it.parent,
614 GenericParamId::LifetimeParamId(it) => it.parent,
615 GenericParamId::ConstParamId(it) => it.parent,
620 // FIXME: `MacroDefId` should store the defining module, then this can implement
622 AttrDefId::MacroDefId(it) => it.krate,
627 /// A helper trait for converting to MacroCallId
628 pub trait AsMacroCall {
631 db: &dyn db::DefDatabase,
633 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
634 ) -> Option<MacroCallId> {
635 self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
638 fn as_call_id_with_errors(
640 db: &dyn db::DefDatabase,
642 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
643 error_sink: &mut dyn FnMut(mbe::ExpandError),
644 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
647 impl AsMacroCall for InFile<&ast::MacroCall> {
648 fn as_call_id_with_errors(
650 db: &dyn db::DefDatabase,
652 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
653 mut error_sink: &mut dyn FnMut(mbe::ExpandError),
654 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
655 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
656 let h = Hygiene::new(db.upcast(), self.file_id);
657 let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
659 let path = match error_sink
660 .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
664 return Ok(Err(error));
668 macro_call_as_call_id(
669 &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
678 /// Helper wrapper for `AstId` with `ModPath`
679 #[derive(Clone, Debug, Eq, PartialEq)]
680 struct AstIdWithPath<T: ast::AstNode> {
685 impl<T: ast::AstNode> AstIdWithPath<T> {
686 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
687 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
691 pub struct UnresolvedMacro {
695 fn macro_call_as_call_id(
696 call: &AstIdWithPath<ast::MacroCall>,
697 db: &dyn db::DefDatabase,
699 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
700 error_sink: &mut dyn FnMut(mbe::ExpandError),
701 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
702 let def: MacroDefId =
703 resolver(call.path.clone()).ok_or_else(|| UnresolvedMacro { path: call.path.clone() })?;
705 let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
706 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
707 let hygiene = Hygiene::new(db.upcast(), call.ast_id.file_id);
714 &|path: ast::Path| resolver(path::ModPath::from_src(path, &hygiene)?),
717 .map(MacroCallId::from)
720 .as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike { ast_id: call.ast_id })
726 fn derive_macro_as_call_id(
727 item_attr: &AstIdWithPath<ast::Item>,
729 db: &dyn db::DefDatabase,
731 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
732 ) -> Result<MacroCallId, UnresolvedMacro> {
733 let def: MacroDefId = resolver(item_attr.path.clone())
734 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
735 let last_segment = item_attr
739 .ok_or_else(|| UnresolvedMacro { path: item_attr.path.clone() })?;
744 MacroCallKind::Derive {
745 ast_id: item_attr.ast_id,
746 derive_name: last_segment.to_string(),