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;
58 use base_db::{impl_intern_key, salsa, CrateId};
60 ast_id_map::FileAstId,
61 eager::{expand_eager_macro, ErrorEmitted, ErrorSink},
63 AstId, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
69 use crate::builtin_type::BuiltinType;
71 Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
76 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
79 /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
80 /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
81 /// `DefMap` of `krate`.
82 block: Option<BlockId>,
83 /// The module's ID in its originating `DefMap`.
84 pub local_id: LocalModuleId,
88 pub fn def_map(&self, db: &dyn db::DefDatabase) -> Arc<DefMap> {
91 db.block_def_map(block).unwrap_or_else(|| {
92 // NOTE: This should be unreachable - all `ModuleId`s come from their `DefMap`s,
93 // so the `DefMap` here must exist.
94 unreachable!("no `block_def_map` for `ModuleId` {:?}", self);
97 None => db.crate_def_map(self.krate),
101 pub fn krate(&self) -> CrateId {
105 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
106 self.def_map(db).containing_module(self.local_id)
110 /// An ID of a module, **local** to a specific crate
111 pub type LocalModuleId = Idx<nameres::ModuleData>;
114 pub struct ItemLoc<N: ItemTreeNode> {
115 pub container: ModuleId,
116 pub id: ItemTreeId<N>,
119 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
120 fn clone(&self) -> Self {
121 Self { container: self.container, id: self.id }
125 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
127 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
128 fn eq(&self, other: &Self) -> bool {
129 self.container == other.container && self.id == other.id
133 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
135 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
136 fn hash<H: Hasher>(&self, state: &mut H) {
137 self.container.hash(state);
143 pub struct AssocItemLoc<N: ItemTreeNode> {
144 pub container: AssocContainerId,
145 pub id: ItemTreeId<N>,
148 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
149 fn clone(&self) -> Self {
150 Self { container: self.container, id: self.id }
154 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
156 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
157 fn eq(&self, other: &Self) -> bool {
158 self.container == other.container && self.id == other.id
162 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
164 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
165 fn hash<H: Hasher>(&self, state: &mut H) {
166 self.container.hash(state);
171 macro_rules! impl_intern {
172 ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
173 impl_intern_key!($id);
175 impl Intern for $loc {
177 fn intern(self, db: &dyn db::DefDatabase) -> $id {
182 impl Lookup for $id {
184 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
191 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
192 pub struct FunctionId(salsa::InternId);
193 type FunctionLoc = AssocItemLoc<Function>;
194 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
196 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
197 pub struct StructId(salsa::InternId);
198 type StructLoc = ItemLoc<Struct>;
199 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
201 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
202 pub struct UnionId(salsa::InternId);
203 pub type UnionLoc = ItemLoc<Union>;
204 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
206 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
207 pub struct EnumId(salsa::InternId);
208 pub type EnumLoc = ItemLoc<Enum>;
209 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
211 // FIXME: rename to `VariantId`, only enums can ave variants
212 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
213 pub struct EnumVariantId {
215 pub local_id: LocalEnumVariantId,
218 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
220 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
222 pub parent: VariantId,
223 pub local_id: LocalFieldId,
226 pub type LocalFieldId = Idx<adt::FieldData>;
228 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
229 pub struct ConstId(salsa::InternId);
230 type ConstLoc = AssocItemLoc<Const>;
231 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
233 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
234 pub struct StaticId(salsa::InternId);
235 pub type StaticLoc = ItemLoc<Static>;
236 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
238 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
239 pub struct TraitId(salsa::InternId);
240 pub type TraitLoc = ItemLoc<Trait>;
241 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
243 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
244 pub struct TypeAliasId(salsa::InternId);
245 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
246 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
248 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
249 pub struct ImplId(salsa::InternId);
250 type ImplLoc = ItemLoc<Impl>;
251 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
253 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
254 pub struct BlockId(salsa::InternId);
255 #[derive(Debug, Hash, PartialEq, Eq, Clone)]
256 pub struct BlockLoc {
257 ast_id: AstId<ast::BlockExpr>,
258 /// The containing module.
261 impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
263 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
264 pub struct TypeParamId {
265 pub parent: GenericDefId,
266 pub local_id: LocalTypeParamId,
269 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
271 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
272 pub struct LifetimeParamId {
273 pub parent: GenericDefId,
274 pub local_id: LocalLifetimeParamId,
276 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
278 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
279 pub struct ConstParamId {
280 pub parent: GenericDefId,
281 pub local_id: LocalConstParamId,
283 pub type LocalConstParamId = Idx<generics::ConstParamData>;
285 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
286 pub enum AssocContainerId {
291 impl_from!(ModuleId for AssocContainerId);
294 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
300 impl_from!(StructId, UnionId, EnumId for AdtId);
303 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
304 pub enum GenericParamId {
305 TypeParamId(TypeParamId),
306 LifetimeParamId(LifetimeParamId),
307 ConstParamId(ConstParamId),
309 impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
311 /// The defs which can be visible in the module.
312 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
313 pub enum ModuleDefId {
315 FunctionId(FunctionId),
317 // Can't be directly declared, but can be imported.
318 EnumVariantId(EnumVariantId),
322 TypeAliasId(TypeAliasId),
323 BuiltinType(BuiltinType),
328 AdtId(StructId, EnumId, UnionId),
338 /// The defs which have a body.
339 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
340 pub enum DefWithBodyId {
341 FunctionId(FunctionId),
346 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
349 pub fn as_generic_def_id(self) -> Option<GenericDefId> {
351 DefWithBodyId::FunctionId(f) => Some(f.into()),
352 DefWithBodyId::StaticId(_) => None,
353 DefWithBodyId::ConstId(c) => Some(c.into()),
358 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
359 pub enum AssocItemId {
360 FunctionId(FunctionId),
362 TypeAliasId(TypeAliasId),
364 // FIXME: not every function, ... is actually an assoc item. maybe we should make
365 // sure that you can only turn actual assoc items into AssocItemIds. This would
366 // require not implementing From, and instead having some checked way of
367 // casting them, and somehow making the constructors private, which would be annoying.
368 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
370 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
371 pub enum GenericDefId {
372 FunctionId(FunctionId),
375 TypeAliasId(TypeAliasId),
377 // enum variants cannot have generics themselves, but their parent enums
378 // can, and this makes some code easier to write
379 EnumVariantId(EnumVariantId),
380 // consts can have type parameters from their parents (i.e. associated consts of traits)
385 AdtId(StructId, EnumId, UnionId),
394 impl From<AssocItemId> for GenericDefId {
395 fn from(item: AssocItemId) -> Self {
397 AssocItemId::FunctionId(f) => f.into(),
398 AssocItemId::ConstId(c) => c.into(),
399 AssocItemId::TypeAliasId(t) => t.into(),
404 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
409 FunctionId(FunctionId),
410 EnumVariantId(EnumVariantId),
414 TypeAliasId(TypeAliasId),
415 MacroDefId(MacroDefId),
417 GenericParamId(GenericParamId),
423 AdtId(StructId, EnumId, UnionId),
436 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
438 EnumVariantId(EnumVariantId),
442 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
446 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
451 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
454 pub trait HasModule {
455 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
458 impl HasModule for AssocContainerId {
459 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
461 AssocContainerId::ModuleId(it) => it,
462 AssocContainerId::ImplId(it) => it.lookup(db).container,
463 AssocContainerId::TraitId(it) => it.lookup(db).container,
468 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
469 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
470 self.container.module(db)
474 impl HasModule for AdtId {
475 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
477 AdtId::StructId(it) => it.lookup(db).container,
478 AdtId::UnionId(it) => it.lookup(db).container,
479 AdtId::EnumId(it) => it.lookup(db).container,
484 impl HasModule for VariantId {
485 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
487 VariantId::EnumVariantId(it) => it.parent.lookup(db).container,
488 VariantId::StructId(it) => it.lookup(db).container,
489 VariantId::UnionId(it) => it.lookup(db).container,
494 impl HasModule for DefWithBodyId {
495 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
497 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
498 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
499 DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
505 pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
507 DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
508 DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
509 DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
514 impl HasModule for GenericDefId {
515 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
517 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
518 GenericDefId::AdtId(it) => it.module(db),
519 GenericDefId::TraitId(it) => it.lookup(db).container,
520 GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
521 GenericDefId::ImplId(it) => it.lookup(db).container,
522 GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container,
523 GenericDefId::ConstId(it) => it.lookup(db).module(db),
528 impl HasModule for StaticLoc {
529 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
535 /// Returns the module containing `self` (or `self`, if `self` is itself a module).
537 /// Returns `None` if `self` refers to a primitive type.
538 pub fn module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
540 ModuleDefId::ModuleId(id) => *id,
541 ModuleDefId::FunctionId(id) => id.lookup(db).module(db),
542 ModuleDefId::AdtId(id) => id.module(db),
543 ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container,
544 ModuleDefId::ConstId(id) => id.lookup(db).container.module(db),
545 ModuleDefId::StaticId(id) => id.lookup(db).container,
546 ModuleDefId::TraitId(id) => id.lookup(db).container,
547 ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db),
548 ModuleDefId::BuiltinType(_) => return None,
554 pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
556 AttrDefId::ModuleId(it) => it.krate,
557 AttrDefId::FieldId(it) => it.parent.module(db).krate,
558 AttrDefId::AdtId(it) => it.module(db).krate,
559 AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
560 AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.krate,
561 AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
562 AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
563 AttrDefId::TraitId(it) => it.lookup(db).container.krate,
564 AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
565 AttrDefId::ImplId(it) => it.lookup(db).container.krate,
566 AttrDefId::GenericParamId(it) => {
568 GenericParamId::TypeParamId(it) => it.parent,
569 GenericParamId::LifetimeParamId(it) => it.parent,
570 GenericParamId::ConstParamId(it) => it.parent,
575 // FIXME: `MacroDefId` should store the defining module, then this can implement
577 AttrDefId::MacroDefId(it) => it.krate,
582 /// A helper trait for converting to MacroCallId
583 pub trait AsMacroCall {
586 db: &dyn db::DefDatabase,
588 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
589 ) -> Option<MacroCallId> {
590 self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
593 fn as_call_id_with_errors(
595 db: &dyn db::DefDatabase,
597 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
598 error_sink: &mut dyn FnMut(mbe::ExpandError),
599 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
602 impl AsMacroCall for InFile<&ast::MacroCall> {
603 fn as_call_id_with_errors(
605 db: &dyn db::DefDatabase,
607 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
608 mut error_sink: &mut dyn FnMut(mbe::ExpandError),
609 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
610 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
611 let h = Hygiene::new(db.upcast(), self.file_id);
612 let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
614 let path = match error_sink
615 .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
619 return Ok(Err(error));
623 macro_call_as_call_id(
624 &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
633 /// Helper wrapper for `AstId` with `ModPath`
634 #[derive(Clone, Debug, Eq, PartialEq)]
635 struct AstIdWithPath<T: ast::AstNode> {
640 impl<T: ast::AstNode> AstIdWithPath<T> {
641 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
642 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
646 pub struct UnresolvedMacro;
648 fn macro_call_as_call_id(
649 call: &AstIdWithPath<ast::MacroCall>,
650 db: &dyn db::DefDatabase,
652 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
653 error_sink: &mut dyn FnMut(mbe::ExpandError),
654 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
655 let def: MacroDefId = resolver(call.path.clone()).ok_or(UnresolvedMacro)?;
657 let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
658 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
659 let hygiene = Hygiene::new(db.upcast(), call.ast_id.file_id);
666 &|path: ast::Path| resolver(path::ModPath::from_src(path, &hygiene)?),
669 .map(MacroCallId::from)
671 Ok(def.as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike(call.ast_id)).into())
676 fn derive_macro_as_call_id(
677 item_attr: &AstIdWithPath<ast::Item>,
678 db: &dyn db::DefDatabase,
680 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
681 ) -> Result<MacroCallId, UnresolvedMacro> {
682 let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?;
683 let last_segment = item_attr.path.segments().last().ok_or(UnresolvedMacro)?;
688 MacroCallKind::Derive(item_attr.ast_id, last_segment.to_string()),