rust/compiler/rustc_ast_lowering/src/index.rs

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

423 lines
15 KiB
Rust
Raw Normal View History

2021-10-21 21:08:57 +00:00
use rustc_data_structures::sorted_map::SortedMap;
use rustc_hir as hir;
use rustc_hir::def_id::{LocalDefId, LocalDefIdMap};
use rustc_hir::intravisit::Visitor;
2020-01-07 13:38:27 +00:00
use rustc_hir::*;
use rustc_index::IndexVec;
2021-07-05 20:26:23 +00:00
use rustc_middle::span_bug;
use rustc_middle::ty::TyCtxt;
2021-02-28 17:58:50 +00:00
use rustc_span::{DUMMY_SP, Span};
use tracing::{debug, instrument};
/// A visitor that walks over the HIR and collects `Node`s into a HIR map.
2023-11-25 19:46:10 +00:00
struct NodeCollector<'a, 'hir> {
tcx: TyCtxt<'hir>,
2021-10-21 21:08:57 +00:00
bodies: &'a SortedMap<ItemLocalId, &'hir Body<'hir>>,
/// Outputs
nodes: IndexVec<ItemLocalId, ParentedNode<'hir>>,
parenting: LocalDefIdMap<ItemLocalId>,
2020-02-07 10:45:04 +00:00
/// The parent of this node
parent_node: ItemLocalId,
2019-02-03 08:14:31 +00:00
owner: OwnerId,
}
#[instrument(level = "debug", skip(tcx, bodies))]
pub(super) fn index_hir<'hir>(
tcx: TyCtxt<'hir>,
item: hir::OwnerNode<'hir>,
2021-10-21 21:08:57 +00:00
bodies: &SortedMap<ItemLocalId, &'hir Body<'hir>>,
num_nodes: usize,
) -> (IndexVec<ItemLocalId, ParentedNode<'hir>>, LocalDefIdMap<ItemLocalId>) {
let err_node = ParentedNode { parent: ItemLocalId::ZERO, node: Node::Err(item.span()) };
let mut nodes = IndexVec::from_elem_n(err_node, num_nodes);
// This node's parent should never be accessed: the owner's parent is computed by the
// hir_owner_parent query. Make it invalid (= ItemLocalId::MAX) to force an ICE whenever it is
// used.
nodes[ItemLocalId::ZERO] = ParentedNode { parent: ItemLocalId::INVALID, node: item.into() };
2021-02-28 19:23:10 +00:00
let mut collector = NodeCollector {
tcx,
owner: item.def_id(),
parent_node: ItemLocalId::ZERO,
nodes,
bodies,
parenting: Default::default(),
2021-02-28 19:23:10 +00:00
};
match item {
OwnerNode::Crate(citem) => {
collector.visit_mod(citem, citem.spans.inner_span, hir::CRATE_HIR_ID)
}
2021-02-28 19:23:10 +00:00
OwnerNode::Item(item) => collector.visit_item(item),
OwnerNode::TraitItem(item) => collector.visit_trait_item(item),
OwnerNode::ImplItem(item) => collector.visit_impl_item(item),
OwnerNode::ForeignItem(item) => collector.visit_foreign_item(item),
OwnerNode::Synthetic => unreachable!(),
2021-02-28 19:23:10 +00:00
};
for (local_id, node) in collector.nodes.iter_enumerated() {
if let Node::Err(span) = node.node {
let hir_id = HirId { owner: item.def_id(), local_id };
let msg = format!("ID {hir_id} not encountered when visiting item HIR");
tcx.dcx().span_delayed_bug(span, msg);
}
}
(collector.nodes, collector.parenting)
2021-02-28 19:23:10 +00:00
}
2021-02-28 19:23:10 +00:00
impl<'a, 'hir> NodeCollector<'a, 'hir> {
#[instrument(level = "debug", skip(self))]
fn insert(&mut self, span: Span, hir_id: HirId, node: Node<'hir>) {
2021-02-28 19:23:10 +00:00
debug_assert_eq!(self.owner, hir_id.owner);
2021-03-27 12:21:26 +00:00
debug_assert_ne!(hir_id.local_id.as_u32(), 0);
debug_assert_ne!(hir_id.local_id, self.parent_node);
// Make sure that the DepNode of some node coincides with the HirId
// owner of that node.
2024-09-11 17:32:53 +00:00
if cfg!(debug_assertions) && hir_id.owner != self.owner {
span_bug!(
span,
"inconsistent HirId at `{:?}` for `{:?}`: \
2020-04-13 16:52:40 +00:00
current_dep_node_owner={} ({:?}), hir_id.owner={} ({:?})",
2024-09-11 17:32:53 +00:00
self.tcx.sess.source_map().span_to_diagnostic_string(span),
node,
self.tcx
.definitions_untracked()
.def_path(self.owner.def_id)
.to_string_no_crate_verbose(),
self.owner,
self.tcx
.definitions_untracked()
.def_path(hir_id.owner.def_id)
.to_string_no_crate_verbose(),
hir_id.owner,
)
}
self.nodes[hir_id.local_id] = ParentedNode { parent: self.parent_node, node };
}
2016-04-14 05:24:30 +00:00
2019-02-06 13:16:11 +00:00
fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_node_id: HirId, f: F) {
2021-02-28 19:23:10 +00:00
debug_assert_eq!(parent_node_id.owner, self.owner);
2019-02-15 14:21:56 +00:00
let parent_node = self.parent_node;
2021-02-28 19:23:10 +00:00
self.parent_node = parent_node_id.local_id;
2016-04-14 05:24:30 +00:00
f(self);
2019-02-15 14:21:56 +00:00
self.parent_node = parent_node;
2016-04-14 05:24:30 +00:00
}
2021-03-05 19:09:33 +00:00
fn insert_nested(&mut self, item: LocalDefId) {
if self.parent_node != ItemLocalId::ZERO {
self.parenting.insert(item, self.parent_node);
}
2021-03-05 19:09:33 +00:00
}
}
2021-02-28 19:23:10 +00:00
impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
/// Because we want to track parent items and so forth, enable
/// deep walking so that we walk nested items in the context of
/// their outer items.
fn visit_nested_item(&mut self, item: ItemId) {
debug!("visit_nested_item: {:?}", item);
self.insert_nested(item.owner_id.def_id);
}
fn visit_nested_trait_item(&mut self, item_id: TraitItemId) {
self.insert_nested(item_id.owner_id.def_id);
}
fn visit_nested_impl_item(&mut self, item_id: ImplItemId) {
self.insert_nested(item_id.owner_id.def_id);
}
2020-11-11 20:57:54 +00:00
fn visit_nested_foreign_item(&mut self, foreign_id: ForeignItemId) {
self.insert_nested(foreign_id.owner_id.def_id);
2020-11-11 20:57:54 +00:00
}
fn visit_nested_body(&mut self, id: BodyId) {
2021-02-28 19:23:10 +00:00
debug_assert_eq!(id.hir_id.owner, self.owner);
2021-10-21 21:08:57 +00:00
let body = self.bodies[&id.hir_id.local_id];
2021-02-28 19:23:10 +00:00
self.visit_body(body);
2016-10-28 20:58:32 +00:00
}
2019-11-29 12:43:03 +00:00
fn visit_param(&mut self, param: &'hir Param<'hir>) {
let node = Node::Param(param);
self.insert(param.pat.span, param.hir_id, node);
self.with_parent(param.hir_id, |this| {
intravisit::walk_param(this, param);
2019-07-26 22:52:37 +00:00
});
}
#[instrument(level = "debug", skip(self))]
2019-11-28 18:28:50 +00:00
fn visit_item(&mut self, i: &'hir Item<'hir>) {
debug_assert_eq!(i.owner_id, self.owner);
2021-02-28 19:23:10 +00:00
self.with_parent(i.hir_id(), |this| {
if let ItemKind::Struct(struct_def, _) = &i.kind {
2021-03-27 12:21:26 +00:00
// If this is a tuple or unit-like struct, register the constructor.
if let Some(ctor_hir_id) = struct_def.ctor_hir_id() {
this.insert(i.span, ctor_hir_id, Node::Ctor(struct_def));
}
2021-03-27 12:21:26 +00:00
}
intravisit::walk_item(this, i);
2016-04-14 05:24:30 +00:00
});
}
#[instrument(level = "debug", skip(self))]
2020-11-11 20:57:54 +00:00
fn visit_foreign_item(&mut self, fi: &'hir ForeignItem<'hir>) {
debug_assert_eq!(fi.owner_id, self.owner);
2021-02-28 19:23:10 +00:00
self.with_parent(fi.hir_id(), |this| {
2021-03-27 12:21:26 +00:00
intravisit::walk_foreign_item(this, fi);
2016-04-14 05:24:30 +00:00
});
}
2019-11-30 16:46:46 +00:00
fn visit_generic_param(&mut self, param: &'hir GenericParam<'hir>) {
self.insert(param.span, param.hir_id, Node::GenericParam(param));
intravisit::walk_generic_param(self, param);
}
fn visit_const_param_default(&mut self, param: HirId, ct: &'hir ConstArg<'hir>) {
2021-03-27 12:21:26 +00:00
self.with_parent(param, |this| {
intravisit::walk_const_param_default(this, ct);
})
2021-03-01 11:50:09 +00:00
}
#[instrument(level = "debug", skip(self))]
2019-11-28 20:47:10 +00:00
fn visit_trait_item(&mut self, ti: &'hir TraitItem<'hir>) {
debug_assert_eq!(ti.owner_id, self.owner);
2021-02-28 19:23:10 +00:00
self.with_parent(ti.hir_id(), |this| {
2021-03-27 12:21:26 +00:00
intravisit::walk_trait_item(this, ti);
2016-04-14 05:24:30 +00:00
});
}
#[instrument(level = "debug", skip(self))]
2019-11-28 21:16:44 +00:00
fn visit_impl_item(&mut self, ii: &'hir ImplItem<'hir>) {
debug_assert_eq!(ii.owner_id, self.owner);
2021-02-28 19:23:10 +00:00
self.with_parent(ii.hir_id(), |this| {
2021-03-27 12:21:26 +00:00
intravisit::walk_impl_item(this, ii);
2016-04-14 05:24:30 +00:00
});
}
2019-11-29 12:43:03 +00:00
fn visit_pat(&mut self, pat: &'hir Pat<'hir>) {
2022-06-28 18:15:30 +00:00
self.insert(pat.span, pat.hir_id, Node::Pat(pat));
self.with_parent(pat.hir_id, |this| {
2016-04-14 05:24:30 +00:00
intravisit::walk_pat(this, pat);
});
}
fn visit_pat_field(&mut self, field: &'hir PatField<'hir>) {
self.insert(field.span, field.hir_id, Node::PatField(field));
self.with_parent(field.hir_id, |this| {
intravisit::walk_pat_field(this, field);
2016-04-14 05:24:30 +00:00
});
}
2019-11-29 12:43:03 +00:00
fn visit_arm(&mut self, arm: &'hir Arm<'hir>) {
2019-03-30 22:54:29 +00:00
let node = Node::Arm(arm);
self.insert(arm.span, arm.hir_id, node);
self.with_parent(arm.hir_id, |this| {
intravisit::walk_arm(this, arm);
});
}
fn visit_opaque_ty(&mut self, opaq: &'hir OpaqueTy<'hir>) {
self.insert(opaq.span, opaq.hir_id, Node::OpaqueTy(opaq));
self.with_parent(opaq.hir_id, |this| {
intravisit::walk_opaque_ty(this, opaq);
});
}
fn visit_anon_const(&mut self, constant: &'hir AnonConst) {
Add `ConstArgKind::Path` and make `ConstArg` its own HIR node This is a very large commit since a lot needs to be changed in order to make the tests pass. The salient changes are: - `ConstArgKind` gets a new `Path` variant, and all const params are now represented using it. Non-param paths still use `ConstArgKind::Anon` to prevent this change from getting too large, but they will soon use the `Path` variant too. - `ConstArg` gets a distinct `hir_id` field and its own variant in `hir::Node`. This affected many parts of the compiler that expected the parent of an `AnonConst` to be the containing context (e.g., an array repeat expression). They have been changed to check the "grandparent" where necessary. - Some `ast::AnonConst`s now have their `DefId`s created in rustc_ast_lowering rather than `DefCollector`. This is because in some cases they will end up becoming a `ConstArgKind::Path` instead, which has no `DefId`. We have to solve this in a hacky way where we guess whether the `AnonConst` could end up as a path const since we can't know for sure until after name resolution (`N` could refer to a free const or a nullary struct). If it has no chance as being a const param, then we create a `DefId` in `DefCollector` -- otherwise we decide during ast_lowering. This will have to be updated once all path consts use `ConstArgKind::Path`. - We explicitly use `ConstArgHasType` for array lengths, rather than implicitly relying on anon const type feeding -- this is due to the addition of `ConstArgKind::Path`. - Some tests have their outputs changed, but the changes are for the most part minor (including removing duplicate or almost-duplicate errors). One test now ICEs, but it is for an incomplete, unstable feature and is now tracked at #127009.
2024-07-17 02:07:36 +00:00
// FIXME: use real span?
self.insert(DUMMY_SP, constant.hir_id, Node::AnonConst(constant));
self.with_parent(constant.hir_id, |this| {
intravisit::walk_anon_const(this, constant);
});
}
fn visit_inline_const(&mut self, constant: &'hir ConstBlock) {
self.insert(DUMMY_SP, constant.hir_id, Node::ConstBlock(constant));
self.with_parent(constant.hir_id, |this| {
intravisit::walk_inline_const(this, constant);
});
}
Add `ConstArgKind::Path` and make `ConstArg` its own HIR node This is a very large commit since a lot needs to be changed in order to make the tests pass. The salient changes are: - `ConstArgKind` gets a new `Path` variant, and all const params are now represented using it. Non-param paths still use `ConstArgKind::Anon` to prevent this change from getting too large, but they will soon use the `Path` variant too. - `ConstArg` gets a distinct `hir_id` field and its own variant in `hir::Node`. This affected many parts of the compiler that expected the parent of an `AnonConst` to be the containing context (e.g., an array repeat expression). They have been changed to check the "grandparent" where necessary. - Some `ast::AnonConst`s now have their `DefId`s created in rustc_ast_lowering rather than `DefCollector`. This is because in some cases they will end up becoming a `ConstArgKind::Path` instead, which has no `DefId`. We have to solve this in a hacky way where we guess whether the `AnonConst` could end up as a path const since we can't know for sure until after name resolution (`N` could refer to a free const or a nullary struct). If it has no chance as being a const param, then we create a `DefId` in `DefCollector` -- otherwise we decide during ast_lowering. This will have to be updated once all path consts use `ConstArgKind::Path`. - We explicitly use `ConstArgHasType` for array lengths, rather than implicitly relying on anon const type feeding -- this is due to the addition of `ConstArgKind::Path`. - Some tests have their outputs changed, but the changes are for the most part minor (including removing duplicate or almost-duplicate errors). One test now ICEs, but it is for an incomplete, unstable feature and is now tracked at #127009.
2024-07-17 02:07:36 +00:00
fn visit_const_arg(&mut self, const_arg: &'hir ConstArg<'hir>) {
// FIXME: use real span?
self.insert(DUMMY_SP, const_arg.hir_id, Node::ConstArg(const_arg));
self.with_parent(const_arg.hir_id, |this| {
intravisit::walk_const_arg(this, const_arg);
});
}
2019-11-29 12:43:03 +00:00
fn visit_expr(&mut self, expr: &'hir Expr<'hir>) {
self.insert(expr.span, expr.hir_id, Node::Expr(expr));
self.with_parent(expr.hir_id, |this| {
2016-04-14 05:24:30 +00:00
intravisit::walk_expr(this, expr);
});
}
fn visit_expr_field(&mut self, field: &'hir ExprField<'hir>) {
self.insert(field.span, field.hir_id, Node::ExprField(field));
self.with_parent(field.hir_id, |this| {
intravisit::walk_expr_field(this, field);
});
}
2019-11-29 12:43:03 +00:00
fn visit_stmt(&mut self, stmt: &'hir Stmt<'hir>) {
self.insert(stmt.span, stmt.hir_id, Node::Stmt(stmt));
2016-04-14 05:24:30 +00:00
self.with_parent(stmt.hir_id, |this| {
2016-04-14 05:24:30 +00:00
intravisit::walk_stmt(this, stmt);
});
}
fn visit_path_segment(&mut self, path_segment: &'hir PathSegment<'hir>) {
2024-01-31 18:55:10 +00:00
// FIXME: walk path segment with `path_segment.hir_id` parent.
self.insert(path_segment.ident.span, path_segment.hir_id, Node::PathSegment(path_segment));
intravisit::walk_path_segment(self, path_segment);
}
2019-11-30 16:46:46 +00:00
fn visit_ty(&mut self, ty: &'hir Ty<'hir>) {
self.insert(ty.span, ty.hir_id, Node::Ty(ty));
self.with_parent(ty.hir_id, |this| {
intravisit::walk_ty(this, ty);
});
}
2021-04-24 21:41:57 +00:00
fn visit_infer(&mut self, inf: &'hir InferArg) {
self.insert(inf.span, inf.hir_id, Node::Infer(inf));
self.with_parent(inf.hir_id, |this| {
intravisit::walk_inf(this, inf);
});
}
2019-11-30 16:46:46 +00:00
fn visit_trait_ref(&mut self, tr: &'hir TraitRef<'hir>) {
self.insert(tr.path.span, tr.hir_ref_id, Node::TraitRef(tr));
self.with_parent(tr.hir_ref_id, |this| {
intravisit::walk_trait_ref(this, tr);
});
}
2019-11-29 12:43:03 +00:00
fn visit_block(&mut self, block: &'hir Block<'hir>) {
self.insert(block.span, block.hir_id, Node::Block(block));
self.with_parent(block.hir_id, |this| {
2016-04-14 05:24:30 +00:00
intravisit::walk_block(this, block);
});
}
fn visit_local(&mut self, l: &'hir LetStmt<'hir>) {
self.insert(l.span, l.hir_id, Node::LetStmt(l));
2021-03-27 12:21:26 +00:00
self.with_parent(l.hir_id, |this| {
intravisit::walk_local(this, l);
})
}
2017-01-26 01:21:50 +00:00
fn visit_lifetime(&mut self, lifetime: &'hir Lifetime) {
self.insert(lifetime.ident.span, lifetime.hir_id, Node::Lifetime(lifetime));
}
2016-10-28 06:52:45 +00:00
fn visit_variant(&mut self, v: &'hir Variant<'hir>) {
self.insert(v.span, v.hir_id, Node::Variant(v));
self.with_parent(v.hir_id, |this| {
// Register the constructor of this variant.
2019-08-14 00:40:21 +00:00
if let Some(ctor_hir_id) = v.data.ctor_hir_id() {
this.insert(v.span, ctor_hir_id, Node::Ctor(&v.data));
}
intravisit::walk_variant(this, v);
});
}
fn visit_field_def(&mut self, field: &'hir FieldDef<'hir>) {
self.insert(field.span, field.hir_id, Node::Field(field));
self.with_parent(field.hir_id, |this| {
intravisit::walk_field_def(this, field);
2016-11-09 18:57:48 +00:00
});
}
fn visit_assoc_item_constraint(&mut self, constraint: &'hir AssocItemConstraint<'hir>) {
self.insert(constraint.span, constraint.hir_id, Node::AssocItemConstraint(constraint));
self.with_parent(constraint.hir_id, |this| {
intravisit::walk_assoc_item_constraint(this, constraint)
})
}
fn visit_trait_item_ref(&mut self, ii: &'hir TraitItemRef) {
// Do not visit the duplicate information in TraitItemRef. We want to
// map the actual nodes, not the duplicate ones in the *Ref.
let TraitItemRef { id, ident: _, kind: _, span: _ } = *ii;
self.visit_nested_trait_item(id);
}
2021-07-15 20:19:39 +00:00
fn visit_impl_item_ref(&mut self, ii: &'hir ImplItemRef) {
// Do not visit the duplicate information in ImplItemRef. We want to
// map the actual nodes, not the duplicate ones in the *Ref.
let ImplItemRef { id, ident: _, kind: _, span: _, trait_item_def_id: _ } = *ii;
self.visit_nested_impl_item(id);
}
2021-07-15 20:19:39 +00:00
fn visit_foreign_item_ref(&mut self, fi: &'hir ForeignItemRef) {
// Do not visit the duplicate information in ForeignItemRef. We want to
// map the actual nodes, not the duplicate ones in the *Ref.
2021-07-15 20:19:39 +00:00
let ForeignItemRef { id, ident: _, span: _ } = *fi;
self.visit_nested_foreign_item(id);
}
fn visit_where_predicate(&mut self, predicate: &'hir WherePredicate<'hir>) {
match predicate {
WherePredicate::BoundPredicate(pred) => {
self.insert(pred.span, pred.hir_id, Node::WhereBoundPredicate(pred));
self.with_parent(pred.hir_id, |this| {
intravisit::walk_where_predicate(this, predicate)
})
}
_ => intravisit::walk_where_predicate(self, predicate),
}
}
2024-04-26 12:57:02 +00:00
fn visit_array_length(&mut self, len: &'hir ArrayLen<'hir>) {
match len {
ArrayLen::Infer(inf) => self.insert(inf.span, inf.hir_id, Node::ArrayLenInfer(inf)),
ArrayLen::Body(..) => intravisit::walk_array_len(self, len),
}
}
fn visit_pattern_type_pattern(&mut self, p: &'hir hir::Pat<'hir>) {
self.visit_pat(p)
}
fn visit_precise_capturing_arg(
&mut self,
arg: &'hir PreciseCapturingArg<'hir>,
) -> Self::Result {
match arg {
PreciseCapturingArg::Lifetime(_) => {
// This is represented as a `Node::Lifetime`, intravisit will get to it below.
}
PreciseCapturingArg::Param(param) => self.insert(
param.ident.span,
param.hir_id,
Node::PreciseCapturingNonLifetimeArg(param),
),
}
intravisit::walk_precise_capturing_arg(self, arg);
}
}