Skip to content

resolve: Make disambiguators for underscore bindings module-local #144013

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions compiler/rustc_resolve/src/build_reduced_graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
ns: Namespace,
binding: NameBinding<'ra>,
) {
let key = self.new_disambiguated_key(ident, ns);
if let Err(old_binding) = self.try_define(parent, key, binding, false) {
if let Err(old_binding) = self.try_define(parent, ident, ns, binding, false) {
self.report_conflict(parent, ident, ns, old_binding, binding);
}
}
Expand Down Expand Up @@ -439,16 +438,18 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {

self.r.indeterminate_imports.push(import);
match import.kind {
// Don't add unresolved underscore imports to modules
ImportKind::Single { target: Ident { name: kw::Underscore, .. }, .. } => {}
ImportKind::Single { target, type_ns_only, .. } => {
self.r.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS {
let key = BindingKey::new(target, ns);
let mut resolution = this.resolution(current_module, key).borrow_mut();
resolution.single_imports.insert(import);
}
});
// Don't add underscore imports to `single_imports`
// because they cannot define any usable names.
if target.name != kw::Underscore {
self.r.per_ns(|this, ns| {
if !type_ns_only || ns == TypeNS {
let key = BindingKey::new(target, ns);
let mut resolution = this.resolution(current_module, key).borrow_mut();
resolution.single_imports.insert(import);
}
});
}
}
// We don't add prelude imports to the globs since they only affect lexical scopes,
// which are not relevant to import resolution.
Expand Down Expand Up @@ -1402,9 +1403,12 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
let parent = self.parent_scope.module;
let expansion = self.parent_scope.expansion;
self.r.define(parent, ident, ns, self.res(def_id), vis, item.span, expansion);
} else if !matches!(&item.kind, AssocItemKind::Delegation(deleg) if deleg.from_glob) {
} else if !matches!(&item.kind, AssocItemKind::Delegation(deleg) if deleg.from_glob)
&& ident.name != kw::Underscore
{
// Don't add underscore names, they cannot be looked up anyway.
let impl_def_id = self.r.tcx.local_parent(local_def_id);
let key = BindingKey::new(ident.normalize_to_macros_2_0(), ns);
let key = BindingKey::new(ident, ns);
self.r.impl_binding_keys.entry(impl_def_id).or_default().insert(key);
}

Expand Down
38 changes: 25 additions & 13 deletions compiler/rustc_resolve/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use rustc_span::{Ident, Span, Symbol, kw, sym};
use smallvec::SmallVec;
use tracing::debug;

use crate::Namespace::*;
use crate::Namespace::{self, *};
use crate::diagnostics::{DiagMode, Suggestion, import_candidates};
use crate::errors::{
CannotBeReexportedCratePublic, CannotBeReexportedCratePublicNS, CannotBeReexportedPrivate,
Expand Down Expand Up @@ -338,13 +338,20 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
pub(crate) fn try_define(
&mut self,
module: Module<'ra>,
key: BindingKey,
ident: Ident,
ns: Namespace,
binding: NameBinding<'ra>,
warn_ambiguity: bool,
) -> Result<(), NameBinding<'ra>> {
let res = binding.res();
self.check_reserved_macro_name(key.ident, res);
self.check_reserved_macro_name(ident, res);
self.set_binding_parent_module(binding, module);
// Even if underscore names cannot be looked up, we still need to add them to modules,
// because they can be fetched by glob imports from those modules, and bring traits
// into scope both directly and through glob imports.
let key = BindingKey::new_disambiguated(ident, ns, || {
(module.0.0.lazy_resolutions.borrow().len() + 1).try_into().unwrap()
});
self.update_resolution(module, key, warn_ambiguity, |this, resolution| {
if let Some(old_binding) = resolution.best_binding() {
if res == Res::Err && old_binding.res() != Res::Err {
Expand Down Expand Up @@ -383,7 +390,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
(old_glob @ true, false) | (old_glob @ false, true) => {
let (glob_binding, non_glob_binding) =
if old_glob { (old_binding, binding) } else { (binding, old_binding) };
if key.ns == MacroNS
if ns == MacroNS
&& non_glob_binding.expansion != LocalExpnId::ROOT
&& glob_binding.res() != non_glob_binding.res()
{
Expand Down Expand Up @@ -489,10 +496,10 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
};
if self.is_accessible_from(binding.vis, scope) {
let imported_binding = self.import(binding, *import);
let key = BindingKey { ident, ..key };
let _ = self.try_define(
import.parent_scope.module,
key,
ident,
key.ns,
imported_binding,
warn_ambiguity,
);
Expand All @@ -514,11 +521,15 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
let dummy_binding = self.dummy_binding;
let dummy_binding = self.import(dummy_binding, import);
self.per_ns(|this, ns| {
let key = BindingKey::new(target, ns);
let _ = this.try_define(import.parent_scope.module, key, dummy_binding, false);
this.update_resolution(import.parent_scope.module, key, false, |_, resolution| {
resolution.single_imports.swap_remove(&import);
})
let module = import.parent_scope.module;
let _ = this.try_define(module, target, ns, dummy_binding, false);
// Don't remove underscores from `single_imports`, they were never added.
if target.name != kw::Underscore {
let key = BindingKey::new(target, ns);
this.update_resolution(module, key, false, |_, resolution| {
resolution.single_imports.swap_remove(&import);
})
}
});
self.record_use(target, dummy_binding, Used::Other);
} else if import.imported_module.get().is_none() {
Expand Down Expand Up @@ -895,7 +906,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
PendingBinding::Ready(Some(imported_binding))
}
Err(Determinacy::Determined) => {
// Don't update the resolution for underscores, because it was never added.
// Don't remove underscores from `single_imports`, they were never added.
if target.name != kw::Underscore {
let key = BindingKey::new(target, ns);
this.update_resolution(parent, key, false, |_, resolution| {
Expand Down Expand Up @@ -1510,7 +1521,8 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
.is_some_and(|binding| binding.warn_ambiguity_recursive());
let _ = self.try_define(
import.parent_scope.module,
key,
key.ident,
key.ns,
imported_binding,
warn_ambiguity,
);
Expand Down
33 changes: 15 additions & 18 deletions compiler/rustc_resolve/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,15 +532,26 @@ struct BindingKey {
/// identifier.
ident: Ident,
ns: Namespace,
/// 0 if ident is not `_`, otherwise a value that's unique to the specific
/// `_` in the expanded AST that introduced this binding.
/// When we add an underscore binding (with ident `_`) to some module, this field has
/// a non-zero value that uniquely identifies this binding in that module.
/// For non-underscore bindings this field is zero.
/// When a key is constructed for name lookup (as opposed to name definition), this field is
/// also zero, even for underscore names, so for underscores the lookup will never succeed.
disambiguator: u32,
}

impl BindingKey {
fn new(ident: Ident, ns: Namespace) -> Self {
let ident = ident.normalize_to_macros_2_0();
BindingKey { ident, ns, disambiguator: 0 }
BindingKey { ident: ident.normalize_to_macros_2_0(), ns, disambiguator: 0 }
}

fn new_disambiguated(
ident: Ident,
ns: Namespace,
disambiguator: impl FnOnce() -> u32,
) -> BindingKey {
let disambiguator = if ident.name == kw::Underscore { disambiguator() } else { 0 };
BindingKey { ident: ident.normalize_to_macros_2_0(), ns, disambiguator }
}
}

Expand Down Expand Up @@ -1078,8 +1089,6 @@ pub struct Resolver<'ra, 'tcx> {
module_map: FxIndexMap<DefId, Module<'ra>>,
binding_parent_modules: FxHashMap<NameBinding<'ra>, Module<'ra>>,

underscore_disambiguator: u32,

/// Maps glob imports to the names of items actually imported.
glob_map: FxIndexMap<LocalDefId, FxIndexSet<Symbol>>,
glob_error: Option<ErrorGuaranteed>,
Expand Down Expand Up @@ -1500,7 +1509,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
extern_crate_map: Default::default(),
module_children: Default::default(),
trait_map: NodeMap::default(),
underscore_disambiguator: 0,
empty_module,
module_map,
block_map: Default::default(),
Expand Down Expand Up @@ -1880,17 +1888,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
import_ids
}

fn new_disambiguated_key(&mut self, ident: Ident, ns: Namespace) -> BindingKey {
let ident = ident.normalize_to_macros_2_0();
let disambiguator = if ident.name == kw::Underscore {
self.underscore_disambiguator += 1;
self.underscore_disambiguator
} else {
0
};
BindingKey { ident, ns, disambiguator }
}

fn resolutions(&mut self, module: Module<'ra>) -> &'ra Resolutions<'ra> {
if module.populate_on_access.get() {
module.populate_on_access.set(false);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_resolve/src/macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
target_trait.for_each_child(self, |this, ident, ns, _binding| {
// FIXME: Adjust hygiene for idents from globs, like for glob imports.
if let Some(overriding_keys) = this.impl_binding_keys.get(&impl_def_id)
&& overriding_keys.contains(&BindingKey::new(ident.normalize_to_macros_2_0(), ns))
&& overriding_keys.contains(&BindingKey::new(ident, ns))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Drive-by cleanup, the normalization already happens inside BindingKey::new.

{
// The name is overridden, do not produce it from the glob delegation.
} else {
Expand Down
Loading