Skip to content

Commit e561ec0

Browse files
committed
Remove global next_disambiguator state and handle it with a DisambiguatorState type
1 parent 2ac60bc commit e561ec0

File tree

24 files changed

+190
-93
lines changed

24 files changed

+190
-93
lines changed

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -509,7 +509,11 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
509509
self.tcx.hir_def_key(self.local_def_id(node_id)),
510510
);
511511

512-
let def_id = self.tcx.at(span).create_def(parent, name, def_kind).def_id();
512+
let def_id = self
513+
.tcx
514+
.at(span)
515+
.create_def(parent, name, def_kind, None, &mut self.resolver.disambiguator)
516+
.def_id();
513517

514518
debug!("create_def: def_id_to_node_id[{:?}] <-> {:?}", def_id, node_id);
515519
self.resolver.node_id_to_def_id.insert(node_id, def_id);

compiler/rustc_const_eval/src/const_eval/dummy_machine.rs

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use rustc_hir::def_id::LocalDefId;
2+
use rustc_hir::definitions::DisambiguatorState;
13
use rustc_middle::mir::interpret::{AllocId, ConstAllocation, InterpResult};
24
use rustc_middle::mir::*;
35
use rustc_middle::query::TyCtxtAt;
@@ -42,7 +44,7 @@ pub macro throw_machine_stop_str($($tt:tt)*) {{
4244
pub struct DummyMachine;
4345

4446
impl HasStaticRootDefId for DummyMachine {
45-
fn static_def_id(&self) -> Option<rustc_hir::def_id::LocalDefId> {
47+
fn static_parent_and_disambiguator(&mut self) -> Option<(LocalDefId, &mut DisambiguatorState)> {
4648
None
4749
}
4850
}

compiler/rustc_const_eval/src/const_eval/machine.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use rustc_abi::{Align, Size};
66
use rustc_ast::Mutability;
77
use rustc_data_structures::fx::{FxHashMap, FxIndexMap, IndexEntry};
88
use rustc_hir::def_id::{DefId, LocalDefId};
9+
use rustc_hir::definitions::DisambiguatorState;
910
use rustc_hir::{self as hir, CRATE_HIR_ID, LangItem};
1011
use rustc_middle::mir::AssertMessage;
1112
use rustc_middle::mir::interpret::ReportedErrorInfo;
@@ -63,7 +64,7 @@ pub struct CompileTimeMachine<'tcx> {
6364
/// If `Some`, we are evaluating the initializer of the static with the given `LocalDefId`,
6465
/// storing the result in the given `AllocId`.
6566
/// Used to prevent reads from a static's base allocation, as that may allow for self-initialization loops.
66-
pub(crate) static_root_ids: Option<(AllocId, LocalDefId)>,
67+
pub(crate) static_root_ids: Option<(AllocId, LocalDefId, DisambiguatorState)>,
6768

6869
/// A cache of "data range" computations for unions (i.e., the offsets of non-padding bytes).
6970
union_data_ranges: FxHashMap<Ty<'tcx>, RangeSet>,
@@ -706,7 +707,7 @@ impl<'tcx> interpret::Machine<'tcx> for CompileTimeMachine<'tcx> {
706707

707708
fn before_alloc_read(ecx: &InterpCx<'tcx, Self>, alloc_id: AllocId) -> InterpResult<'tcx> {
708709
// Check if this is the currently evaluated static.
709-
if Some(alloc_id) == ecx.machine.static_root_ids.map(|(id, _)| id) {
710+
if Some(alloc_id) == ecx.machine.static_root_ids.as_ref().map(|(id, ..)| *id) {
710711
return Err(ConstEvalErrKind::RecursiveStatic).into();
711712
}
712713
// If this is another static, make sure we fire off the query to detect cycles.

compiler/rustc_const_eval/src/interpret/intern.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ use hir::def::DefKind;
1717
use rustc_ast::Mutability;
1818
use rustc_data_structures::fx::{FxHashSet, FxIndexMap};
1919
use rustc_hir as hir;
20+
use rustc_hir::definitions::DisambiguatorState;
2021
use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrs;
2122
use rustc_middle::mir::interpret::{ConstAllocation, CtfeProvenance, InterpResult};
2223
use rustc_middle::query::TyCtxtAt;
@@ -46,12 +47,13 @@ pub trait CompileTimeMachine<'tcx, T> = Machine<
4647
pub trait HasStaticRootDefId {
4748
/// Returns the `DefId` of the static item that is currently being evaluated.
4849
/// Used for interning to be able to handle nested allocations.
49-
fn static_def_id(&self) -> Option<LocalDefId>;
50+
fn static_parent_and_disambiguator(&mut self) -> Option<(LocalDefId, &mut DisambiguatorState)>;
5051
}
5152

5253
impl HasStaticRootDefId for const_eval::CompileTimeMachine<'_> {
53-
fn static_def_id(&self) -> Option<LocalDefId> {
54-
Some(self.static_root_ids?.1)
54+
fn static_parent_and_disambiguator(&mut self) -> Option<(LocalDefId, &mut DisambiguatorState)> {
55+
let (_, static_id, d) = self.static_root_ids.as_mut()?;
56+
Some((*static_id, d))
5557
}
5658
}
5759

@@ -87,8 +89,8 @@ fn intern_shallow<'tcx, T, M: CompileTimeMachine<'tcx, T>>(
8789
}
8890
// link the alloc id to the actual allocation
8991
let alloc = ecx.tcx.mk_const_alloc(alloc);
90-
if let Some(static_id) = ecx.machine.static_def_id() {
91-
intern_as_new_static(ecx.tcx, static_id, alloc_id, alloc);
92+
if let Some((static_id, disambiguator)) = ecx.machine.static_parent_and_disambiguator() {
93+
intern_as_new_static(ecx.tcx, static_id, alloc_id, alloc, disambiguator);
9294
} else {
9395
ecx.tcx.set_alloc_id_memory(alloc_id, alloc);
9496
}
@@ -102,11 +104,14 @@ fn intern_as_new_static<'tcx>(
102104
static_id: LocalDefId,
103105
alloc_id: AllocId,
104106
alloc: ConstAllocation<'tcx>,
107+
disambiguator: &mut DisambiguatorState,
105108
) {
106109
let feed = tcx.create_def(
107110
static_id,
108111
Some(sym::nested),
109112
DefKind::Static { safety: hir::Safety::Safe, mutability: alloc.0.mutability, nested: true },
113+
None,
114+
disambiguator,
110115
);
111116
tcx.set_nested_alloc_id_static(alloc_id, feed.def_id());
112117

compiler/rustc_const_eval/src/interpret/util.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
use rustc_hir::def_id::LocalDefId;
2+
use rustc_hir::definitions::DisambiguatorState;
23
use rustc_middle::mir;
34
use rustc_middle::mir::interpret::{AllocInit, Allocation, InterpResult, Pointer};
45
use rustc_middle::ty::layout::TyAndLayout;
@@ -40,8 +41,8 @@ pub(crate) fn create_static_alloc<'tcx>(
4041
) -> InterpResult<'tcx, MPlaceTy<'tcx>> {
4142
let alloc = Allocation::try_new(layout.size, layout.align.abi, AllocInit::Uninit)?;
4243
let alloc_id = ecx.tcx.reserve_and_set_static_alloc(static_def_id.into());
43-
assert_eq!(ecx.machine.static_root_ids, None);
44-
ecx.machine.static_root_ids = Some((alloc_id, static_def_id));
44+
assert!(ecx.machine.static_root_ids.is_none());
45+
ecx.machine.static_root_ids = Some((alloc_id, static_def_id, DisambiguatorState::new()));
4546
assert!(ecx.memory.alloc_map.insert(alloc_id, (MemoryKind::Stack, alloc)).is_none());
4647
interp_ok(ecx.ptr_to_mplace(Pointer::from(alloc_id).into(), layout))
4748
}

compiler/rustc_hir/src/def.rs

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -269,14 +269,9 @@ impl DefKind {
269269
| DefKind::TyParam
270270
| DefKind::ExternCrate => DefPathData::TypeNs(name.unwrap()),
271271

272-
// An associated type name will be missing for an RPITIT.
273-
DefKind::AssocTy => {
274-
if let Some(name) = name {
275-
DefPathData::TypeNs(name)
276-
} else {
277-
DefPathData::AnonAssocTy
278-
}
279-
}
272+
// An associated type name will be missing for an RPITIT (DefPathData::AnonAssocTy),
273+
// but those provide their own DefPathData.
274+
DefKind::AssocTy => DefPathData::TypeNs(name.unwrap()),
280275

281276
// It's not exactly an anon const, but wrt DefPathData, there
282277
// is no difference.

compiler/rustc_hir/src/definitions.rs

Lines changed: 44 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ impl DefPathTable {
6868
//
6969
// See the documentation for DefPathHash for more information.
7070
panic!(
71-
"found DefPathHash collision between {def_path1:?} and {def_path2:?}. \
71+
"found DefPathHash collision between {def_path1:#?} and {def_path2:#?}. \
7272
Compilation cannot continue."
7373
);
7474
}
@@ -97,13 +97,31 @@ impl DefPathTable {
9797
}
9898
}
9999

100+
#[derive(Debug)]
101+
pub struct DisambiguatorState {
102+
next: UnordMap<(LocalDefId, DefPathData), u32>,
103+
}
104+
105+
impl DisambiguatorState {
106+
pub fn new() -> Self {
107+
Self { next: Default::default() }
108+
}
109+
110+
/// Creates a `DisambiguatorState` where the next allocated `(LocalDefId, DefPathData)` pair
111+
/// will have `index` as the disambiguator.
112+
pub fn with(def_id: LocalDefId, data: DefPathData, index: u32) -> Self {
113+
let mut this = Self::new();
114+
this.next.insert((def_id, data), index);
115+
this
116+
}
117+
}
118+
100119
/// The definition table containing node definitions.
101120
/// It holds the `DefPathTable` for `LocalDefId`s/`DefPath`s.
102121
/// It also stores mappings to convert `LocalDefId`s to/from `HirId`s.
103122
#[derive(Debug)]
104123
pub struct Definitions {
105124
table: DefPathTable,
106-
next_disambiguator: UnordMap<(LocalDefId, DefPathData), u32>,
107125
}
108126

109127
/// A unique identifier that we can use to lookup a definition
@@ -173,7 +191,11 @@ impl DisambiguatedDefPathData {
173191
}
174192
}
175193
DefPathDataName::Anon { namespace } => {
176-
write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
194+
if let DefPathData::AnonAssocTy(method) = self.data {
195+
write!(writer, "{}::{{{}#{}}}", method, namespace, self.disambiguator)
196+
} else {
197+
write!(writer, "{{{}#{}}}", namespace, self.disambiguator)
198+
}
177199
}
178200
}
179201
}
@@ -288,7 +310,7 @@ pub enum DefPathData {
288310
/// Argument position `impl Trait` have a `TypeNs` with their pretty-printed name.
289311
OpaqueTy,
290312
/// An anonymous associated type from an RPITIT.
291-
AnonAssocTy,
313+
AnonAssocTy(Symbol),
292314
/// A synthetic body for a coroutine's by-move body.
293315
SyntheticCoroutineBody,
294316
}
@@ -342,24 +364,33 @@ impl Definitions {
342364
let root = LocalDefId { local_def_index: table.allocate(key, def_path_hash) };
343365
assert_eq!(root.local_def_index, CRATE_DEF_INDEX);
344366

345-
Definitions { table, next_disambiguator: Default::default() }
367+
Definitions { table }
346368
}
347369

348-
/// Adds a definition with a parent definition.
349-
pub fn create_def(&mut self, parent: LocalDefId, data: DefPathData) -> LocalDefId {
370+
/// Creates a definition with a parent definition.
371+
/// If there are multiple definitions with the same DefPathData and the same parent, use
372+
/// `disambiguator` to differentiate them. Distinct `DisambiguatorState` instances are not
373+
/// guaranteed to generate unique disambiguators and should instead ensure that the `parent`
374+
/// and `data` pair is distinct from other instances.
375+
pub fn create_def(
376+
&mut self,
377+
parent: LocalDefId,
378+
data: DefPathData,
379+
disambiguator: &mut DisambiguatorState,
380+
) -> LocalDefId {
350381
// We can't use `Debug` implementation for `LocalDefId` here, since it tries to acquire a
351382
// reference to `Definitions` and we're already holding a mutable reference.
352383
debug!(
353384
"create_def(parent={}, data={data:?})",
354385
self.def_path(parent).to_string_no_crate_verbose(),
355386
);
356387

357-
// The root node must be created with `create_root_def()`.
388+
// The root node must be created in `new()`.
358389
assert!(data != DefPathData::CrateRoot);
359390

360391
// Find the next free disambiguator for this key.
361392
let disambiguator = {
362-
let next_disamb = self.next_disambiguator.entry((parent, data)).or_insert(0);
393+
let next_disamb = disambiguator.next.entry((parent, data)).or_insert(0);
363394
let disambiguator = *next_disamb;
364395
*next_disamb = next_disamb.checked_add(1).expect("disambiguator overflow");
365396
disambiguator
@@ -411,7 +442,9 @@ impl DefPathData {
411442
pub fn get_opt_name(&self) -> Option<Symbol> {
412443
use self::DefPathData::*;
413444
match *self {
414-
TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
445+
TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) | AnonAssocTy(name) => {
446+
Some(name)
447+
}
415448

416449
Impl
417450
| ForeignMod
@@ -422,7 +455,6 @@ impl DefPathData {
422455
| Ctor
423456
| AnonConst
424457
| OpaqueTy
425-
| AnonAssocTy
426458
| SyntheticCoroutineBody => None,
427459
}
428460
}
@@ -443,7 +475,7 @@ impl DefPathData {
443475
Ctor => DefPathDataName::Anon { namespace: sym::constructor },
444476
AnonConst => DefPathDataName::Anon { namespace: sym::constant },
445477
OpaqueTy => DefPathDataName::Anon { namespace: sym::opaque },
446-
AnonAssocTy => DefPathDataName::Anon { namespace: sym::anon_assoc },
478+
AnonAssocTy(..) => DefPathDataName::Anon { namespace: sym::anon_assoc },
447479
SyntheticCoroutineBody => DefPathDataName::Anon { namespace: sym::synthetic },
448480
}
449481
}

compiler/rustc_hir_analysis/src/collect/resolve_bound_vars.rs

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use rustc_ast::visit::walk_list;
1414
use rustc_data_structures::fx::{FxHashSet, FxIndexMap, FxIndexSet};
1515
use rustc_errors::ErrorGuaranteed;
1616
use rustc_hir::def::{DefKind, Res};
17+
use rustc_hir::definitions::DisambiguatorState;
1718
use rustc_hir::intravisit::{self, InferKind, Visitor, VisitorExt};
1819
use rustc_hir::{
1920
self as hir, AmbigArg, GenericArg, GenericParam, GenericParamKind, HirId, LifetimeKind, Node,
@@ -63,6 +64,7 @@ impl ResolvedArg {
6364
struct BoundVarContext<'a, 'tcx> {
6465
tcx: TyCtxt<'tcx>,
6566
rbv: &'a mut ResolveBoundVars,
67+
disambiguator: &'a mut DisambiguatorState,
6668
scope: ScopeRef<'a>,
6769
}
6870

@@ -245,8 +247,12 @@ pub(crate) fn provide(providers: &mut Providers) {
245247
#[instrument(level = "debug", skip(tcx))]
246248
fn resolve_bound_vars(tcx: TyCtxt<'_>, local_def_id: hir::OwnerId) -> ResolveBoundVars {
247249
let mut rbv = ResolveBoundVars::default();
248-
let mut visitor =
249-
BoundVarContext { tcx, rbv: &mut rbv, scope: &Scope::Root { opt_parent_item: None } };
250+
let mut visitor = BoundVarContext {
251+
tcx,
252+
rbv: &mut rbv,
253+
scope: &Scope::Root { opt_parent_item: None },
254+
disambiguator: &mut DisambiguatorState::new(),
255+
};
250256
match tcx.hir_owner_node(local_def_id) {
251257
hir::OwnerNode::Item(item) => visitor.visit_item(item),
252258
hir::OwnerNode::ForeignItem(item) => visitor.visit_foreign_item(item),
@@ -515,9 +521,10 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
515521

516522
let capture_all_in_scope_lifetimes = opaque_captures_all_in_scope_lifetimes(opaque);
517523
if capture_all_in_scope_lifetimes {
524+
let tcx = self.tcx;
518525
let lifetime_ident = |def_id: LocalDefId| {
519-
let name = self.tcx.item_name(def_id.to_def_id());
520-
let span = self.tcx.def_span(def_id);
526+
let name = tcx.item_name(def_id.to_def_id());
527+
let span = tcx.def_span(def_id);
521528
Ident::new(name, span)
522529
};
523530

@@ -1091,8 +1098,8 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
10911098
where
10921099
F: for<'b> FnOnce(&mut BoundVarContext<'b, 'tcx>),
10931100
{
1094-
let BoundVarContext { tcx, rbv, .. } = self;
1095-
let mut this = BoundVarContext { tcx: *tcx, rbv, scope: &wrap_scope };
1101+
let BoundVarContext { tcx, rbv, disambiguator, .. } = self;
1102+
let mut this = BoundVarContext { tcx: *tcx, rbv, disambiguator, scope: &wrap_scope };
10961103
let span = debug_span!("scope", scope = ?this.scope.debug_truncated());
10971104
{
10981105
let _enter = span.enter();
@@ -1446,7 +1453,7 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
14461453

14471454
#[instrument(level = "trace", skip(self, opaque_capture_scopes), ret)]
14481455
fn remap_opaque_captures(
1449-
&self,
1456+
&mut self,
14501457
opaque_capture_scopes: &Vec<(LocalDefId, &RefCell<FxIndexMap<ResolvedArg, LocalDefId>>)>,
14511458
mut lifetime: ResolvedArg,
14521459
ident: Ident,
@@ -1462,8 +1469,13 @@ impl<'a, 'tcx> BoundVarContext<'a, 'tcx> {
14621469
for &(opaque_def_id, captures) in opaque_capture_scopes.iter().rev() {
14631470
let mut captures = captures.borrow_mut();
14641471
let remapped = *captures.entry(lifetime).or_insert_with(|| {
1465-
let feed =
1466-
self.tcx.create_def(opaque_def_id, Some(ident.name), DefKind::LifetimeParam);
1472+
let feed = self.tcx.create_def(
1473+
opaque_def_id,
1474+
Some(ident.name),
1475+
DefKind::LifetimeParam,
1476+
None,
1477+
&mut self.disambiguator,
1478+
);
14671479
feed.def_span(ident.span);
14681480
feed.def_ident_span(Some(ident.span));
14691481
feed.def_id()

compiler/rustc_middle/src/ty/context.rs

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use rustc_errors::{
3434
};
3535
use rustc_hir::def::{CtorKind, DefKind};
3636
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId};
37-
use rustc_hir::definitions::Definitions;
37+
use rustc_hir::definitions::{DefPathData, Definitions, DisambiguatorState};
3838
use rustc_hir::intravisit::VisitorExt;
3939
use rustc_hir::lang_items::LangItem;
4040
use rustc_hir::{self as hir, Attribute, HirId, Node, TraitCandidate};
@@ -1957,8 +1957,10 @@ impl<'tcx> TyCtxtAt<'tcx> {
19571957
parent: LocalDefId,
19581958
name: Option<Symbol>,
19591959
def_kind: DefKind,
1960+
def_path_data: Option<DefPathData>,
1961+
disambiguator: &mut DisambiguatorState,
19601962
) -> TyCtxtFeed<'tcx, LocalDefId> {
1961-
let feed = self.tcx.create_def(parent, name, def_kind);
1963+
let feed = self.tcx.create_def(parent, name, def_kind, def_path_data, disambiguator);
19621964

19631965
feed.def_span(self.span);
19641966
feed
@@ -1972,8 +1974,10 @@ impl<'tcx> TyCtxt<'tcx> {
19721974
parent: LocalDefId,
19731975
name: Option<Symbol>,
19741976
def_kind: DefKind,
1977+
def_path_data: Option<DefPathData>,
1978+
disambiguator: &mut DisambiguatorState,
19751979
) -> TyCtxtFeed<'tcx, LocalDefId> {
1976-
let data = def_kind.def_path_data(name);
1980+
let data = def_path_data.unwrap_or_else(|| def_kind.def_path_data(name));
19771981
// The following call has the side effect of modifying the tables inside `definitions`.
19781982
// These very tables are relied on by the incr. comp. engine to decode DepNodes and to
19791983
// decode the on-disk cache.
@@ -1983,12 +1987,7 @@ impl<'tcx> TyCtxt<'tcx> {
19831987
// - has been created by this call to `create_def`.
19841988
// As a consequence, this LocalDefId is always re-created before it is needed by the incr.
19851989
// comp. engine itself.
1986-
//
1987-
// This call also writes to the value of the `source_span` query.
1988-
// This is fine because:
1989-
// - that query is `eval_always` so we won't miss its result changing;
1990-
// - this write will have happened before that query is called.
1991-
let def_id = self.untracked.definitions.write().create_def(parent, data);
1990+
let def_id = self.untracked.definitions.write().create_def(parent, data, disambiguator);
19921991

19931992
// This function modifies `self.definitions` using a side-effect.
19941993
// We need to ensure that these side effects are re-run by the incr. comp. engine.

0 commit comments

Comments
 (0)