Make with_hir_id_owner responsible for registering the item.

This commit is contained in:
Camille GILLOT 2021-07-16 10:16:23 +02:00
parent c1bac9229a
commit a1a35576eb
3 changed files with 94 additions and 143 deletions

View File

@ -327,7 +327,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let mut generic_args = vec![];
for (idx, arg) in args.into_iter().enumerate() {
if legacy_args_idx.contains(&idx) {
let parent_def_id = self.current_hir_id_owner.0;
let parent_def_id = self.current_hir_id_owner;
let node_id = self.resolver.next_node_id();
// Add a definition for the in-band const def.

View File

@ -40,12 +40,9 @@ impl ItemLowerer<'_, '_, '_> {
impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
fn visit_item(&mut self, item: &'a Item) {
self.lctx.allocate_hir_id_counter(item.id);
let hir_id = self.lctx.with_hir_id_owner(item.id, |lctx| {
lctx.without_in_scope_lifetime_defs(|lctx| {
let hir_item = lctx.lower_item(item);
lctx.insert_item(hir_item)
})
let node = lctx.without_in_scope_lifetime_defs(|lctx| lctx.lower_item(item));
hir::OwnerNode::Item(node)
});
self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
@ -72,26 +69,17 @@ impl<'a> Visitor<'a> for ItemLowerer<'a, '_, '_> {
}
fn visit_assoc_item(&mut self, item: &'a AssocItem, ctxt: AssocCtxt) {
self.lctx.allocate_hir_id_counter(item.id);
self.lctx.with_hir_id_owner(item.id, |lctx| match ctxt {
AssocCtxt::Trait => {
let hir_item = lctx.lower_trait_item(item);
lctx.insert_trait_item(hir_item);
}
AssocCtxt::Impl => {
let hir_item = lctx.lower_impl_item(item);
lctx.insert_impl_item(hir_item);
}
AssocCtxt::Trait => hir::OwnerNode::TraitItem(lctx.lower_trait_item(item)),
AssocCtxt::Impl => hir::OwnerNode::ImplItem(lctx.lower_impl_item(item)),
});
visit::walk_assoc_item(self, item, ctxt);
}
fn visit_foreign_item(&mut self, item: &'a ForeignItem) {
self.lctx.allocate_hir_id_counter(item.id);
self.lctx.with_hir_id_owner(item.id, |lctx| {
let hir_item = lctx.lower_foreign_item(item);
lctx.insert_foreign_item(hir_item);
hir::OwnerNode::ForeignItem(lctx.lower_foreign_item(item))
});
visit::walk_foreign_item(self, item);
@ -106,12 +94,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
// only used when lowering a child item of a trait or impl.
fn with_parent_item_lifetime_defs<T>(
&mut self,
parent_hir_id: hir::ItemId,
parent_hir_id: LocalDefId,
f: impl FnOnce(&mut Self) -> T,
) -> T {
let old_len = self.in_scope_lifetimes.len();
let parent_generics = match self.owners[parent_hir_id.def_id].unwrap().expect_item().kind {
let parent_generics = match self.owners[parent_hir_id].unwrap().expect_item().kind {
hir::ItemKind::Impl(hir::Impl { ref generics, .. })
| hir::ItemKind::Trait(_, _, ref generics, ..) => generics.params,
_ => &[],
@ -186,19 +174,20 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
}
pub fn lower_item(&mut self, i: &Item) -> hir::Item<'hir> {
fn lower_item(&mut self, i: &Item) -> &'hir hir::Item<'hir> {
let mut ident = i.ident;
let mut vis = self.lower_visibility(&i.vis);
let hir_id = self.lower_node_id(i.id);
let attrs = self.lower_attrs(hir_id, &i.attrs);
let kind = self.lower_item_kind(i.span, i.id, hir_id, &mut ident, attrs, &mut vis, &i.kind);
hir::Item {
let item = hir::Item {
def_id: hir_id.expect_owner(),
ident: self.lower_ident(ident),
kind,
vis,
span: self.lower_span(i.span),
}
};
self.arena.alloc(item)
}
fn lower_item_kind(
@ -480,10 +469,16 @@ impl<'hir> LoweringContext<'_, 'hir> {
// Essentially a single `use` which imports two names is desugared into
// two imports.
for new_node_id in [id1, id2] {
// Associate an HirId to both ids even if there is no resolution.
let new_id = self.allocate_hir_id_counter(new_node_id);
let res = if let Some(res) = resolutions.next() { res } else { continue };
let new_id = self.resolver.local_def_id(new_node_id);
let res = if let Some(res) = resolutions.next() {
res
} else {
// Associate an HirId to both ids even if there is no resolution.
self.node_id_to_hir_id.ensure_contains_elem(new_node_id, || None);
debug_assert!(self.node_id_to_hir_id[new_node_id].is_none());
self.node_id_to_hir_id[new_node_id] = Some(hir::HirId::make_owner(new_id));
continue;
};
let ident = *ident;
let mut path = path.clone();
for seg in &mut path.segments {
@ -500,13 +495,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
this.attrs.insert(hir::HirId::make_owner(new_id), attrs);
}
this.insert_item(hir::Item {
let item = hir::Item {
def_id: new_id,
ident: this.lower_ident(ident),
kind,
vis,
span: this.lower_span(span),
});
};
hir::OwnerNode::Item(this.arena.alloc(item))
});
}
@ -550,7 +546,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
// Add all the nested `PathListItem`s to the HIR.
for &(ref use_tree, id) in trees {
let new_hir_id = self.allocate_hir_id_counter(id);
let new_hir_id = self.resolver.local_def_id(id);
let mut prefix = prefix.clone();
@ -574,13 +570,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
this.attrs.insert(hir::HirId::make_owner(new_hir_id), attrs);
}
this.insert_item(hir::Item {
let item = hir::Item {
def_id: new_hir_id,
ident: this.lower_ident(ident),
kind,
vis,
span: this.lower_span(use_tree.span),
});
};
hir::OwnerNode::Item(this.arena.alloc(item))
});
}
@ -647,11 +644,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
respan(self.lower_span(vis.span), vis_kind)
}
fn lower_foreign_item(&mut self, i: &ForeignItem) -> hir::ForeignItem<'hir> {
fn lower_foreign_item(&mut self, i: &ForeignItem) -> &'hir hir::ForeignItem<'hir> {
let hir_id = self.lower_node_id(i.id);
let def_id = hir_id.expect_owner();
self.lower_attrs(hir_id, &i.attrs);
hir::ForeignItem {
let item = hir::ForeignItem {
def_id,
ident: self.lower_ident(i.ident),
kind: match i.kind {
@ -681,12 +678,13 @@ impl<'hir> LoweringContext<'_, 'hir> {
},
vis: self.lower_visibility(&i.vis),
span: self.lower_span(i.span),
}
};
self.arena.alloc(item)
}
fn lower_foreign_item_ref(&mut self, i: &ForeignItem) -> hir::ForeignItemRef {
hir::ForeignItemRef {
id: hir::ForeignItemId { def_id: self.allocate_hir_id_counter(i.id) },
id: hir::ForeignItemId { def_id: self.resolver.local_def_id(i.id) },
ident: self.lower_ident(i.ident),
span: self.lower_span(i.span),
}
@ -761,7 +759,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
}
}
fn lower_trait_item(&mut self, i: &AssocItem) -> hir::TraitItem<'hir> {
fn lower_trait_item(&mut self, i: &AssocItem) -> &'hir hir::TraitItem<'hir> {
let hir_id = self.lower_node_id(i.id);
let trait_item_def_id = hir_id.expect_owner();
@ -804,13 +802,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
};
self.lower_attrs(hir_id, &i.attrs);
hir::TraitItem {
let item = hir::TraitItem {
def_id: trait_item_def_id,
ident: self.lower_ident(i.ident),
generics,
kind,
span: self.lower_span(i.span),
}
};
self.arena.alloc(item)
}
fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
@ -840,7 +839,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
self.expr(span, hir::ExprKind::Err, AttrVec::new())
}
fn lower_impl_item(&mut self, i: &AssocItem) -> hir::ImplItem<'hir> {
fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
let impl_item_def_id = self.resolver.local_def_id(i.id);
let (generics, kind) = match &i.kind {
@ -894,7 +893,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
let hir_id = self.lower_node_id(i.id);
self.lower_attrs(hir_id, &i.attrs);
hir::ImplItem {
let item = hir::ImplItem {
def_id: hir_id.expect_owner(),
ident: self.lower_ident(i.ident),
generics,
@ -902,7 +901,8 @@ impl<'hir> LoweringContext<'_, 'hir> {
defaultness,
kind,
span: self.lower_span(i.span),
}
};
self.arena.alloc(item)
}
fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
@ -910,7 +910,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
let has_value = true;
let (defaultness, _) = self.lower_defaultness(i.kind.defaultness(), has_value);
hir::ImplItemRef {
id: hir::ImplItemId { def_id: self.allocate_hir_id_counter(i.id) },
id: hir::ImplItemId { def_id: self.resolver.local_def_id(i.id) },
ident: self.lower_ident(i.ident),
span: self.lower_span(i.span),
defaultness,

View File

@ -148,8 +148,8 @@ struct LoweringContext<'a, 'hir: 'a> {
/// vector.
in_scope_lifetimes: Vec<ParamName>,
current_hir_id_owner: (LocalDefId, u32),
item_local_id_counters: IndexVec<LocalDefId, u32>,
current_hir_id_owner: LocalDefId,
item_local_id_counter: hir::ItemLocalId,
node_id_to_hir_id: IndexVec<NodeId, Option<hir::HirId>>,
allow_try_trait: Option<Lrc<[Symbol]>>,
@ -328,8 +328,8 @@ pub fn lower_crate<'a, 'hir>(
is_in_trait_impl: false,
is_in_dyn_type: false,
anonymous_lifetime_mode: AnonymousLifetimeMode::PassThrough,
current_hir_id_owner: (CRATE_DEF_ID, 0),
item_local_id_counters: Default::default(),
current_hir_id_owner: CRATE_DEF_ID,
item_local_id_counter: hir::ItemLocalId::new(0),
node_id_to_hir_id: IndexVec::new(),
generator_kind: None,
task_context: None,
@ -410,15 +410,15 @@ enum AnonymousLifetimeMode {
impl<'a, 'hir> LoweringContext<'a, 'hir> {
fn lower_crate(mut self, c: &Crate) -> &'hir hir::Crate<'hir> {
self.lower_node_id(CRATE_NODE_ID);
debug_assert!(self.node_id_to_hir_id[CRATE_NODE_ID] == Some(hir::CRATE_HIR_ID));
debug_assert_eq!(self.resolver.local_def_id(CRATE_NODE_ID), CRATE_DEF_ID);
visit::walk_crate(&mut item::ItemLowerer { lctx: &mut self }, c);
let module = self.arena.alloc(self.lower_mod(&c.items, c.span));
self.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
self.owners.ensure_contains_elem(CRATE_DEF_ID, || None);
self.owners[CRATE_DEF_ID] = Some(hir::OwnerNode::Crate(module));
self.with_hir_id_owner(CRATE_NODE_ID, |lctx| {
let module = lctx.lower_mod(&c.items, c.span);
lctx.lower_attrs(hir::CRATE_HIR_ID, &c.attrs);
hir::OwnerNode::Crate(lctx.arena.alloc(module))
});
let mut trait_map: FxHashMap<_, FxHashMap<_, _>> = FxHashMap::default();
for (k, v) in self.resolver.take_trait_map().into_iter() {
@ -454,38 +454,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.arena.alloc(krate)
}
fn insert_item(&mut self, item: hir::Item<'hir>) -> hir::ItemId {
let id = item.item_id();
let item = self.arena.alloc(item);
self.owners.ensure_contains_elem(id.def_id, || None);
self.owners[id.def_id] = Some(hir::OwnerNode::Item(item));
id
}
fn insert_foreign_item(&mut self, item: hir::ForeignItem<'hir>) -> hir::ForeignItemId {
let id = item.foreign_item_id();
let item = self.arena.alloc(item);
self.owners.ensure_contains_elem(id.def_id, || None);
self.owners[id.def_id] = Some(hir::OwnerNode::ForeignItem(item));
id
}
fn insert_impl_item(&mut self, item: hir::ImplItem<'hir>) -> hir::ImplItemId {
let id = item.impl_item_id();
let item = self.arena.alloc(item);
self.owners.ensure_contains_elem(id.def_id, || None);
self.owners[id.def_id] = Some(hir::OwnerNode::ImplItem(item));
id
}
fn insert_trait_item(&mut self, item: hir::TraitItem<'hir>) -> hir::TraitItemId {
let id = item.trait_item_id();
let item = self.arena.alloc(item);
self.owners.ensure_contains_elem(id.def_id, || None);
self.owners[id.def_id] = Some(hir::OwnerNode::TraitItem(item));
id
}
fn create_stable_hashing_context(&self) -> LoweringHasher<'_> {
LoweringHasher {
source_map: CachingSourceMapView::new(self.sess.source_map()),
@ -493,46 +461,35 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
}
fn allocate_hir_id_counter(&mut self, owner: NodeId) -> LocalDefId {
// Set up the counter if needed.
fn with_hir_id_owner(
&mut self,
owner: NodeId,
f: impl FnOnce(&mut Self) -> hir::OwnerNode<'hir>,
) -> LocalDefId {
let def_id = self.resolver.local_def_id(owner);
// Always allocate the first `HirId` for the owner itself.
self.node_id_to_hir_id.ensure_contains_elem(owner, || None);
if let Some(_lowered) = self.node_id_to_hir_id[owner] {
debug_assert_eq!(_lowered.owner, def_id);
debug_assert_eq!(_lowered.local_id.as_u32(), 0);
} else {
self.item_local_id_counters.ensure_contains_elem(def_id, || 0);
let local_id_counter = &mut self.item_local_id_counters[def_id];
let local_id = *local_id_counter;
// We want to be sure not to modify the counter in the map while it
// is also on the stack. Otherwise we'll get lost updates when writing
// back from the stack to the map.
debug_assert_eq!(local_id, 0);
*local_id_counter += 1;
self.node_id_to_hir_id[owner] = Some(hir::HirId::make_owner(def_id));
panic!("with_hir_id_owner must not be called multiple times on owner {:?}", def_id);
}
self.node_id_to_hir_id[owner] = Some(hir::HirId::make_owner(def_id));
let current_owner = std::mem::replace(&mut self.current_hir_id_owner, def_id);
let current_local_counter =
std::mem::replace(&mut self.item_local_id_counter, hir::ItemLocalId::new(1));
let item = f(self);
self.current_hir_id_owner = current_owner;
self.item_local_id_counter = current_local_counter;
self.owners.ensure_contains_elem(def_id, || None);
self.owners[def_id] = Some(item);
def_id
}
fn with_hir_id_owner<T>(&mut self, owner: NodeId, f: impl FnOnce(&mut Self) -> T) -> T {
let def_id = self.resolver.local_def_id(owner);
let counter = self.item_local_id_counters[def_id];
let old_owner = std::mem::replace(&mut self.current_hir_id_owner, (def_id, counter));
let ret = f(self);
let (new_def_id, new_counter) =
std::mem::replace(&mut self.current_hir_id_owner, old_owner);
debug_assert!(def_id == new_def_id);
debug_assert!(new_counter >= counter);
self.item_local_id_counters[def_id] = new_counter;
ret
}
/// This method allocates a new `HirId` for the given `NodeId` and stores it in
/// the `LoweringContext`'s `NodeId => HirId` map.
/// Take care not to call this method if the resulting `HirId` is then not
@ -547,10 +504,10 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
existing_hir_id
} else {
// Generate a new `HirId`.
let &mut (owner, ref mut local_id_counter) = &mut self.current_hir_id_owner;
let local_id = *local_id_counter;
*local_id_counter += 1;
let hir_id = hir::HirId { owner, local_id: hir::ItemLocalId::from_u32(local_id) };
let owner = self.current_hir_id_owner;
let local_id = self.item_local_id_counter;
self.item_local_id_counter.increment_by(1);
let hir_id = hir::HirId { owner, local_id };
self.node_id_to_hir_id[ast_node_id] = Some(hir_id);
hir_id
}
@ -626,7 +583,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
/// Mark a span as relative to the current owning item.
fn lower_span(&self, span: Span) -> Span {
if self.sess.opts.debugging_opts.incremental_relative_spans {
span.with_parent(Some(self.current_hir_id_owner.0))
span.with_parent(Some(self.current_hir_id_owner))
} else {
// Do not make spans relative when not using incremental compilation.
span
@ -799,7 +756,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// wouldn't have been added yet.
let generics = this.lower_generics_mut(
generics,
ImplTraitContext::Universal(&mut params, this.current_hir_id_owner.0),
ImplTraitContext::Universal(&mut params, this.current_hir_id_owner),
);
let res = f(this, &mut params);
(params, (generics, res))
@ -1005,7 +962,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
}
AssocTyConstraintKind::Bound { ref bounds } => {
let mut capturable_lifetimes;
let mut parent_def_id = self.current_hir_id_owner.0;
let mut parent_def_id = self.current_hir_id_owner;
// Piggy-back on the `impl Trait` context to figure out the correct behavior.
let (desugar_to_impl_trait, itctx) = match itctx {
// We are in the return position:
@ -1133,7 +1090,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// Construct an AnonConst where the expr is the "ty"'s path.
let parent_def_id = self.current_hir_id_owner.0;
let parent_def_id = self.current_hir_id_owner;
let node_id = self.resolver.next_node_id();
// Add a definition for the in-band const def.
@ -1399,12 +1356,13 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// frequently opened issues show.
let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::OpaqueTy, span, None);
let opaque_ty_def_id = self.allocate_hir_id_counter(opaque_ty_node_id);
let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
let collected_lifetimes = self.with_hir_id_owner(opaque_ty_node_id, move |lctx| {
let mut collected_lifetimes = Vec::new();
self.with_hir_id_owner(opaque_ty_node_id, |lctx| {
let hir_bounds = lower_bounds(lctx);
let collected_lifetimes = lifetimes_from_impl_trait_bounds(
collected_lifetimes = lifetimes_from_impl_trait_bounds(
opaque_ty_node_id,
&hir_bounds,
capturable_lifetimes,
@ -1457,9 +1415,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
};
trace!("lower_opaque_impl_trait: {:#?}", opaque_ty_def_id);
lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
collected_lifetimes
lctx.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
});
let lifetimes =
@ -1481,7 +1437,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
opaque_ty_item: hir::OpaqueTy<'hir>,
span: Span,
opaque_ty_span: Span,
) {
) -> hir::OwnerNode<'hir> {
let opaque_ty_item_kind = hir::ItemKind::OpaqueTy(opaque_ty_item);
// Generate an `type Foo = impl Trait;` declaration.
trace!("registering opaque type with id {:#?}", opaque_ty_id);
@ -1492,11 +1448,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
vis: respan(self.lower_span(span.shrink_to_lo()), hir::VisibilityKind::Inherited),
span: self.lower_span(opaque_ty_span),
};
// Insert the item into the global item list. This usually happens
// automatically for all AST items. But this opaque type item
// does not actually exist in the AST.
self.insert_item(opaque_ty_item);
hir::OwnerNode::Item(self.arena.alloc(opaque_ty_item))
}
fn lower_fn_params_to_names(&mut self, decl: &FnDecl) -> &'hir [Ident] {
@ -1565,7 +1517,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
if let Some((_, ibty)) = &mut in_band_ty_params {
this.lower_ty_direct(
&param.ty,
ImplTraitContext::Universal(ibty, this.current_hir_id_owner.0),
ImplTraitContext::Universal(ibty, this.current_hir_id_owner),
)
} else {
this.lower_ty_direct(&param.ty, ImplTraitContext::disallowed())
@ -1656,7 +1608,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let opaque_ty_span = self.mark_span_with_reason(DesugaringKind::Async, span, None);
let opaque_ty_def_id = self.allocate_hir_id_counter(opaque_ty_node_id);
let opaque_ty_def_id = self.resolver.local_def_id(opaque_ty_node_id);
// When we create the opaque type for this async fn, it is going to have
// to capture all the lifetimes involved in the signature (including in the
@ -1706,7 +1658,8 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
// grow.
let input_lifetimes_count = self.in_scope_lifetimes.len() + self.lifetimes_to_define.len();
let lifetime_params = self.with_hir_id_owner(opaque_ty_node_id, |this| {
let mut lifetime_params = Vec::new();
self.with_hir_id_owner(opaque_ty_node_id, |this| {
// We have to be careful to get elision right here. The
// idea is that we create a lifetime parameter for each
// lifetime in the return type. So, given a return type
@ -1728,7 +1681,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
//
// Note: this must be done after lowering the output type,
// as the output type may introduce new in-band lifetimes.
let lifetime_params: Vec<(Span, ParamName)> = this
lifetime_params = this
.in_scope_lifetimes
.iter()
.cloned()
@ -1757,9 +1710,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
};
trace!("exist ty from async fn def id: {:#?}", opaque_ty_def_id);
this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span);
lifetime_params
this.generate_opaque_type(opaque_ty_def_id, opaque_ty_item, span, opaque_ty_span)
});
// As documented above on the variable