1 //! Name resolution façade.
9 use rustc_hash::FxHashSet;
12 body::scope::{ExprScopes, ScopeId},
13 builtin_type::BuiltinType,
15 expr::{ExprId, LabelId, PatId},
16 generics::GenericParams,
18 item_scope::{BuiltinShadowMode, BUILTIN_SCOPE},
20 path::{ModPath, PathKind},
22 visibility::{RawVisibility, Visibility},
23 AdtId, AssocContainerId, AssocItemId, ConstId, ConstParamId, DefWithBodyId, EnumId,
24 EnumVariantId, FunctionId, GenericDefId, GenericParamId, HasModule, ImplId, LifetimeParamId,
25 LocalModuleId, Lookup, ModuleDefId, ModuleId, StaticId, StructId, TraitId, TypeAliasId,
26 TypeParamId, VariantId,
29 #[derive(Debug, Clone, Default)]
31 // FIXME: all usages generally call `.rev`, so maybe reverse once in construction?
35 // FIXME how to store these best
36 #[derive(Debug, Clone)]
37 struct ModuleItemMap {
39 module_id: LocalModuleId,
42 #[derive(Debug, Clone)]
45 expr_scopes: Arc<ExprScopes>,
49 #[derive(Debug, Clone)]
51 /// All the items and imported names of a module
52 ModuleScope(ModuleItemMap),
53 /// Brings the generic parameters of an item into scope
54 GenericParams { def: GenericDefId, params: Interned<GenericParams> },
55 /// Brings `Self` in `impl` block into scope
57 /// Brings `Self` in enum, struct and union definitions into scope
63 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
66 GenericParam(TypeParamId),
69 // Yup, enum variants are added to the types ns, but any usage of variant as
71 EnumVariantId(EnumVariantId),
72 TypeAliasId(TypeAliasId),
73 BuiltinType(BuiltinType),
75 // Module belong to type ns, but the resolver is used when all module paths
76 // are fully resolved.
80 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
81 pub enum ResolveValueResult {
83 Partial(TypeNs, usize),
86 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
90 FunctionId(FunctionId),
94 EnumVariantId(EnumVariantId),
95 GenericParam(ConstParamId),
99 /// Resolve known trait from std, like `std::futures::Future`
100 pub fn resolve_known_trait(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<TraitId> {
101 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?;
103 ModuleDefId::TraitId(it) => Some(it),
108 /// Resolve known struct from std, like `std::boxed::Box`
109 pub fn resolve_known_struct(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<StructId> {
110 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?;
112 ModuleDefId::AdtId(AdtId::StructId(it)) => Some(it),
117 /// Resolve known enum from std, like `std::result::Result`
118 pub fn resolve_known_enum(&self, db: &dyn DefDatabase, path: &ModPath) -> Option<EnumId> {
119 let res = self.resolve_module_path(db, path, BuiltinShadowMode::Other).take_types()?;
121 ModuleDefId::AdtId(AdtId::EnumId(it)) => Some(it),
126 fn resolve_module_path(
128 db: &dyn DefDatabase,
130 shadow: BuiltinShadowMode,
132 let (item_map, module) = match self.module_scope() {
134 None => return PerNs::none(),
136 let (module_res, segment_index) = item_map.resolve_path(db, module, path, shadow);
137 if segment_index.is_some() {
138 return PerNs::none();
143 pub fn resolve_module_path_in_items(&self, db: &dyn DefDatabase, path: &ModPath) -> PerNs {
144 self.resolve_module_path(db, path, BuiltinShadowMode::Module)
147 pub fn resolve_module_path_in_trait_assoc_items(
149 db: &dyn DefDatabase,
152 let (item_map, module) = self.module_scope()?;
153 let (module_res, idx) = item_map.resolve_path(db, module, path, BuiltinShadowMode::Module);
154 match module_res.take_types()? {
155 ModuleDefId::TraitId(it) => {
157 let unresolved = &path.segments()[idx..];
158 let assoc = match unresolved {
162 let &(_, assoc) = db.trait_data(it).items.iter().find(|(n, _)| n == assoc)?;
164 AssocItemId::FunctionId(it) => PerNs::values(it.into(), Visibility::Public),
165 AssocItemId::ConstId(it) => PerNs::values(it.into(), Visibility::Public),
166 AssocItemId::TypeAliasId(it) => PerNs::types(it.into(), Visibility::Public),
173 pub fn resolve_path_in_type_ns(
175 db: &dyn DefDatabase,
177 ) -> Option<(TypeNs, Option<usize>)> {
178 let first_name = path.segments().first()?;
179 let skip_to_mod = path.kind != PathKind::Plain;
180 for scope in self.scopes.iter().rev() {
182 Scope::ExprScope(_) => continue,
183 Scope::GenericParams { .. } | Scope::ImplDefScope(_) if skip_to_mod => continue,
185 Scope::GenericParams { params, def } => {
186 if let Some(local_id) = params.find_type_by_name(first_name) {
187 let idx = if path.segments().len() == 1 { None } else { Some(1) };
189 TypeNs::GenericParam(TypeParamId { local_id, parent: *def }),
194 Scope::ImplDefScope(impl_) => {
195 if first_name == &name![Self] {
196 let idx = if path.segments().len() == 1 { None } else { Some(1) };
197 return Some((TypeNs::SelfType(*impl_), idx));
200 Scope::AdtScope(adt) => {
201 if first_name == &name![Self] {
202 let idx = if path.segments().len() == 1 { None } else { Some(1) };
203 return Some((TypeNs::AdtSelfType(*adt), idx));
206 Scope::ModuleScope(m) => {
207 if let Some(res) = m.resolve_path_in_type_ns(db, path) {
216 pub fn resolve_path_in_type_ns_fully(
218 db: &dyn DefDatabase,
220 ) -> Option<TypeNs> {
221 let (res, unresolved) = self.resolve_path_in_type_ns(db, path)?;
222 if unresolved.is_some() {
228 pub fn resolve_visibility(
230 db: &dyn DefDatabase,
231 visibility: &RawVisibility,
232 ) -> Option<Visibility> {
234 RawVisibility::Module(_) => {
235 let (item_map, module) = match self.module_scope() {
239 item_map.resolve_visibility(db, module, visibility)
241 RawVisibility::Public => Some(Visibility::Public),
245 pub fn resolve_path_in_value_ns(
247 db: &dyn DefDatabase,
249 ) -> Option<ResolveValueResult> {
250 let n_segments = path.segments().len();
251 let tmp = name![self];
252 let first_name = if path.is_self() { &tmp } else { path.segments().first()? };
253 let skip_to_mod = path.kind != PathKind::Plain && !path.is_self();
254 for scope in self.scopes.iter().rev() {
257 | Scope::ExprScope(_)
258 | Scope::GenericParams { .. }
259 | Scope::ImplDefScope(_)
265 Scope::ExprScope(scope) if n_segments <= 1 => {
268 .entries(scope.scope_id)
270 .find(|entry| entry.name() == first_name);
272 if let Some(e) = entry {
273 return Some(ResolveValueResult::ValueNs(ValueNs::LocalBinding(e.pat())));
276 Scope::ExprScope(_) => continue,
278 Scope::GenericParams { params, def } if n_segments > 1 => {
279 if let Some(local_id) = params.find_type_by_name(first_name) {
280 let ty = TypeNs::GenericParam(TypeParamId { local_id, parent: *def });
281 return Some(ResolveValueResult::Partial(ty, 1));
284 Scope::GenericParams { params, def } if n_segments == 1 => {
285 if let Some(local_id) = params.find_const_by_name(first_name) {
286 let val = ValueNs::GenericParam(ConstParamId { local_id, parent: *def });
287 return Some(ResolveValueResult::ValueNs(val));
290 Scope::GenericParams { .. } => continue,
292 Scope::ImplDefScope(impl_) => {
293 if first_name == &name![Self] {
295 let ty = TypeNs::SelfType(*impl_);
296 return Some(ResolveValueResult::Partial(ty, 1));
298 return Some(ResolveValueResult::ValueNs(ValueNs::ImplSelf(*impl_)));
302 Scope::AdtScope(adt) => {
304 // bare `Self` doesn't work in the value namespace in a struct/enum definition
307 if first_name == &name![Self] {
308 let ty = TypeNs::AdtSelfType(*adt);
309 return Some(ResolveValueResult::Partial(ty, 1));
313 Scope::ModuleScope(m) => {
314 if let Some(def) = m.resolve_path_in_value_ns(db, path) {
324 pub fn resolve_path_in_value_ns_fully(
326 db: &dyn DefDatabase,
328 ) -> Option<ValueNs> {
329 match self.resolve_path_in_value_ns(db, path)? {
330 ResolveValueResult::ValueNs(it) => Some(it),
331 ResolveValueResult::Partial(..) => None,
335 pub fn resolve_path_as_macro(
337 db: &dyn DefDatabase,
339 ) -> Option<MacroDefId> {
340 let (item_map, module) = self.module_scope()?;
341 item_map.resolve_path(db, module, path, BuiltinShadowMode::Other).0.take_macros()
344 pub fn process_all_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
345 for scope in self.scopes.iter().rev() {
346 scope.process_names(db, f);
350 pub fn traits_in_scope(&self, db: &dyn DefDatabase) -> FxHashSet<TraitId> {
351 let mut traits = FxHashSet::default();
352 for scope in &self.scopes {
354 Scope::ModuleScope(m) => {
355 if let Some(prelude) = m.def_map.prelude() {
356 let prelude_def_map = prelude.def_map(db);
357 traits.extend(prelude_def_map[prelude.local_id].scope.traits());
359 traits.extend(m.def_map[m.module_id].scope.traits());
361 // Add all traits that are in scope because of the containing DefMaps
362 m.def_map.with_ancestor_maps(db, m.module_id, &mut |def_map, module| {
363 if let Some(prelude) = def_map.prelude() {
364 let prelude_def_map = prelude.def_map(db);
365 traits.extend(prelude_def_map[prelude.local_id].scope.traits());
367 traits.extend(def_map[module].scope.traits());
371 &Scope::ImplDefScope(impl_) => {
372 if let Some(target_trait) = &db.impl_data(impl_).target_trait {
373 if let Some(TypeNs::TraitId(trait_)) =
374 self.resolve_path_in_type_ns_fully(db, target_trait.path.mod_path())
376 traits.insert(trait_);
386 fn module_scope(&self) -> Option<(&DefMap, LocalModuleId)> {
387 self.scopes.iter().rev().find_map(|scope| match scope {
388 Scope::ModuleScope(m) => Some((&*m.def_map, m.module_id)),
394 pub fn module(&self) -> Option<ModuleId> {
395 let (def_map, local_id) = self.module_scope()?;
396 Some(def_map.module_id(local_id))
399 pub fn krate(&self) -> Option<CrateId> {
400 // FIXME: can this ever be `None`?
401 self.module_scope().map(|t| t.0.krate())
404 pub fn where_predicates_in_scope(
406 ) -> impl Iterator<Item = &crate::generics::WherePredicate> {
410 .filter_map(|scope| match scope {
411 Scope::GenericParams { params, .. } => Some(params),
414 .flat_map(|params| params.where_predicates.iter())
417 pub fn generic_def(&self) -> Option<GenericDefId> {
418 self.scopes.iter().rev().find_map(|scope| match scope {
419 Scope::GenericParams { def, .. } => Some(*def),
424 pub fn body_owner(&self) -> Option<DefWithBodyId> {
425 self.scopes.iter().rev().find_map(|scope| match scope {
426 Scope::ExprScope(it) => Some(it.owner),
434 ImplSelfType(ImplId),
436 GenericParam(GenericParamId),
442 fn process_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
443 let mut seen = FxHashSet::default();
445 Scope::ModuleScope(m) => {
446 // FIXME: should we provide `self` here?
448 // Name::self_param(),
449 // PerNs::types(Resolution::Def {
450 // def: m.module.into(),
453 m.def_map[m.module_id].scope.entries().for_each(|(name, def)| {
454 f(name.clone(), ScopeDef::PerNs(def));
456 m.def_map[m.module_id].scope.legacy_macros().for_each(|(name, macro_)| {
457 let scope = PerNs::macros(macro_, Visibility::Public);
458 seen.insert((name.clone(), scope));
459 f(name.clone(), ScopeDef::PerNs(scope));
461 m.def_map.extern_prelude().for_each(|(name, &def)| {
462 f(name.clone(), ScopeDef::PerNs(PerNs::types(def, Visibility::Public)));
464 BUILTIN_SCOPE.iter().for_each(|(name, &def)| {
465 f(name.clone(), ScopeDef::PerNs(def));
467 if let Some(prelude) = m.def_map.prelude() {
468 let prelude_def_map = prelude.def_map(db);
469 prelude_def_map[prelude.local_id].scope.entries().for_each(|(name, def)| {
470 let seen_tuple = (name.clone(), def);
471 if !seen.contains(&seen_tuple) {
472 f(seen_tuple.0, ScopeDef::PerNs(def));
477 &Scope::GenericParams { ref params, def: parent } => {
478 for (local_id, param) in params.types.iter() {
479 if let Some(ref name) = param.name {
480 let id = TypeParamId { parent, local_id };
481 f(name.clone(), ScopeDef::GenericParam(id.into()))
484 for (local_id, param) in params.consts.iter() {
485 let id = ConstParamId { parent, local_id };
486 f(param.name.clone(), ScopeDef::GenericParam(id.into()))
488 for (local_id, param) in params.lifetimes.iter() {
489 let id = LifetimeParamId { parent, local_id };
490 f(param.name.clone(), ScopeDef::GenericParam(id.into()))
493 Scope::ImplDefScope(i) => {
494 f(name![Self], ScopeDef::ImplSelfType(*i));
496 Scope::AdtScope(i) => {
497 f(name![Self], ScopeDef::AdtSelfType(*i));
499 Scope::ExprScope(scope) => {
500 if let Some((label, name)) = scope.expr_scopes.label(scope.scope_id) {
501 f(name, ScopeDef::Label(label))
503 scope.expr_scopes.entries(scope.scope_id).iter().for_each(|e| {
504 f(e.name().clone(), ScopeDef::Local(e.pat()));
511 // needs arbitrary_self_types to be a method... or maybe move to the def?
512 pub fn resolver_for_expr(db: &dyn DefDatabase, owner: DefWithBodyId, expr_id: ExprId) -> Resolver {
513 let scopes = db.expr_scopes(owner);
514 resolver_for_scope(db, owner, scopes.scope_for(expr_id))
517 pub fn resolver_for_scope(
518 db: &dyn DefDatabase,
519 owner: DefWithBodyId,
520 scope_id: Option<ScopeId>,
522 let mut r = owner.resolver(db);
523 let scopes = db.expr_scopes(owner);
524 let scope_chain = scopes.scope_chain(scope_id).collect::<Vec<_>>();
525 for scope in scope_chain.into_iter().rev() {
526 if let Some(block) = scopes.block(scope) {
527 if let Some(def_map) = db.block_def_map(block) {
528 let root = def_map.root();
529 r = r.push_module_scope(def_map, root);
530 // FIXME: This adds as many module scopes as there are blocks, but resolving in each
531 // already traverses all parents, so this is O(n²). I think we could only store the
532 // innermost module scope instead?
536 r = r.push_expr_scope(owner, Arc::clone(&scopes), scope);
542 fn push_scope(mut self, scope: Scope) -> Resolver {
543 self.scopes.push(scope);
547 fn push_generic_params_scope(self, db: &dyn DefDatabase, def: GenericDefId) -> Resolver {
548 let params = db.generic_params(def);
549 self.push_scope(Scope::GenericParams { def, params })
552 fn push_impl_def_scope(self, impl_def: ImplId) -> Resolver {
553 self.push_scope(Scope::ImplDefScope(impl_def))
556 fn push_module_scope(self, def_map: Arc<DefMap>, module_id: LocalModuleId) -> Resolver {
557 self.push_scope(Scope::ModuleScope(ModuleItemMap { def_map, module_id }))
562 owner: DefWithBodyId,
563 expr_scopes: Arc<ExprScopes>,
566 self.push_scope(Scope::ExprScope(ExprScope { owner, expr_scopes, scope_id }))
571 fn resolve_path_in_value_ns(
573 db: &dyn DefDatabase,
575 ) -> Option<ResolveValueResult> {
576 let (module_def, idx) =
577 self.def_map.resolve_path_locally(db, self.module_id, path, BuiltinShadowMode::Other);
580 let value = to_value_ns(module_def)?;
581 Some(ResolveValueResult::ValueNs(value))
584 let ty = match module_def.take_types()? {
585 ModuleDefId::AdtId(it) => TypeNs::AdtId(it),
586 ModuleDefId::TraitId(it) => TypeNs::TraitId(it),
587 ModuleDefId::TypeAliasId(it) => TypeNs::TypeAliasId(it),
588 ModuleDefId::BuiltinType(it) => TypeNs::BuiltinType(it),
590 ModuleDefId::ModuleId(_)
591 | ModuleDefId::FunctionId(_)
592 | ModuleDefId::EnumVariantId(_)
593 | ModuleDefId::ConstId(_)
594 | ModuleDefId::StaticId(_) => return None,
596 Some(ResolveValueResult::Partial(ty, idx))
601 fn resolve_path_in_type_ns(
603 db: &dyn DefDatabase,
605 ) -> Option<(TypeNs, Option<usize>)> {
606 let (module_def, idx) =
607 self.def_map.resolve_path_locally(db, self.module_id, path, BuiltinShadowMode::Other);
608 let res = to_type_ns(module_def)?;
613 fn to_value_ns(per_ns: PerNs) -> Option<ValueNs> {
614 let res = match per_ns.take_values()? {
615 ModuleDefId::FunctionId(it) => ValueNs::FunctionId(it),
616 ModuleDefId::AdtId(AdtId::StructId(it)) => ValueNs::StructId(it),
617 ModuleDefId::EnumVariantId(it) => ValueNs::EnumVariantId(it),
618 ModuleDefId::ConstId(it) => ValueNs::ConstId(it),
619 ModuleDefId::StaticId(it) => ValueNs::StaticId(it),
621 ModuleDefId::AdtId(AdtId::EnumId(_) | AdtId::UnionId(_))
622 | ModuleDefId::TraitId(_)
623 | ModuleDefId::TypeAliasId(_)
624 | ModuleDefId::BuiltinType(_)
625 | ModuleDefId::ModuleId(_) => return None,
630 fn to_type_ns(per_ns: PerNs) -> Option<TypeNs> {
631 let res = match per_ns.take_types()? {
632 ModuleDefId::AdtId(it) => TypeNs::AdtId(it),
633 ModuleDefId::EnumVariantId(it) => TypeNs::EnumVariantId(it),
635 ModuleDefId::TypeAliasId(it) => TypeNs::TypeAliasId(it),
636 ModuleDefId::BuiltinType(it) => TypeNs::BuiltinType(it),
638 ModuleDefId::TraitId(it) => TypeNs::TraitId(it),
640 ModuleDefId::FunctionId(_)
641 | ModuleDefId::ConstId(_)
642 | ModuleDefId::StaticId(_)
643 | ModuleDefId::ModuleId(_) => return None,
648 pub trait HasResolver: Copy {
649 /// Builds a resolver for type references inside this def.
650 fn resolver(self, db: &dyn DefDatabase) -> Resolver;
653 impl HasResolver for ModuleId {
654 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
655 let mut def_map = self.def_map(db);
656 let mut modules = vec![(def_map.clone(), self.local_id)];
657 while let Some(parent) = def_map.parent() {
658 def_map = parent.def_map(db);
659 modules.push((def_map.clone(), parent.local_id));
661 let mut resolver = Resolver::default();
662 for (def_map, module) in modules.into_iter().rev() {
663 resolver = resolver.push_module_scope(def_map, module);
669 impl HasResolver for TraitId {
670 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
671 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
675 impl<T: Into<AdtId> + Copy> HasResolver for T {
676 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
677 let def = self.into();
680 .push_generic_params_scope(db, def.into())
681 .push_scope(Scope::AdtScope(def))
685 impl HasResolver for FunctionId {
686 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
687 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
691 impl HasResolver for ConstId {
692 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
693 self.lookup(db).container.resolver(db)
697 impl HasResolver for StaticId {
698 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
699 self.lookup(db).container.resolver(db)
703 impl HasResolver for TypeAliasId {
704 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
705 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
709 impl HasResolver for ImplId {
710 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
714 .push_generic_params_scope(db, self.into())
715 .push_impl_def_scope(self)
719 impl HasResolver for DefWithBodyId {
720 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
722 DefWithBodyId::ConstId(c) => c.resolver(db),
723 DefWithBodyId::FunctionId(f) => f.resolver(db),
724 DefWithBodyId::StaticId(s) => s.resolver(db),
729 impl HasResolver for AssocContainerId {
730 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
732 AssocContainerId::ModuleId(it) => it.resolver(db),
733 AssocContainerId::TraitId(it) => it.resolver(db),
734 AssocContainerId::ImplId(it) => it.resolver(db),
739 impl HasResolver for GenericDefId {
740 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
742 GenericDefId::FunctionId(inner) => inner.resolver(db),
743 GenericDefId::AdtId(adt) => adt.resolver(db),
744 GenericDefId::TraitId(inner) => inner.resolver(db),
745 GenericDefId::TypeAliasId(inner) => inner.resolver(db),
746 GenericDefId::ImplId(inner) => inner.resolver(db),
747 GenericDefId::EnumVariantId(inner) => inner.parent.resolver(db),
748 GenericDefId::ConstId(inner) => inner.resolver(db),
753 impl HasResolver for VariantId {
754 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
756 VariantId::EnumVariantId(it) => it.parent.resolver(db),
757 VariantId::StructId(it) => it.resolver(db),
758 VariantId::UnionId(it) => it.resolver(db),