Skip to content

Commit 04d5f41

Browse files
cjgillotspastorino
authored andcommitted
Make node_id_to_hir_id owner-local.
1 parent 30b3f35 commit 04d5f41

File tree

3 files changed

+53
-36
lines changed

3 files changed

+53
-36
lines changed

compiler/rustc_ast_lowering/src/item.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -473,10 +473,6 @@ impl<'hir> LoweringContext<'_, 'hir> {
473473
let new_id = self.resolver.local_def_id(new_node_id);
474474
let Some(res) = resolutions.next() else {
475475
// Associate an HirId to both ids even if there is no resolution.
476-
let _old = self
477-
.node_id_to_hir_id
478-
.insert(new_node_id, hir::HirId::make_owner(new_id));
479-
debug_assert!(_old.is_none());
480476
self.owners.ensure_contains_elem(new_id, || hir::MaybeOwner::Phantom);
481477
let _old = std::mem::replace(
482478
&mut self.owners[new_id],

compiler/rustc_ast_lowering/src/lib.rs

Lines changed: 40 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ use rustc_ast::{self as ast, *};
4444
use rustc_ast_pretty::pprust;
4545
use rustc_data_structures::captures::Captures;
4646
use rustc_data_structures::fingerprint::Fingerprint;
47-
use rustc_data_structures::fx::FxHashSet;
47+
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
4848
use rustc_data_structures::sorted_map::SortedMap;
4949
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
5050
use rustc_data_structures::sync::Lrc;
@@ -67,6 +67,7 @@ use rustc_span::symbol::{kw, sym, Ident, Symbol};
6767
use rustc_span::{Span, DUMMY_SP};
6868

6969
use smallvec::SmallVec;
70+
use std::collections::hash_map::Entry;
7071
use tracing::{debug, trace};
7172

7273
macro_rules! arena_vec {
@@ -154,10 +155,9 @@ struct LoweringContext<'a, 'hir: 'a> {
154155

155156
current_hir_id_owner: LocalDefId,
156157
item_local_id_counter: hir::ItemLocalId,
157-
node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
158158

159159
/// NodeIds that are lowered inside the current HIR owner.
160-
local_node_ids: Vec<NodeId>,
160+
node_id_to_local_id: FxHashMap<NodeId, hir::ItemLocalId>,
161161

162162
allow_try_trait: Option<Lrc<[Symbol]>>,
163163
allow_gen_future: Option<Lrc<[Symbol]>>,
@@ -311,8 +311,7 @@ pub fn lower_crate<'a, 'hir>(
311311
anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
312312
current_hir_id_owner: CRATE_DEF_ID,
313313
item_local_id_counter: hir::ItemLocalId::new(0),
314-
node_id_to_hir_id: IndexVec::new(),
315-
local_node_ids: Vec::new(),
314+
node_id_to_local_id: FxHashMap::default(),
316315
generator_kind: None,
317316
task_context: None,
318317
current_item: None,
@@ -439,23 +438,22 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
439438

440439
let current_attrs = std::mem::take(&mut self.attrs);
441440
let current_bodies = std::mem::take(&mut self.bodies);
442-
let current_node_ids = std::mem::take(&mut self.local_node_ids);
441+
let current_node_ids = std::mem::take(&mut self.node_id_to_local_id);
443442
let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
444443
let current_local_counter =
445444
std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
446445

447446
// Always allocate the first `HirId` for the owner itself.
448-
let _old = self.node_id_to_hir_id.insert(owner, hir::HirId::make_owner(def_id));
447+
let _old = self.node_id_to_local_id.insert(owner, hir::ItemLocalId::new(0));
449448
debug_assert_eq!(_old, None);
450-
self.local_node_ids.push(owner);
451449

452450
let item = f(self);
453451
debug_assert_eq!(def_id, item.def_id());
454452
let info = self.make_owner_info(item);
455453

456454
self.attrs = current_attrs;
457455
self.bodies = current_bodies;
458-
self.local_node_ids = current_node_ids;
456+
self.node_id_to_local_id = current_node_ids;
459457
self.current_hir_id_owner = current_owner;
460458
self.item_local_id_counter = current_local_counter;
461459

@@ -468,32 +466,32 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
468466
fn make_owner_info(&mut self, node: hir::OwnerNode<'hir>) -> hir::OwnerInfo<'hir> {
469467
let attrs = std::mem::take(&mut self.attrs);
470468
let mut bodies = std::mem::take(&mut self.bodies);
471-
let local_node_ids = std::mem::take(&mut self.local_node_ids);
469+
let node_id_to_local_id = std::mem::take(&mut self.node_id_to_local_id);
472470

473-
let local_id_to_def_id = local_node_ids
471+
let local_id_to_def_id = node_id_to_local_id
474472
.iter()
475-
.filter_map(|&node_id| {
476-
let hir_id = self.node_id_to_hir_id[node_id]?;
477-
if hir_id.local_id == hir::ItemLocalId::new(0) {
473+
.filter_map(|(&node_id, &local_id)| {
474+
if local_id == hir::ItemLocalId::new(0) {
478475
None
479476
} else {
480477
let def_id = self.resolver.opt_local_def_id(node_id)?;
478+
481479
self.owners.ensure_contains_elem(def_id, || hir::MaybeOwner::Phantom);
482480
if let o @ hir::MaybeOwner::Phantom = &mut self.owners[def_id] {
483481
// Do not override a `MaybeOwner::Owner` that may already here.
482+
let hir_id = hir::HirId { owner: self.current_hir_id_owner, local_id };
484483
*o = hir::MaybeOwner::NonOwner(hir_id);
485484
}
486-
Some((hir_id.local_id, def_id))
485+
Some((local_id, def_id))
487486
}
488487
})
489488
.collect();
490489

491-
let trait_map = local_node_ids
490+
let trait_map = node_id_to_local_id
492491
.into_iter()
493-
.filter_map(|node_id| {
494-
let hir_id = self.node_id_to_hir_id[node_id]?;
492+
.filter_map(|(node_id, local_id)| {
495493
let traits = self.resolver.take_trait_map(node_id)?;
496-
Some((hir_id.local_id, traits.into_boxed_slice()))
494+
Some((local_id, traits.into_boxed_slice()))
497495
})
498496
.collect();
499497

@@ -558,14 +556,18 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
558556
fn lower_node_id(&mut self, ast_node_id: NodeId) -> hir::HirId {
559557
assert_ne!(ast_node_id, DUMMY_NODE_ID);
560558

561-
*self.node_id_to_hir_id.get_or_insert_with(ast_node_id, || {
562-
// Generate a new `HirId`.
563-
let owner = self.current_hir_id_owner;
564-
let local_id = self.item_local_id_counter;
565-
self.item_local_id_counter.increment_by(1);
566-
self.local_node_ids.push(ast_node_id);
567-
hir::HirId { owner, local_id }
568-
})
559+
let owner = self.current_hir_id_owner;
560+
let local_id = match self.node_id_to_local_id.entry(ast_node_id) {
561+
Entry::Occupied(o) => *o.get(),
562+
Entry::Vacant(v) => {
563+
// Generate a new `HirId`.
564+
let local_id = self.item_local_id_counter;
565+
self.item_local_id_counter.increment_by(1);
566+
v.insert(local_id);
567+
local_id
568+
}
569+
};
570+
hir::HirId { owner, local_id }
569571
}
570572

571573
fn next_id(&mut self) -> hir::HirId {
@@ -574,11 +576,17 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
574576
}
575577

576578
fn lower_res(&mut self, res: Res<NodeId>) -> Res {
577-
res.map_id(|id| {
578-
self.node_id_to_hir_id.get(id).copied().flatten().unwrap_or_else(|| {
579-
panic!("expected `NodeId` to be lowered already for res {:#?}", res);
580-
})
581-
})
579+
let res: Result<Res, ()> = res.apply_id(|id| {
580+
let owner = self.current_hir_id_owner;
581+
let local_id = self.node_id_to_local_id.get(&id).copied().ok_or(())?;
582+
Ok(hir::HirId { owner, local_id })
583+
});
584+
// We may fail to find a HirId when the Res points to a Local from an enclosing HIR owner.
585+
// This can happen when trying to lower the return type `x` in erroneous code like
586+
// async fn foo(x: u8) -> x {}
587+
// In that case, `x` is lowered as a function parameter, and the return type is lowered as
588+
// an opaque type as a synthetized HIR owner.
589+
res.unwrap_or(Res::Err)
582590
}
583591

584592
fn expect_full_res(&mut self, id: NodeId) -> Res<NodeId> {

compiler/rustc_hir/src/def.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -611,6 +611,19 @@ impl<Id> Res<Id> {
611611
}
612612
}
613613

614+
pub fn apply_id<R, E>(self, mut map: impl FnMut(Id) -> Result<R, E>) -> Result<Res<R>, E> {
615+
Ok(match self {
616+
Res::Def(kind, id) => Res::Def(kind, id),
617+
Res::SelfCtor(id) => Res::SelfCtor(id),
618+
Res::PrimTy(id) => Res::PrimTy(id),
619+
Res::Local(id) => Res::Local(map(id)?),
620+
Res::SelfTy { trait_, alias_to } => Res::SelfTy { trait_, alias_to },
621+
Res::ToolMod => Res::ToolMod,
622+
Res::NonMacroAttr(attr_kind) => Res::NonMacroAttr(attr_kind),
623+
Res::Err => Res::Err,
624+
})
625+
}
626+
614627
#[track_caller]
615628
pub fn expect_non_local<OtherId>(self) -> Res<OtherId> {
616629
self.map_id(|_| panic!("unexpected `Res::Local`"))

0 commit comments

Comments
 (0)