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, ConstId, ConstParamId, DefWithBodyId, EnumId, EnumVariantId,
24 FunctionId, GenericDefId, GenericParamId, HasModule, ImplId, LifetimeParamId, LocalModuleId,
25 Lookup, ModuleDefId, ModuleId, StaticId, StructId, TraitId, TypeAliasId, TypeParamId,
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_items(
149 db: &dyn DefDatabase,
151 ) -> Option<TraitId> {
152 let (item_map, module) = self.module_scope()?;
153 let (module_res, ..) = item_map.resolve_path(db, module, &path, BuiltinShadowMode::Module);
154 match module_res.take_types()? {
155 ModuleDefId::TraitId(it) => Some(it),
160 pub fn resolve_path_in_type_ns(
162 db: &dyn DefDatabase,
164 ) -> Option<(TypeNs, Option<usize>)> {
165 let first_name = path.segments().first()?;
166 let skip_to_mod = path.kind != PathKind::Plain;
167 for scope in self.scopes.iter().rev() {
169 Scope::ExprScope(_) => continue,
170 Scope::GenericParams { .. } | Scope::ImplDefScope(_) if skip_to_mod => continue,
172 Scope::GenericParams { params, def } => {
173 if let Some(local_id) = params.find_type_by_name(first_name) {
174 let idx = if path.segments().len() == 1 { None } else { Some(1) };
176 TypeNs::GenericParam(TypeParamId { local_id, parent: *def }),
181 Scope::ImplDefScope(impl_) => {
182 if first_name == &name![Self] {
183 let idx = if path.segments().len() == 1 { None } else { Some(1) };
184 return Some((TypeNs::SelfType(*impl_), idx));
187 Scope::AdtScope(adt) => {
188 if first_name == &name![Self] {
189 let idx = if path.segments().len() == 1 { None } else { Some(1) };
190 return Some((TypeNs::AdtSelfType(*adt), idx));
193 Scope::ModuleScope(m) => {
194 if let Some(res) = m.resolve_path_in_type_ns(db, path) {
203 pub fn resolve_path_in_type_ns_fully(
205 db: &dyn DefDatabase,
207 ) -> Option<TypeNs> {
208 let (res, unresolved) = self.resolve_path_in_type_ns(db, path)?;
209 if unresolved.is_some() {
215 pub fn resolve_visibility(
217 db: &dyn DefDatabase,
218 visibility: &RawVisibility,
219 ) -> Option<Visibility> {
221 RawVisibility::Module(_) => {
222 let (item_map, module) = match self.module_scope() {
226 item_map.resolve_visibility(db, module, visibility)
228 RawVisibility::Public => Some(Visibility::Public),
232 pub fn resolve_path_in_value_ns(
234 db: &dyn DefDatabase,
236 ) -> Option<ResolveValueResult> {
237 let n_segments = path.segments().len();
238 let tmp = name![self];
239 let first_name = if path.is_self() { &tmp } else { path.segments().first()? };
240 let skip_to_mod = path.kind != PathKind::Plain && !path.is_self();
241 for scope in self.scopes.iter().rev() {
244 | Scope::ExprScope(_)
245 | Scope::GenericParams { .. }
246 | Scope::ImplDefScope(_)
252 Scope::ExprScope(scope) if n_segments <= 1 => {
255 .entries(scope.scope_id)
257 .find(|entry| entry.name() == first_name);
259 if let Some(e) = entry {
260 return Some(ResolveValueResult::ValueNs(ValueNs::LocalBinding(e.pat())));
263 Scope::ExprScope(_) => continue,
265 Scope::GenericParams { params, def } if n_segments > 1 => {
266 if let Some(local_id) = params.find_type_by_name(first_name) {
267 let ty = TypeNs::GenericParam(TypeParamId { local_id, parent: *def });
268 return Some(ResolveValueResult::Partial(ty, 1));
271 Scope::GenericParams { params, def } if n_segments == 1 => {
272 if let Some(local_id) = params.find_const_by_name(first_name) {
273 let val = ValueNs::GenericParam(ConstParamId { local_id, parent: *def });
274 return Some(ResolveValueResult::ValueNs(val));
277 Scope::GenericParams { .. } => continue,
279 Scope::ImplDefScope(impl_) => {
280 if first_name == &name![Self] {
282 let ty = TypeNs::SelfType(*impl_);
283 return Some(ResolveValueResult::Partial(ty, 1));
285 return Some(ResolveValueResult::ValueNs(ValueNs::ImplSelf(*impl_)));
289 Scope::AdtScope(adt) => {
291 // bare `Self` doesn't work in the value namespace in a struct/enum definition
294 if first_name == &name![Self] {
295 let ty = TypeNs::AdtSelfType(*adt);
296 return Some(ResolveValueResult::Partial(ty, 1));
300 Scope::ModuleScope(m) => {
301 if let Some(def) = m.resolve_path_in_value_ns(db, path) {
311 pub fn resolve_path_in_value_ns_fully(
313 db: &dyn DefDatabase,
315 ) -> Option<ValueNs> {
316 match self.resolve_path_in_value_ns(db, path)? {
317 ResolveValueResult::ValueNs(it) => Some(it),
318 ResolveValueResult::Partial(..) => None,
322 pub fn resolve_path_as_macro(
324 db: &dyn DefDatabase,
326 ) -> Option<MacroDefId> {
327 let (item_map, module) = self.module_scope()?;
328 item_map.resolve_path(db, module, &path, BuiltinShadowMode::Other).0.take_macros()
331 pub fn process_all_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
332 for scope in self.scopes.iter().rev() {
333 scope.process_names(db, f);
337 pub fn traits_in_scope(&self, db: &dyn DefDatabase) -> FxHashSet<TraitId> {
338 let mut traits = FxHashSet::default();
339 for scope in &self.scopes {
340 if let Scope::ModuleScope(m) = scope {
341 if let Some(prelude) = m.def_map.prelude() {
342 let prelude_def_map = prelude.def_map(db);
343 traits.extend(prelude_def_map[prelude.local_id].scope.traits());
345 traits.extend(m.def_map[m.module_id].scope.traits());
347 // Add all traits that are in scope because of the containing DefMaps
348 m.def_map.with_ancestor_maps(db, m.module_id, &mut |def_map, module| {
349 if let Some(prelude) = def_map.prelude() {
350 let prelude_def_map = prelude.def_map(db);
351 traits.extend(prelude_def_map[prelude.local_id].scope.traits());
353 traits.extend(def_map[module].scope.traits());
361 fn module_scope(&self) -> Option<(&DefMap, LocalModuleId)> {
362 self.scopes.iter().rev().find_map(|scope| match scope {
363 Scope::ModuleScope(m) => Some((&*m.def_map, m.module_id)),
369 pub fn module(&self) -> Option<ModuleId> {
370 let (def_map, local_id) = self.module_scope()?;
371 Some(def_map.module_id(local_id))
374 pub fn krate(&self) -> Option<CrateId> {
375 // FIXME: can this ever be `None`?
376 self.module_scope().map(|t| t.0.krate())
379 pub fn where_predicates_in_scope<'a>(
381 ) -> impl Iterator<Item = &'a crate::generics::WherePredicate> + 'a {
385 .filter_map(|scope| match scope {
386 Scope::GenericParams { params, .. } => Some(params),
389 .flat_map(|params| params.where_predicates.iter())
392 pub fn generic_def(&self) -> Option<GenericDefId> {
393 self.scopes.iter().rev().find_map(|scope| match scope {
394 Scope::GenericParams { def, .. } => Some(*def),
399 pub fn body_owner(&self) -> Option<DefWithBodyId> {
400 self.scopes.iter().rev().find_map(|scope| match scope {
401 Scope::ExprScope(it) => Some(it.owner),
409 ImplSelfType(ImplId),
411 GenericParam(GenericParamId),
417 fn process_names(&self, db: &dyn DefDatabase, f: &mut dyn FnMut(Name, ScopeDef)) {
418 let mut seen = FxHashSet::default();
420 Scope::ModuleScope(m) => {
421 // FIXME: should we provide `self` here?
423 // Name::self_param(),
424 // PerNs::types(Resolution::Def {
425 // def: m.module.into(),
428 m.def_map[m.module_id].scope.entries().for_each(|(name, def)| {
429 f(name.clone(), ScopeDef::PerNs(def));
431 m.def_map[m.module_id].scope.legacy_macros().for_each(|(name, macro_)| {
432 let scope = PerNs::macros(macro_, Visibility::Public);
433 seen.insert((name.clone(), scope));
434 f(name.clone(), ScopeDef::PerNs(scope));
436 m.def_map.extern_prelude().for_each(|(name, &def)| {
437 f(name.clone(), ScopeDef::PerNs(PerNs::types(def, Visibility::Public)));
439 BUILTIN_SCOPE.iter().for_each(|(name, &def)| {
440 f(name.clone(), ScopeDef::PerNs(def));
442 if let Some(prelude) = m.def_map.prelude() {
443 let prelude_def_map = prelude.def_map(db);
444 prelude_def_map[prelude.local_id].scope.entries().for_each(|(name, def)| {
445 let seen_tuple = (name.clone(), def);
446 if !seen.contains(&seen_tuple) {
447 f(seen_tuple.0, ScopeDef::PerNs(def));
452 &Scope::GenericParams { ref params, def: parent } => {
453 for (local_id, param) in params.types.iter() {
454 if let Some(ref name) = param.name {
455 let id = TypeParamId { local_id, parent };
456 f(name.clone(), ScopeDef::GenericParam(id.into()))
459 for (local_id, param) in params.consts.iter() {
460 let id = ConstParamId { local_id, parent };
461 f(param.name.clone(), ScopeDef::GenericParam(id.into()))
463 for (local_id, param) in params.lifetimes.iter() {
464 let id = LifetimeParamId { local_id, parent };
465 f(param.name.clone(), ScopeDef::GenericParam(id.into()))
468 Scope::ImplDefScope(i) => {
469 f(name![Self], ScopeDef::ImplSelfType(*i));
471 Scope::AdtScope(i) => {
472 f(name![Self], ScopeDef::AdtSelfType(*i));
474 Scope::ExprScope(scope) => {
475 if let Some((label, name)) = scope.expr_scopes.label(scope.scope_id) {
476 f(name, ScopeDef::Label(label))
478 scope.expr_scopes.entries(scope.scope_id).iter().for_each(|e| {
479 f(e.name().clone(), ScopeDef::Local(e.pat()));
486 // needs arbitrary_self_types to be a method... or maybe move to the def?
487 pub fn resolver_for_expr(db: &dyn DefDatabase, owner: DefWithBodyId, expr_id: ExprId) -> Resolver {
488 let scopes = db.expr_scopes(owner);
489 resolver_for_scope(db, owner, scopes.scope_for(expr_id))
492 pub fn resolver_for_scope(
493 db: &dyn DefDatabase,
494 owner: DefWithBodyId,
495 scope_id: Option<ScopeId>,
497 let mut r = owner.resolver(db);
498 let scopes = db.expr_scopes(owner);
499 let scope_chain = scopes.scope_chain(scope_id).collect::<Vec<_>>();
500 for scope in scope_chain.into_iter().rev() {
501 if let Some(block) = scopes.block(scope) {
502 if let Some(def_map) = db.block_def_map(block) {
503 let root = def_map.root();
504 r = r.push_module_scope(def_map, root);
505 // FIXME: This adds as many module scopes as there are blocks, but resolving in each
506 // already traverses all parents, so this is O(n²). I think we could only store the
507 // innermost module scope instead?
511 r = r.push_expr_scope(owner, Arc::clone(&scopes), scope);
517 fn push_scope(mut self, scope: Scope) -> Resolver {
518 self.scopes.push(scope);
522 fn push_generic_params_scope(self, db: &dyn DefDatabase, def: GenericDefId) -> Resolver {
523 let params = db.generic_params(def);
524 self.push_scope(Scope::GenericParams { def, params })
527 fn push_impl_def_scope(self, impl_def: ImplId) -> Resolver {
528 self.push_scope(Scope::ImplDefScope(impl_def))
531 fn push_module_scope(self, def_map: Arc<DefMap>, module_id: LocalModuleId) -> Resolver {
532 self.push_scope(Scope::ModuleScope(ModuleItemMap { def_map, module_id }))
537 owner: DefWithBodyId,
538 expr_scopes: Arc<ExprScopes>,
541 self.push_scope(Scope::ExprScope(ExprScope { owner, expr_scopes, scope_id }))
546 fn resolve_path_in_value_ns(
548 db: &dyn DefDatabase,
550 ) -> Option<ResolveValueResult> {
551 let (module_def, idx) =
552 self.def_map.resolve_path_locally(db, self.module_id, &path, BuiltinShadowMode::Other);
555 let value = to_value_ns(module_def)?;
556 Some(ResolveValueResult::ValueNs(value))
559 let ty = match module_def.take_types()? {
560 ModuleDefId::AdtId(it) => TypeNs::AdtId(it),
561 ModuleDefId::TraitId(it) => TypeNs::TraitId(it),
562 ModuleDefId::TypeAliasId(it) => TypeNs::TypeAliasId(it),
563 ModuleDefId::BuiltinType(it) => TypeNs::BuiltinType(it),
565 ModuleDefId::ModuleId(_)
566 | ModuleDefId::FunctionId(_)
567 | ModuleDefId::EnumVariantId(_)
568 | ModuleDefId::ConstId(_)
569 | ModuleDefId::StaticId(_) => return None,
571 Some(ResolveValueResult::Partial(ty, idx))
576 fn resolve_path_in_type_ns(
578 db: &dyn DefDatabase,
580 ) -> Option<(TypeNs, Option<usize>)> {
581 let (module_def, idx) =
582 self.def_map.resolve_path_locally(db, self.module_id, &path, BuiltinShadowMode::Other);
583 let res = to_type_ns(module_def)?;
588 fn to_value_ns(per_ns: PerNs) -> Option<ValueNs> {
589 let res = match per_ns.take_values()? {
590 ModuleDefId::FunctionId(it) => ValueNs::FunctionId(it),
591 ModuleDefId::AdtId(AdtId::StructId(it)) => ValueNs::StructId(it),
592 ModuleDefId::EnumVariantId(it) => ValueNs::EnumVariantId(it),
593 ModuleDefId::ConstId(it) => ValueNs::ConstId(it),
594 ModuleDefId::StaticId(it) => ValueNs::StaticId(it),
596 ModuleDefId::AdtId(AdtId::EnumId(_))
597 | ModuleDefId::AdtId(AdtId::UnionId(_))
598 | ModuleDefId::TraitId(_)
599 | ModuleDefId::TypeAliasId(_)
600 | ModuleDefId::BuiltinType(_)
601 | ModuleDefId::ModuleId(_) => return None,
606 fn to_type_ns(per_ns: PerNs) -> Option<TypeNs> {
607 let res = match per_ns.take_types()? {
608 ModuleDefId::AdtId(it) => TypeNs::AdtId(it),
609 ModuleDefId::EnumVariantId(it) => TypeNs::EnumVariantId(it),
611 ModuleDefId::TypeAliasId(it) => TypeNs::TypeAliasId(it),
612 ModuleDefId::BuiltinType(it) => TypeNs::BuiltinType(it),
614 ModuleDefId::TraitId(it) => TypeNs::TraitId(it),
616 ModuleDefId::FunctionId(_)
617 | ModuleDefId::ConstId(_)
618 | ModuleDefId::StaticId(_)
619 | ModuleDefId::ModuleId(_) => return None,
624 pub trait HasResolver: Copy {
625 /// Builds a resolver for type references inside this def.
626 fn resolver(self, db: &dyn DefDatabase) -> Resolver;
629 impl HasResolver for ModuleId {
630 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
631 let mut def_map = self.def_map(db);
632 let mut modules = Vec::new();
633 modules.push((def_map.clone(), self.local_id));
634 while let Some(parent) = def_map.parent() {
635 def_map = parent.def_map(db);
636 modules.push((def_map.clone(), parent.local_id));
638 let mut resolver = Resolver::default();
639 for (def_map, module) in modules.into_iter().rev() {
640 resolver = resolver.push_module_scope(def_map, module);
646 impl HasResolver for TraitId {
647 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
648 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
652 impl<T: Into<AdtId> + Copy> HasResolver for T {
653 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
654 let def = self.into();
657 .push_generic_params_scope(db, def.into())
658 .push_scope(Scope::AdtScope(def))
662 impl HasResolver for FunctionId {
663 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
664 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
668 impl HasResolver for ConstId {
669 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
670 self.lookup(db).container.resolver(db)
674 impl HasResolver for StaticId {
675 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
676 self.lookup(db).container.resolver(db)
680 impl HasResolver for TypeAliasId {
681 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
682 self.lookup(db).container.resolver(db).push_generic_params_scope(db, self.into())
686 impl HasResolver for ImplId {
687 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
691 .push_generic_params_scope(db, self.into())
692 .push_impl_def_scope(self)
696 impl HasResolver for DefWithBodyId {
697 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
699 DefWithBodyId::ConstId(c) => c.resolver(db),
700 DefWithBodyId::FunctionId(f) => f.resolver(db),
701 DefWithBodyId::StaticId(s) => s.resolver(db),
706 impl HasResolver for AssocContainerId {
707 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
709 AssocContainerId::ModuleId(it) => it.resolver(db),
710 AssocContainerId::TraitId(it) => it.resolver(db),
711 AssocContainerId::ImplId(it) => it.resolver(db),
716 impl HasResolver for GenericDefId {
717 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
719 GenericDefId::FunctionId(inner) => inner.resolver(db),
720 GenericDefId::AdtId(adt) => adt.resolver(db),
721 GenericDefId::TraitId(inner) => inner.resolver(db),
722 GenericDefId::TypeAliasId(inner) => inner.resolver(db),
723 GenericDefId::ImplId(inner) => inner.resolver(db),
724 GenericDefId::EnumVariantId(inner) => inner.parent.resolver(db),
725 GenericDefId::ConstId(inner) => inner.resolver(db),
730 impl HasResolver for VariantId {
731 fn resolver(self, db: &dyn DefDatabase) -> Resolver {
733 VariantId::EnumVariantId(it) => it.parent.resolver(db),
734 VariantId::StructId(it) => it.resolver(db),
735 VariantId::UnionId(it) => it.resolver(db),