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, HirFileId, InFile, MacroCallId, MacroCallKind, MacroDefId, MacroDefKind,
70 use crate::builtin_type::BuiltinType;
72 Const, Enum, Function, Impl, ItemTreeId, ItemTreeNode, ModItem, Static, Struct, Trait,
77 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
80 /// If this `ModuleId` was derived from a `DefMap` for a block expression, this stores the
81 /// `BlockId` of that block expression. If `None`, this module is part of the crate-level
82 /// `DefMap` of `krate`.
83 block: Option<BlockId>,
84 /// The module's ID in its originating `DefMap`.
85 pub local_id: LocalModuleId,
89 pub fn def_map(&self, db: &dyn db::DefDatabase) -> Arc<DefMap> {
92 db.block_def_map(block).unwrap_or_else(|| {
93 // NOTE: This should be unreachable - all `ModuleId`s come from their `DefMap`s,
94 // so the `DefMap` here must exist.
95 unreachable!("no `block_def_map` for `ModuleId` {:?}", self);
98 None => db.crate_def_map(self.krate),
102 pub fn krate(&self) -> CrateId {
106 pub fn containing_module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
107 self.def_map(db).containing_module(self.local_id)
111 /// An ID of a module, **local** to a specific crate
112 pub type LocalModuleId = Idx<nameres::ModuleData>;
115 pub struct ItemLoc<N: ItemTreeNode> {
116 pub container: ModuleId,
117 pub id: ItemTreeId<N>,
120 impl<N: ItemTreeNode> Clone for ItemLoc<N> {
121 fn clone(&self) -> Self {
122 Self { container: self.container, id: self.id }
126 impl<N: ItemTreeNode> Copy for ItemLoc<N> {}
128 impl<N: ItemTreeNode> PartialEq for ItemLoc<N> {
129 fn eq(&self, other: &Self) -> bool {
130 self.container == other.container && self.id == other.id
134 impl<N: ItemTreeNode> Eq for ItemLoc<N> {}
136 impl<N: ItemTreeNode> Hash for ItemLoc<N> {
137 fn hash<H: Hasher>(&self, state: &mut H) {
138 self.container.hash(state);
144 pub struct AssocItemLoc<N: ItemTreeNode> {
145 pub container: AssocContainerId,
146 pub id: ItemTreeId<N>,
149 impl<N: ItemTreeNode> Clone for AssocItemLoc<N> {
150 fn clone(&self) -> Self {
151 Self { container: self.container, id: self.id }
155 impl<N: ItemTreeNode> Copy for AssocItemLoc<N> {}
157 impl<N: ItemTreeNode> PartialEq for AssocItemLoc<N> {
158 fn eq(&self, other: &Self) -> bool {
159 self.container == other.container && self.id == other.id
163 impl<N: ItemTreeNode> Eq for AssocItemLoc<N> {}
165 impl<N: ItemTreeNode> Hash for AssocItemLoc<N> {
166 fn hash<H: Hasher>(&self, state: &mut H) {
167 self.container.hash(state);
172 macro_rules! impl_intern {
173 ($id:ident, $loc:ident, $intern:ident, $lookup:ident) => {
174 impl_intern_key!($id);
176 impl Intern for $loc {
178 fn intern(self, db: &dyn db::DefDatabase) -> $id {
183 impl Lookup for $id {
185 fn lookup(&self, db: &dyn db::DefDatabase) -> $loc {
192 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
193 pub struct FunctionId(salsa::InternId);
194 type FunctionLoc = AssocItemLoc<Function>;
195 impl_intern!(FunctionId, FunctionLoc, intern_function, lookup_intern_function);
197 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
198 pub struct StructId(salsa::InternId);
199 type StructLoc = ItemLoc<Struct>;
200 impl_intern!(StructId, StructLoc, intern_struct, lookup_intern_struct);
202 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
203 pub struct UnionId(salsa::InternId);
204 pub type UnionLoc = ItemLoc<Union>;
205 impl_intern!(UnionId, UnionLoc, intern_union, lookup_intern_union);
207 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
208 pub struct EnumId(salsa::InternId);
209 pub type EnumLoc = ItemLoc<Enum>;
210 impl_intern!(EnumId, EnumLoc, intern_enum, lookup_intern_enum);
212 // FIXME: rename to `VariantId`, only enums can ave variants
213 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
214 pub struct EnumVariantId {
216 pub local_id: LocalEnumVariantId,
219 pub type LocalEnumVariantId = Idx<adt::EnumVariantData>;
221 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
223 pub parent: VariantId,
224 pub local_id: LocalFieldId,
227 pub type LocalFieldId = Idx<adt::FieldData>;
229 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
230 pub struct ConstId(salsa::InternId);
231 type ConstLoc = AssocItemLoc<Const>;
232 impl_intern!(ConstId, ConstLoc, intern_const, lookup_intern_const);
234 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
235 pub struct StaticId(salsa::InternId);
236 pub type StaticLoc = ItemLoc<Static>;
237 impl_intern!(StaticId, StaticLoc, intern_static, lookup_intern_static);
239 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
240 pub struct TraitId(salsa::InternId);
241 pub type TraitLoc = ItemLoc<Trait>;
242 impl_intern!(TraitId, TraitLoc, intern_trait, lookup_intern_trait);
244 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
245 pub struct TypeAliasId(salsa::InternId);
246 type TypeAliasLoc = AssocItemLoc<TypeAlias>;
247 impl_intern!(TypeAliasId, TypeAliasLoc, intern_type_alias, lookup_intern_type_alias);
249 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
250 pub struct ImplId(salsa::InternId);
251 type ImplLoc = ItemLoc<Impl>;
252 impl_intern!(ImplId, ImplLoc, intern_impl, lookup_intern_impl);
254 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)]
255 pub struct BlockId(salsa::InternId);
256 #[derive(Debug, Hash, PartialEq, Eq, Clone)]
257 pub struct BlockLoc {
258 ast_id: AstId<ast::BlockExpr>,
259 /// The containing module.
262 impl_intern!(BlockId, BlockLoc, intern_block, lookup_intern_block);
264 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
265 pub struct TypeParamId {
266 pub parent: GenericDefId,
267 pub local_id: LocalTypeParamId,
270 pub type LocalTypeParamId = Idx<generics::TypeParamData>;
272 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
273 pub struct LifetimeParamId {
274 pub parent: GenericDefId,
275 pub local_id: LocalLifetimeParamId,
277 pub type LocalLifetimeParamId = Idx<generics::LifetimeParamData>;
279 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
280 pub struct ConstParamId {
281 pub parent: GenericDefId,
282 pub local_id: LocalConstParamId,
284 pub type LocalConstParamId = Idx<generics::ConstParamData>;
286 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
287 pub enum AssocContainerId {
292 impl_from!(ModuleId for AssocContainerId);
295 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
301 impl_from!(StructId, UnionId, EnumId for AdtId);
304 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
305 pub enum GenericParamId {
306 TypeParamId(TypeParamId),
307 LifetimeParamId(LifetimeParamId),
308 ConstParamId(ConstParamId),
310 impl_from!(TypeParamId, LifetimeParamId, ConstParamId for GenericParamId);
312 /// The defs which can be visible in the module.
313 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
314 pub enum ModuleDefId {
316 FunctionId(FunctionId),
318 // Can't be directly declared, but can be imported.
319 EnumVariantId(EnumVariantId),
323 TypeAliasId(TypeAliasId),
324 BuiltinType(BuiltinType),
329 AdtId(StructId, EnumId, UnionId),
339 /// The defs which have a body.
340 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
341 pub enum DefWithBodyId {
342 FunctionId(FunctionId),
347 impl_from!(FunctionId, ConstId, StaticId for DefWithBodyId);
350 pub fn as_generic_def_id(self) -> Option<GenericDefId> {
352 DefWithBodyId::FunctionId(f) => Some(f.into()),
353 DefWithBodyId::StaticId(_) => None,
354 DefWithBodyId::ConstId(c) => Some(c.into()),
359 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
360 pub enum AssocItemId {
361 FunctionId(FunctionId),
363 TypeAliasId(TypeAliasId),
365 // FIXME: not every function, ... is actually an assoc item. maybe we should make
366 // sure that you can only turn actual assoc items into AssocItemIds. This would
367 // require not implementing From, and instead having some checked way of
368 // casting them, and somehow making the constructors private, which would be annoying.
369 impl_from!(FunctionId, ConstId, TypeAliasId for AssocItemId);
371 #[derive(Clone, Copy, PartialEq, Eq, Debug, Hash)]
372 pub enum GenericDefId {
373 FunctionId(FunctionId),
376 TypeAliasId(TypeAliasId),
378 // enum variants cannot have generics themselves, but their parent enums
379 // can, and this makes some code easier to write
380 EnumVariantId(EnumVariantId),
381 // consts can have type parameters from their parents (i.e. associated consts of traits)
386 AdtId(StructId, EnumId, UnionId),
395 impl From<AssocItemId> for GenericDefId {
396 fn from(item: AssocItemId) -> Self {
398 AssocItemId::FunctionId(f) => f.into(),
399 AssocItemId::ConstId(c) => c.into(),
400 AssocItemId::TypeAliasId(t) => t.into(),
405 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
410 FunctionId(FunctionId),
411 EnumVariantId(EnumVariantId),
415 TypeAliasId(TypeAliasId),
416 MacroDefId(MacroDefId),
418 GenericParamId(GenericParamId),
424 AdtId(StructId, EnumId, UnionId),
437 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
439 EnumVariantId(EnumVariantId),
443 impl_from!(EnumVariantId, StructId, UnionId for VariantId);
447 fn intern(self, db: &dyn db::DefDatabase) -> Self::ID;
452 fn lookup(&self, db: &dyn db::DefDatabase) -> Self::Data;
455 pub trait HasModule {
456 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId;
459 impl HasModule for AssocContainerId {
460 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
462 AssocContainerId::ModuleId(it) => it,
463 AssocContainerId::ImplId(it) => it.lookup(db).container,
464 AssocContainerId::TraitId(it) => it.lookup(db).container,
469 impl<N: ItemTreeNode> HasModule for AssocItemLoc<N> {
470 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
471 self.container.module(db)
475 impl HasModule for AdtId {
476 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
478 AdtId::StructId(it) => it.lookup(db).container,
479 AdtId::UnionId(it) => it.lookup(db).container,
480 AdtId::EnumId(it) => it.lookup(db).container,
485 impl HasModule for VariantId {
486 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
488 VariantId::EnumVariantId(it) => it.parent.lookup(db).container,
489 VariantId::StructId(it) => it.lookup(db).container,
490 VariantId::UnionId(it) => it.lookup(db).container,
495 impl HasModule for DefWithBodyId {
496 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
498 DefWithBodyId::FunctionId(it) => it.lookup(db).module(db),
499 DefWithBodyId::StaticId(it) => it.lookup(db).module(db),
500 DefWithBodyId::ConstId(it) => it.lookup(db).module(db),
506 pub fn as_mod_item(self, db: &dyn db::DefDatabase) -> ModItem {
508 DefWithBodyId::FunctionId(it) => it.lookup(db).id.value.into(),
509 DefWithBodyId::StaticId(it) => it.lookup(db).id.value.into(),
510 DefWithBodyId::ConstId(it) => it.lookup(db).id.value.into(),
515 impl HasModule for GenericDefId {
516 fn module(&self, db: &dyn db::DefDatabase) -> ModuleId {
518 GenericDefId::FunctionId(it) => it.lookup(db).module(db),
519 GenericDefId::AdtId(it) => it.module(db),
520 GenericDefId::TraitId(it) => it.lookup(db).container,
521 GenericDefId::TypeAliasId(it) => it.lookup(db).module(db),
522 GenericDefId::ImplId(it) => it.lookup(db).container,
523 GenericDefId::EnumVariantId(it) => it.parent.lookup(db).container,
524 GenericDefId::ConstId(it) => it.lookup(db).module(db),
529 impl HasModule for StaticLoc {
530 fn module(&self, _db: &dyn db::DefDatabase) -> ModuleId {
536 /// Returns the module containing `self` (or `self`, if `self` is itself a module).
538 /// Returns `None` if `self` refers to a primitive type.
539 pub fn module(&self, db: &dyn db::DefDatabase) -> Option<ModuleId> {
541 ModuleDefId::ModuleId(id) => *id,
542 ModuleDefId::FunctionId(id) => id.lookup(db).module(db),
543 ModuleDefId::AdtId(id) => id.module(db),
544 ModuleDefId::EnumVariantId(id) => id.parent.lookup(db).container,
545 ModuleDefId::ConstId(id) => id.lookup(db).container.module(db),
546 ModuleDefId::StaticId(id) => id.lookup(db).container,
547 ModuleDefId::TraitId(id) => id.lookup(db).container,
548 ModuleDefId::TypeAliasId(id) => id.lookup(db).module(db),
549 ModuleDefId::BuiltinType(_) => return None,
555 pub fn krate(&self, db: &dyn db::DefDatabase) -> CrateId {
557 AttrDefId::ModuleId(it) => it.krate,
558 AttrDefId::FieldId(it) => it.parent.module(db).krate,
559 AttrDefId::AdtId(it) => it.module(db).krate,
560 AttrDefId::FunctionId(it) => it.lookup(db).module(db).krate,
561 AttrDefId::EnumVariantId(it) => it.parent.lookup(db).container.krate,
562 AttrDefId::StaticId(it) => it.lookup(db).module(db).krate,
563 AttrDefId::ConstId(it) => it.lookup(db).module(db).krate,
564 AttrDefId::TraitId(it) => it.lookup(db).container.krate,
565 AttrDefId::TypeAliasId(it) => it.lookup(db).module(db).krate,
566 AttrDefId::ImplId(it) => it.lookup(db).container.krate,
567 AttrDefId::GenericParamId(it) => {
569 GenericParamId::TypeParamId(it) => it.parent,
570 GenericParamId::LifetimeParamId(it) => it.parent,
571 GenericParamId::ConstParamId(it) => it.parent,
576 // FIXME: `MacroDefId` should store the defining module, then this can implement
578 AttrDefId::MacroDefId(it) => it.krate,
583 /// A helper trait for converting to MacroCallId
584 pub trait AsMacroCall {
587 db: &dyn db::DefDatabase,
589 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
590 ) -> Option<MacroCallId> {
591 self.as_call_id_with_errors(db, krate, resolver, &mut |_| ()).ok()?.ok()
594 fn as_call_id_with_errors(
596 db: &dyn db::DefDatabase,
598 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
599 error_sink: &mut dyn FnMut(mbe::ExpandError),
600 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro>;
603 impl AsMacroCall for InFile<&ast::MacroCall> {
604 fn as_call_id_with_errors(
606 db: &dyn db::DefDatabase,
608 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
609 mut error_sink: &mut dyn FnMut(mbe::ExpandError),
610 ) -> Result<Result<MacroCallId, ErrorEmitted>, UnresolvedMacro> {
611 let ast_id = AstId::new(self.file_id, db.ast_id_map(self.file_id).ast_id(self.value));
612 let h = Hygiene::new(db.upcast(), self.file_id);
613 let path = self.value.path().and_then(|path| path::ModPath::from_src(path, &h));
615 let path = match error_sink
616 .option(path, || mbe::ExpandError::Other("malformed macro invocation".into()))
620 return Ok(Err(error));
624 macro_call_as_call_id(
625 &AstIdWithPath::new(ast_id.file_id, ast_id.value, path),
634 /// Helper wrapper for `AstId` with `ModPath`
635 #[derive(Clone, Debug, Eq, PartialEq)]
636 struct AstIdWithPath<T: ast::AstNode> {
641 impl<T: ast::AstNode> AstIdWithPath<T> {
642 fn new(file_id: HirFileId, ast_id: FileAstId<T>, path: path::ModPath) -> AstIdWithPath<T> {
643 AstIdWithPath { ast_id: AstId::new(file_id, ast_id), path }
647 pub struct UnresolvedMacro;
649 fn macro_call_as_call_id(
650 call: &AstIdWithPath<ast::MacroCall>,
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> {
656 let def: MacroDefId = resolver(call.path.clone()).ok_or(UnresolvedMacro)?;
658 let res = if let MacroDefKind::BuiltInEager(..) = def.kind {
659 let macro_call = InFile::new(call.ast_id.file_id, call.ast_id.to_node(db.upcast()));
660 let hygiene = Hygiene::new(db.upcast(), call.ast_id.file_id);
667 &|path: ast::Path| resolver(path::ModPath::from_src(path, &hygiene)?),
670 .map(MacroCallId::from)
672 Ok(def.as_lazy_macro(db.upcast(), krate, MacroCallKind::FnLike(call.ast_id)).into())
677 fn derive_macro_as_call_id(
678 item_attr: &AstIdWithPath<ast::Item>,
679 db: &dyn db::DefDatabase,
681 resolver: impl Fn(path::ModPath) -> Option<MacroDefId>,
682 ) -> Result<MacroCallId, UnresolvedMacro> {
683 let def: MacroDefId = resolver(item_attr.path.clone()).ok_or(UnresolvedMacro)?;
684 let last_segment = item_attr.path.segments().last().ok_or(UnresolvedMacro)?;
689 MacroCallKind::Derive(item_attr.ast_id, last_segment.to_string()),