Skip to content

Commit 21fc882

Browse files
committed
Auto merge of rust-lang#120206 - petrochenkov:somehir, r=<try>
hir: Make sure all `HirId`s have corresponding HIR `Node`s And then remove `tcx.opt_hir_node(hir_id)` in favor of `tcx.hir_node(hir_id)`.
2 parents ef71f10 + f26f870 commit 21fc882

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

52 files changed

+352
-367
lines changed

compiler/rustc_ast_lowering/src/index.rs

+37-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ pub(super) fn index_hir<'hir>(
2929
tcx: TyCtxt<'hir>,
3030
item: hir::OwnerNode<'hir>,
3131
bodies: &SortedMap<ItemLocalId, &'hir Body<'hir>>,
32-
) -> (IndexVec<ItemLocalId, Option<ParentedNode<'hir>>>, LocalDefIdMap<ItemLocalId>) {
32+
) -> (IndexVec<ItemLocalId, ParentedNode<'hir>>, LocalDefIdMap<ItemLocalId>) {
3333
let mut nodes = IndexVec::new();
3434
// This node's parent should never be accessed: the owner's parent is computed by the
3535
// hir_owner_parent query. Make it invalid (= ItemLocalId::MAX) to force an ICE whenever it is
@@ -54,7 +54,18 @@ pub(super) fn index_hir<'hir>(
5454
OwnerNode::ForeignItem(item) => collector.visit_foreign_item(item),
5555
};
5656

57-
(collector.nodes, collector.parenting)
57+
let err = || {
58+
let span = item.span();
59+
tcx.dcx().span_delayed_bug(*span, "ID not encountered when visiting item HIR");
60+
ParentedNode { parent: ItemLocalId::new(0), node: Node::Err(span) }
61+
};
62+
let nodes = collector
63+
.nodes
64+
.into_iter()
65+
.map(|parented_node| parented_node.unwrap_or_else(err))
66+
.collect();
67+
68+
(nodes, collector.parenting)
5869
}
5970

6071
impl<'a, 'hir> NodeCollector<'a, 'hir> {
@@ -348,4 +359,28 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
348359

349360
self.visit_nested_foreign_item(id);
350361
}
362+
363+
fn visit_where_predicate(&mut self, predicate: &'hir WherePredicate<'hir>) {
364+
match predicate {
365+
WherePredicate::BoundPredicate(pred) => {
366+
self.insert(pred.span, pred.hir_id, Node::WhereBoundPredicate(pred));
367+
self.with_parent(pred.hir_id, |this| {
368+
intravisit::walk_where_predicate(this, predicate)
369+
})
370+
}
371+
_ => intravisit::walk_where_predicate(self, predicate),
372+
}
373+
}
374+
375+
fn visit_let_expr(&mut self, lex: &'hir Let<'hir>) {
376+
self.insert(lex.span, lex.hir_id, Node::Let(lex));
377+
self.with_parent(lex.hir_id, |this| intravisit::walk_let_expr(this, lex))
378+
}
379+
380+
fn visit_array_length(&mut self, len: &'hir ArrayLen) {
381+
match len {
382+
ArrayLen::Infer(hir_id, span) => self.insert(*span, *hir_id, Node::ArrayLenInfer(span)),
383+
ArrayLen::Body(..) => intravisit::walk_array_len(self, len),
384+
}
385+
}
351386
}

compiler/rustc_borrowck/src/diagnostics/conflict_errors.rs

+57-64
Original file line numberDiff line numberDiff line change
@@ -399,66 +399,60 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
399399
}
400400
let typeck = self.infcx.tcx.typeck(self.mir_def_id());
401401
let hir_id = hir.parent_id(expr.hir_id);
402-
if let Some(parent) = self.infcx.tcx.opt_hir_node(hir_id) {
403-
let (def_id, args, offset) = if let hir::Node::Expr(parent_expr) = parent
404-
&& let hir::ExprKind::MethodCall(_, _, args, _) = parent_expr.kind
405-
&& let Some(def_id) = typeck.type_dependent_def_id(parent_expr.hir_id)
406-
{
407-
(def_id.as_local(), args, 1)
408-
} else if let hir::Node::Expr(parent_expr) = parent
409-
&& let hir::ExprKind::Call(call, args) = parent_expr.kind
410-
&& let ty::FnDef(def_id, _) = typeck.node_type(call.hir_id).kind()
411-
{
412-
(def_id.as_local(), args, 0)
413-
} else {
414-
(None, &[][..], 0)
402+
let parent = self.infcx.tcx.hir_node(hir_id);
403+
let (def_id, args, offset) = if let hir::Node::Expr(parent_expr) = parent
404+
&& let hir::ExprKind::MethodCall(_, _, args, _) = parent_expr.kind
405+
&& let Some(def_id) = typeck.type_dependent_def_id(parent_expr.hir_id)
406+
{
407+
(def_id.as_local(), args, 1)
408+
} else if let hir::Node::Expr(parent_expr) = parent
409+
&& let hir::ExprKind::Call(call, args) = parent_expr.kind
410+
&& let ty::FnDef(def_id, _) = typeck.node_type(call.hir_id).kind()
411+
{
412+
(def_id.as_local(), args, 0)
413+
} else {
414+
(None, &[][..], 0)
415+
};
416+
if let Some(def_id) = def_id
417+
&& let node =
418+
self.infcx.tcx.hir_node(self.infcx.tcx.local_def_id_to_hir_id(def_id))
419+
&& let Some(fn_sig) = node.fn_sig()
420+
&& let Some(ident) = node.ident()
421+
&& let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id)
422+
&& let Some(arg) = fn_sig.decl.inputs.get(pos + offset)
423+
{
424+
let mut span: MultiSpan = arg.span.into();
425+
span.push_span_label(
426+
arg.span,
427+
"this parameter takes ownership of the value".to_string(),
428+
);
429+
let descr = match node.fn_kind() {
430+
Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
431+
Some(hir::intravisit::FnKind::Method(..)) => "method",
432+
Some(hir::intravisit::FnKind::Closure) => "closure",
415433
};
416-
if let Some(def_id) = def_id
417-
&& let Some(node) = self
418-
.infcx
419-
.tcx
420-
.opt_hir_node(self.infcx.tcx.local_def_id_to_hir_id(def_id))
421-
&& let Some(fn_sig) = node.fn_sig()
422-
&& let Some(ident) = node.ident()
423-
&& let Some(pos) = args.iter().position(|arg| arg.hir_id == expr.hir_id)
424-
&& let Some(arg) = fn_sig.decl.inputs.get(pos + offset)
425-
{
426-
let mut span: MultiSpan = arg.span.into();
427-
span.push_span_label(
428-
arg.span,
429-
"this parameter takes ownership of the value".to_string(),
430-
);
431-
let descr = match node.fn_kind() {
432-
Some(hir::intravisit::FnKind::ItemFn(..)) | None => "function",
433-
Some(hir::intravisit::FnKind::Method(..)) => "method",
434-
Some(hir::intravisit::FnKind::Closure) => "closure",
435-
};
436-
span.push_span_label(ident.span, format!("in this {descr}"));
437-
err.span_note(
438-
span,
439-
format!(
440-
"consider changing this parameter type in {descr} `{ident}` to \
434+
span.push_span_label(ident.span, format!("in this {descr}"));
435+
err.span_note(
436+
span,
437+
format!(
438+
"consider changing this parameter type in {descr} `{ident}` to \
441439
borrow instead if owning the value isn't necessary",
442-
),
443-
);
444-
}
445-
let place = &self.move_data.move_paths[mpi].place;
446-
let ty = place.ty(self.body, self.infcx.tcx).ty;
447-
if let hir::Node::Expr(parent_expr) = parent
448-
&& let hir::ExprKind::Call(call_expr, _) = parent_expr.kind
449-
&& let hir::ExprKind::Path(hir::QPath::LangItem(
450-
LangItem::IntoIterIntoIter,
451-
_,
452-
)) = call_expr.kind
453-
{
454-
// Do not suggest `.clone()` in a `for` loop, we already suggest borrowing.
455-
} else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } =
456-
move_spans
457-
{
458-
// We already suggest cloning for these cases in `explain_captures`.
459-
} else {
460-
self.suggest_cloning(err, ty, expr, move_span);
461-
}
440+
),
441+
);
442+
}
443+
let place = &self.move_data.move_paths[mpi].place;
444+
let ty = place.ty(self.body, self.infcx.tcx).ty;
445+
if let hir::Node::Expr(parent_expr) = parent
446+
&& let hir::ExprKind::Call(call_expr, _) = parent_expr.kind
447+
&& let hir::ExprKind::Path(hir::QPath::LangItem(LangItem::IntoIterIntoIter, _)) =
448+
call_expr.kind
449+
{
450+
// Do not suggest `.clone()` in a `for` loop, we already suggest borrowing.
451+
} else if let UseSpans::FnSelfUse { kind: CallKind::Normal { .. }, .. } = move_spans
452+
{
453+
// We already suggest cloning for these cases in `explain_captures`.
454+
} else {
455+
self.suggest_cloning(err, ty, expr, move_span);
462456
}
463457
}
464458
if let Some(pat) = finder.pat {
@@ -1757,7 +1751,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
17571751
fn_decl: hir::FnDecl { inputs, .. },
17581752
..
17591753
}) = e.kind
1760-
&& let Some(hir::Node::Expr(body)) = self.tcx.opt_hir_node(body.hir_id)
1754+
&& let hir::Node::Expr(body) = self.tcx.hir_node(body.hir_id)
17611755
{
17621756
self.suggest_arg = "this: &Self".to_string();
17631757
if inputs.len() > 0 {
@@ -1823,11 +1817,11 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
18231817
}
18241818
}
18251819

1826-
if let Some(hir::Node::ImplItem(hir::ImplItem {
1820+
if let hir::Node::ImplItem(hir::ImplItem {
18271821
kind: hir::ImplItemKind::Fn(_fn_sig, body_id),
18281822
..
1829-
})) = self.infcx.tcx.opt_hir_node(self.mir_hir_id())
1830-
&& let Some(hir::Node::Expr(expr)) = self.infcx.tcx.opt_hir_node(body_id.hir_id)
1823+
}) = self.infcx.tcx.hir_node(self.mir_hir_id())
1824+
&& let hir::Node::Expr(expr) = self.infcx.tcx.hir_node(body_id.hir_id)
18311825
{
18321826
let mut finder = ExpressionFinder {
18331827
capture_span: *capture_kind_span,
@@ -2395,8 +2389,7 @@ impl<'cx, 'tcx> MirBorrowckCtxt<'cx, 'tcx> {
23952389
let proper_span = proper_span.source_callsite();
23962390
if let Some(scope) = self.body.source_scopes.get(source_info.scope)
23972391
&& let ClearCrossCrate::Set(scope_data) = &scope.local_data
2398-
&& let Some(node) = self.infcx.tcx.opt_hir_node(scope_data.lint_root)
2399-
&& let Some(id) = node.body_id()
2392+
&& let Some(id) = self.infcx.tcx.hir_node(scope_data.lint_root).body_id()
24002393
&& let hir::ExprKind::Block(block, _) = self.infcx.tcx.hir().body(id).value.kind
24012394
{
24022395
for stmt in block.stmts {

compiler/rustc_borrowck/src/diagnostics/explain_borrow.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ impl<'tcx> BorrowExplanation<'tcx> {
8787
if let hir::ExprKind::Path(hir::QPath::Resolved(None, p)) = expr.kind
8888
&& let [hir::PathSegment { ident, args: None, .. }] = p.segments
8989
&& let hir::def::Res::Local(hir_id) = p.res
90-
&& let Some(hir::Node::Pat(pat)) = tcx.opt_hir_node(hir_id)
90+
&& let hir::Node::Pat(pat) = tcx.hir_node(hir_id)
9191
{
9292
err.span_label(pat.span, format!("binding `{ident}` declared here"));
9393
}

compiler/rustc_borrowck/src/diagnostics/mutability_errors.rs

+7-7
Original file line numberDiff line numberDiff line change
@@ -396,7 +396,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
396396

397397
let upvar_hir_id = captured_place.get_root_variable();
398398

399-
if let Some(Node::Pat(pat)) = self.infcx.tcx.opt_hir_node(upvar_hir_id)
399+
if let Node::Pat(pat) = self.infcx.tcx.hir_node(upvar_hir_id)
400400
&& let hir::PatKind::Binding(hir::BindingAnnotation::NONE, _, upvar_ident, _) =
401401
pat.kind
402402
{
@@ -688,15 +688,15 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
688688
break;
689689
}
690690
f_in_trait_opt.and_then(|f_in_trait| {
691-
match self.infcx.tcx.opt_hir_node(f_in_trait) {
692-
Some(Node::TraitItem(hir::TraitItem {
691+
match self.infcx.tcx.hir_node(f_in_trait) {
692+
Node::TraitItem(hir::TraitItem {
693693
kind:
694694
hir::TraitItemKind::Fn(
695695
hir::FnSig { decl: hir::FnDecl { inputs, .. }, .. },
696696
_,
697697
),
698698
..
699-
})) => {
699+
}) => {
700700
let hir::Ty { span, .. } = inputs[local.index() - 1];
701701
Some(span)
702702
}
@@ -759,10 +759,10 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
759759
//
760760
// `let &b = a;` -> `let &(mut b) = a;`
761761
if let Some(hir_id) = hir_id
762-
&& let Some(hir::Node::Local(hir::Local {
762+
&& let hir::Node::Local(hir::Local {
763763
pat: hir::Pat { kind: hir::PatKind::Ref(_, _), .. },
764764
..
765-
})) = self.infcx.tcx.opt_hir_node(hir_id)
765+
}) = self.infcx.tcx.hir_node(hir_id)
766766
&& let Ok(name) =
767767
self.infcx.tcx.sess.source_map().span_to_snippet(local_decl.source_info.span)
768768
{
@@ -1206,7 +1206,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
12061206
};
12071207

12081208
if let Some(hir_id) = hir_id
1209-
&& let Some(hir::Node::Local(local)) = self.infcx.tcx.opt_hir_node(hir_id)
1209+
&& let hir::Node::Local(local) = self.infcx.tcx.hir_node(hir_id)
12101210
{
12111211
let tables = self.infcx.tcx.typeck(def_id.as_local().unwrap());
12121212
if let Some(clone_trait) = self.infcx.tcx.lang_items().clone_trait()

compiler/rustc_borrowck/src/diagnostics/region_errors.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,8 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
216216
if let Some(id) = placeholder.bound.kind.get_id()
217217
&& let Some(placeholder_id) = id.as_local()
218218
&& let gat_hir_id = self.infcx.tcx.local_def_id_to_hir_id(placeholder_id)
219-
&& let Some(generics_impl) = hir.get_parent(gat_hir_id).generics()
219+
&& let Some(generics_impl) =
220+
hir.get_parent(hir.parent_id(gat_hir_id)).generics()
220221
{
221222
Some((gat_hir_id, generics_impl))
222223
} else {

compiler/rustc_hir/src/hir.rs

+20-15
Original file line numberDiff line numberDiff line change
@@ -835,17 +835,16 @@ pub struct OwnerNodes<'tcx> {
835835
// The zeroth node's parent should never be accessed: the owner's parent is computed by the
836836
// hir_owner_parent query. It is set to `ItemLocalId::INVALID` to force an ICE if accidentally
837837
// used.
838-
pub nodes: IndexVec<ItemLocalId, Option<ParentedNode<'tcx>>>,
838+
pub nodes: IndexVec<ItemLocalId, ParentedNode<'tcx>>,
839839
/// Content of local bodies.
840840
pub bodies: SortedMap<ItemLocalId, &'tcx Body<'tcx>>,
841841
}
842842

843843
impl<'tcx> OwnerNodes<'tcx> {
844844
pub fn node(&self) -> OwnerNode<'tcx> {
845845
use rustc_index::Idx;
846-
let node = self.nodes[ItemLocalId::new(0)].as_ref().unwrap().node;
847-
let node = node.as_owner().unwrap(); // Indexing must ensure it is an OwnerNode.
848-
node
846+
// Indexing must ensure it is an OwnerNode.
847+
self.nodes[ItemLocalId::new(0)].node.as_owner().unwrap()
849848
}
850849
}
851850

@@ -860,9 +859,7 @@ impl fmt::Debug for OwnerNodes<'_> {
860859
.nodes
861860
.iter_enumerated()
862861
.map(|(id, parented_node)| {
863-
let parented_node = parented_node.as_ref().map(|node| node.parent);
864-
865-
debug_fn(move |f| write!(f, "({id:?}, {parented_node:?})"))
862+
debug_fn(move |f| write!(f, "({id:?}, {:?})", parented_node.parent))
866863
})
867864
.collect::<Vec<_>>(),
868865
)
@@ -3356,13 +3353,14 @@ impl<'hir> OwnerNode<'hir> {
33563353
}
33573354
}
33583355

3359-
pub fn span(&self) -> Span {
3356+
#[allow(rustc::pass_by_value)]
3357+
pub fn span(&self) -> &'hir Span {
33603358
match self {
33613359
OwnerNode::Item(Item { span, .. })
33623360
| OwnerNode::ForeignItem(ForeignItem { span, .. })
33633361
| OwnerNode::ImplItem(ImplItem { span, .. })
3364-
| OwnerNode::TraitItem(TraitItem { span, .. }) => *span,
3365-
OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => *inner_span,
3362+
| OwnerNode::TraitItem(TraitItem { span, .. }) => span,
3363+
OwnerNode::Crate(Mod { spans: ModSpans { inner_span, .. }, .. }) => inner_span,
33663364
}
33673365
}
33683366

@@ -3491,17 +3489,20 @@ pub enum Node<'hir> {
34913489
Arm(&'hir Arm<'hir>),
34923490
Block(&'hir Block<'hir>),
34933491
Local(&'hir Local<'hir>),
3494-
34953492
/// `Ctor` refers to the constructor of an enum variant or struct. Only tuple or unit variants
34963493
/// with synthesized constructors.
34973494
Ctor(&'hir VariantData<'hir>),
3498-
34993495
Lifetime(&'hir Lifetime),
35003496
GenericParam(&'hir GenericParam<'hir>),
3501-
35023497
Crate(&'hir Mod<'hir>),
3503-
35043498
Infer(&'hir InferArg),
3499+
WhereBoundPredicate(&'hir WhereBoundPredicate<'hir>),
3500+
Let(&'hir Let<'hir>),
3501+
// Span by reference to minimize `Node`'s size
3502+
#[allow(rustc::pass_by_value)]
3503+
ArrayLenInfer(&'hir Span),
3504+
#[allow(rustc::pass_by_value)]
3505+
Err(&'hir Span),
35053506
}
35063507

35073508
impl<'hir> Node<'hir> {
@@ -3546,7 +3547,11 @@ impl<'hir> Node<'hir> {
35463547
| Node::Crate(..)
35473548
| Node::Ty(..)
35483549
| Node::TraitRef(..)
3549-
| Node::Infer(..) => None,
3550+
| Node::Infer(..)
3551+
| Node::WhereBoundPredicate(..)
3552+
| Node::Let(..)
3553+
| Node::ArrayLenInfer(..)
3554+
| Node::Err(..) => None,
35503555
}
35513556
}
35523557

compiler/rustc_hir/src/intravisit.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ impl<'a> FnKind<'a> {
108108

109109
/// An abstract representation of the HIR `rustc_middle::hir::map::Map`.
110110
pub trait Map<'hir> {
111-
/// Retrieves the `Node` corresponding to `id`, returning `None` if cannot be found.
112-
fn find(&self, hir_id: HirId) -> Option<Node<'hir>>;
111+
/// Retrieves the `Node` corresponding to `id`.
112+
fn hir_node(&self, hir_id: HirId) -> Node<'hir>;
113113
fn body(&self, id: BodyId) -> &'hir Body<'hir>;
114114
fn item(&self, id: ItemId) -> &'hir Item<'hir>;
115115
fn trait_item(&self, id: TraitItemId) -> &'hir TraitItem<'hir>;
@@ -119,7 +119,7 @@ pub trait Map<'hir> {
119119

120120
// Used when no map is actually available, forcing manual implementation of nested visitors.
121121
impl<'hir> Map<'hir> for ! {
122-
fn find(&self, _: HirId) -> Option<Node<'hir>> {
122+
fn hir_node(&self, _: HirId) -> Node<'hir> {
123123
*self;
124124
}
125125
fn body(&self, _: BodyId) -> &'hir Body<'hir> {

0 commit comments

Comments
 (0)