Skip to content

Commit 1107fc7

Browse files
authored
Rollup merge of #138929 - oli-obk:assoc-ctxt-of-trait, r=compiler-errors
Visitors track whether an assoc item is in a trait impl or an inherent impl `AssocCtxt::Impl` now contains an `of_trait` field. This allows ast lowering and nameres to not have to track whether we're in a trait impl or an inherent impl.
2 parents ffc5717 + 59e3380 commit 1107fc7

File tree

17 files changed

+185
-96
lines changed

17 files changed

+185
-96
lines changed

compiler/rustc_ast/src/mut_visit.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -1318,7 +1318,9 @@ impl WalkItemKind for ItemKind {
13181318
visit_polarity(vis, polarity);
13191319
visit_opt(of_trait, |trait_ref| vis.visit_trait_ref(trait_ref));
13201320
vis.visit_ty(self_ty);
1321-
items.flat_map_in_place(|item| vis.flat_map_assoc_item(item, AssocCtxt::Impl));
1321+
items.flat_map_in_place(|item| {
1322+
vis.flat_map_assoc_item(item, AssocCtxt::Impl { of_trait: of_trait.is_some() })
1323+
});
13221324
}
13231325
ItemKind::Trait(box Trait { safety, is_auto: _, generics, bounds, items }) => {
13241326
visit_safety(vis, safety);

compiler/rustc_ast/src/visit.rs

+7-2
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use crate::ptr::P;
2323
#[derive(Copy, Clone, Debug, PartialEq)]
2424
pub enum AssocCtxt {
2525
Trait,
26-
Impl,
26+
Impl { of_trait: bool },
2727
}
2828

2929
#[derive(Copy, Clone, Debug, PartialEq)]
@@ -422,7 +422,12 @@ impl WalkItemKind for ItemKind {
422422
try_visit!(visitor.visit_generics(generics));
423423
visit_opt!(visitor, visit_trait_ref, of_trait);
424424
try_visit!(visitor.visit_ty(self_ty));
425-
walk_list!(visitor, visit_assoc_item, items, AssocCtxt::Impl);
425+
walk_list!(
426+
visitor,
427+
visit_assoc_item,
428+
items,
429+
AssocCtxt::Impl { of_trait: of_trait.is_some() }
430+
);
426431
}
427432
ItemKind::Struct(struct_definition, generics)
428433
| ItemKind::Union(struct_definition, generics) => {

compiler/rustc_ast_lowering/src/delegation.rs

+12-4
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,14 @@ pub(crate) struct DelegationResults<'hir> {
6161

6262
impl<'hir> LoweringContext<'_, 'hir> {
6363
/// Defines whether the delegatee is an associated function whose first parameter is `self`.
64-
pub(crate) fn delegatee_is_method(&self, item_id: NodeId, path_id: NodeId, span: Span) -> bool {
65-
let sig_id = self.get_delegation_sig_id(item_id, path_id, span);
64+
pub(crate) fn delegatee_is_method(
65+
&self,
66+
item_id: NodeId,
67+
path_id: NodeId,
68+
span: Span,
69+
is_in_trait_impl: bool,
70+
) -> bool {
71+
let sig_id = self.get_delegation_sig_id(item_id, path_id, span, is_in_trait_impl);
6672
let Ok(sig_id) = sig_id else {
6773
return false;
6874
};
@@ -88,9 +94,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
8894
&mut self,
8995
delegation: &Delegation,
9096
item_id: NodeId,
97+
is_in_trait_impl: bool,
9198
) -> DelegationResults<'hir> {
9299
let span = self.lower_span(delegation.path.segments.last().unwrap().ident.span);
93-
let sig_id = self.get_delegation_sig_id(item_id, delegation.id, span);
100+
let sig_id = self.get_delegation_sig_id(item_id, delegation.id, span, is_in_trait_impl);
94101
match sig_id {
95102
Ok(sig_id) => {
96103
let (param_count, c_variadic) = self.param_count(sig_id);
@@ -110,8 +117,9 @@ impl<'hir> LoweringContext<'_, 'hir> {
110117
item_id: NodeId,
111118
path_id: NodeId,
112119
span: Span,
120+
is_in_trait_impl: bool,
113121
) -> Result<DefId, ErrorGuaranteed> {
114-
let sig_id = if self.is_in_trait_impl { item_id } else { path_id };
122+
let sig_id = if is_in_trait_impl { item_id } else { path_id };
115123
self.get_resolution_id(sig_id, span)
116124
}
117125

compiler/rustc_ast_lowering/src/item.rs

+27-35
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use rustc_hir::def::{DefKind, Res};
77
use rustc_hir::def_id::{CRATE_DEF_ID, LocalDefId};
88
use rustc_hir::{self as hir, HirId, PredicateOrigin};
99
use rustc_index::{IndexSlice, IndexVec};
10-
use rustc_middle::span_bug;
1110
use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
1211
use rustc_span::edit_distance::find_best_match_for_name;
1312
use rustc_span::{DUMMY_SP, DesugaringKind, Ident, Span, Symbol, kw, sym};
@@ -104,10 +103,7 @@ impl<'a, 'hir> ItemLowerer<'a, 'hir> {
104103
}
105104

106105
fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) {
107-
let def_id = self.resolver.node_id_to_def_id[&item.id];
108-
let parent_id = self.tcx.local_parent(def_id);
109-
let parent_hir = self.lower_node(parent_id).unwrap();
110-
self.with_lctx(item.id, |lctx| lctx.lower_assoc_item(item, ctxt, parent_hir))
106+
self.with_lctx(item.id, |lctx| lctx.lower_assoc_item(item, ctxt))
111107
}
112108

113109
fn lower_foreign_item(&mut self, item: &ForeignItem) {
@@ -405,10 +401,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
405401
(trait_ref, lowered_ty)
406402
});
407403

408-
self.is_in_trait_impl = trait_ref.is_some();
409-
let new_impl_items = self
410-
.arena
411-
.alloc_from_iter(impl_items.iter().map(|item| self.lower_impl_item_ref(item)));
404+
let new_impl_items = self.arena.alloc_from_iter(
405+
impl_items
406+
.iter()
407+
.map(|item| self.lower_impl_item_ref(item, trait_ref.is_some())),
408+
);
412409

413410
// `defaultness.has_value()` is never called for an `impl`, always `true` in order
414411
// to not cause an assertion failure inside the `lower_defaultness` function.
@@ -485,7 +482,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
485482
ItemKind::Delegation(box delegation) => {
486483
debug_assert_ne!(ident.name, kw::Empty);
487484
let ident = self.lower_ident(ident);
488-
let delegation_results = self.lower_delegation(delegation, id);
485+
let delegation_results = self.lower_delegation(delegation, id, false);
489486
hir::ItemKind::Fn {
490487
ident,
491488
sig: delegation_results.sig,
@@ -628,29 +625,15 @@ impl<'hir> LoweringContext<'_, 'hir> {
628625
}
629626
}
630627

631-
fn lower_assoc_item(
632-
&mut self,
633-
item: &AssocItem,
634-
ctxt: AssocCtxt,
635-
parent_hir: &'hir hir::OwnerInfo<'hir>,
636-
) -> hir::OwnerNode<'hir> {
637-
let parent_item = parent_hir.node().expect_item();
638-
match parent_item.kind {
639-
hir::ItemKind::Impl(impl_) => {
640-
self.is_in_trait_impl = impl_.of_trait.is_some();
641-
}
642-
hir::ItemKind::Trait(..) => {}
643-
kind => {
644-
span_bug!(item.span, "assoc item has unexpected kind of parent: {}", kind.descr())
645-
}
646-
}
647-
628+
fn lower_assoc_item(&mut self, item: &AssocItem, ctxt: AssocCtxt) -> hir::OwnerNode<'hir> {
648629
// Evaluate with the lifetimes in `params` in-scope.
649630
// This is used to track which lifetimes have already been defined,
650631
// and which need to be replicated when lowering an async fn.
651632
match ctxt {
652633
AssocCtxt::Trait => hir::OwnerNode::TraitItem(self.lower_trait_item(item)),
653-
AssocCtxt::Impl => hir::OwnerNode::ImplItem(self.lower_impl_item(item)),
634+
AssocCtxt::Impl { of_trait } => {
635+
hir::OwnerNode::ImplItem(self.lower_impl_item(item, of_trait))
636+
}
654637
}
655638
}
656639

@@ -891,7 +874,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
891874
(generics, kind, ty.is_some())
892875
}
893876
AssocItemKind::Delegation(box delegation) => {
894-
let delegation_results = self.lower_delegation(delegation, i.id);
877+
let delegation_results = self.lower_delegation(delegation, i.id, false);
895878
let item_kind = hir::TraitItemKind::Fn(
896879
delegation_results.sig,
897880
hir::TraitFn::Provided(delegation_results.body_id),
@@ -922,7 +905,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
922905
hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
923906
}
924907
AssocItemKind::Delegation(box delegation) => hir::AssocItemKind::Fn {
925-
has_self: self.delegatee_is_method(i.id, delegation.id, i.span),
908+
has_self: self.delegatee_is_method(i.id, delegation.id, i.span, false),
926909
},
927910
AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
928911
panic!("macros should have been expanded by now")
@@ -942,7 +925,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
942925
self.expr(span, hir::ExprKind::Err(guar))
943926
}
944927

945-
fn lower_impl_item(&mut self, i: &AssocItem) -> &'hir hir::ImplItem<'hir> {
928+
fn lower_impl_item(
929+
&mut self,
930+
i: &AssocItem,
931+
is_in_trait_impl: bool,
932+
) -> &'hir hir::ImplItem<'hir> {
946933
debug_assert_ne!(i.ident.name, kw::Empty);
947934
// Since `default impl` is not yet implemented, this is always true in impls.
948935
let has_value = true;
@@ -978,7 +965,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
978965
generics,
979966
sig,
980967
i.id,
981-
if self.is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
968+
if is_in_trait_impl { FnDeclKind::Impl } else { FnDeclKind::Inherent },
982969
sig.header.coroutine_kind,
983970
attrs,
984971
);
@@ -1018,7 +1005,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
10181005
)
10191006
}
10201007
AssocItemKind::Delegation(box delegation) => {
1021-
let delegation_results = self.lower_delegation(delegation, i.id);
1008+
let delegation_results = self.lower_delegation(delegation, i.id, is_in_trait_impl);
10221009
(
10231010
delegation_results.generics,
10241011
hir::ImplItemKind::Fn(delegation_results.sig, delegation_results.body_id),
@@ -1041,7 +1028,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
10411028
self.arena.alloc(item)
10421029
}
10431030

1044-
fn lower_impl_item_ref(&mut self, i: &AssocItem) -> hir::ImplItemRef {
1031+
fn lower_impl_item_ref(&mut self, i: &AssocItem, is_in_trait_impl: bool) -> hir::ImplItemRef {
10451032
hir::ImplItemRef {
10461033
id: hir::ImplItemId { owner_id: self.owner_id(i.id) },
10471034
ident: self.lower_ident(i.ident),
@@ -1053,7 +1040,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
10531040
hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
10541041
}
10551042
AssocItemKind::Delegation(box delegation) => hir::AssocItemKind::Fn {
1056-
has_self: self.delegatee_is_method(i.id, delegation.id, i.span),
1043+
has_self: self.delegatee_is_method(
1044+
i.id,
1045+
delegation.id,
1046+
i.span,
1047+
is_in_trait_impl,
1048+
),
10571049
},
10581050
AssocItemKind::MacCall(..) | AssocItemKind::DelegationMac(..) => {
10591051
panic!("macros should have been expanded by now")

compiler/rustc_ast_lowering/src/lib.rs

-2
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,6 @@ struct LoweringContext<'a, 'hir> {
121121
catch_scope: Option<HirId>,
122122
loop_scope: Option<HirId>,
123123
is_in_loop_condition: bool,
124-
is_in_trait_impl: bool,
125124
is_in_dyn_type: bool,
126125

127126
current_hir_id_owner: hir::OwnerId,
@@ -173,7 +172,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
173172
catch_scope: None,
174173
loop_scope: None,
175174
is_in_loop_condition: false,
176-
is_in_trait_impl: false,
177175
is_in_dyn_type: false,
178176
coroutine_kind: None,
179177
task_context: None,

compiler/rustc_ast_passes/src/ast_validation.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -860,7 +860,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
860860
this.visit_trait_ref(t);
861861
this.visit_ty(self_ty);
862862

863-
walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
863+
walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl { of_trait: true });
864864
});
865865
walk_list!(self, visit_attribute, &item.attrs);
866866
return; // Avoid visiting again.
@@ -913,7 +913,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
913913
|this| this.visit_generics(generics),
914914
);
915915
this.visit_ty(self_ty);
916-
walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl);
916+
walk_list!(this, visit_assoc_item, items, AssocCtxt::Impl { of_trait: false });
917917
});
918918
walk_list!(self, visit_attribute, &item.attrs);
919919
return; // Avoid visiting again.
@@ -1414,7 +1414,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
14141414
self.check_defaultness(item.span, item.kind.defaultness());
14151415
}
14161416

1417-
if ctxt == AssocCtxt::Impl {
1417+
if let AssocCtxt::Impl { .. } = ctxt {
14181418
match &item.kind {
14191419
AssocItemKind::Const(box ConstItem { expr: None, .. }) => {
14201420
self.dcx().emit_err(errors::AssocConstWithoutBody {

compiler/rustc_builtin_macros/src/autodiff.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ mod llvm_enzyme {
157157
};
158158
(sig.clone(), false)
159159
}
160-
Annotatable::AssocItem(assoc_item, _) => {
160+
Annotatable::AssocItem(assoc_item, Impl { of_trait: false }) => {
161161
let sig = match &assoc_item.kind {
162162
ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) => sig,
163163
_ => {
@@ -296,7 +296,7 @@ mod llvm_enzyme {
296296
}
297297
Annotatable::Item(iitem.clone())
298298
}
299-
Annotatable::AssocItem(ref mut assoc_item, i @ Impl) => {
299+
Annotatable::AssocItem(ref mut assoc_item, i @ Impl { of_trait: false }) => {
300300
if !assoc_item.attrs.iter().any(|a| same_attribute(&a.kind, &attr.kind)) {
301301
assoc_item.attrs.push(attr);
302302
}
@@ -327,7 +327,7 @@ mod llvm_enzyme {
327327
kind: assoc_item,
328328
tokens: None,
329329
});
330-
Annotatable::AssocItem(d_fn, Impl)
330+
Annotatable::AssocItem(d_fn, Impl { of_trait: false })
331331
} else {
332332
let mut d_fn =
333333
ecx.item(span, d_ident, thin_vec![d_attr, inline_never], ItemKind::Fn(asdf));

compiler/rustc_builtin_macros/src/cfg_eval.rs

+3-10
Original file line numberDiff line numberDiff line change
@@ -121,18 +121,11 @@ impl CfgEval<'_> {
121121
let item = parser.parse_item(ForceCollect::Yes)?.unwrap();
122122
Annotatable::Item(self.flat_map_item(item).pop().unwrap())
123123
}
124-
Annotatable::AssocItem(_, AssocCtxt::Trait) => {
124+
Annotatable::AssocItem(_, ctxt) => {
125125
let item = parser.parse_trait_item(ForceCollect::Yes)?.unwrap().unwrap();
126126
Annotatable::AssocItem(
127-
self.flat_map_assoc_item(item, AssocCtxt::Trait).pop().unwrap(),
128-
AssocCtxt::Trait,
129-
)
130-
}
131-
Annotatable::AssocItem(_, AssocCtxt::Impl) => {
132-
let item = parser.parse_impl_item(ForceCollect::Yes)?.unwrap().unwrap();
133-
Annotatable::AssocItem(
134-
self.flat_map_assoc_item(item, AssocCtxt::Impl).pop().unwrap(),
135-
AssocCtxt::Impl,
127+
self.flat_map_assoc_item(item, ctxt).pop().unwrap(),
128+
ctxt,
136129
)
137130
}
138131
Annotatable::ForeignItem(_) => {

compiler/rustc_expand/src/base.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ impl Annotatable {
153153

154154
pub fn expect_impl_item(self) -> P<ast::AssocItem> {
155155
match self {
156-
Annotatable::AssocItem(i, AssocCtxt::Impl) => i,
156+
Annotatable::AssocItem(i, AssocCtxt::Impl { .. }) => i,
157157
_ => panic!("expected Item"),
158158
}
159159
}
@@ -403,6 +403,11 @@ pub trait MacResult {
403403
None
404404
}
405405

406+
/// Creates zero or more impl items.
407+
fn make_trait_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
408+
None
409+
}
410+
406411
/// Creates zero or more trait items.
407412
fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
408413
None
@@ -516,6 +521,10 @@ impl MacResult for MacEager {
516521
self.impl_items
517522
}
518523

524+
fn make_trait_impl_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
525+
self.impl_items
526+
}
527+
519528
fn make_trait_items(self: Box<Self>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
520529
self.trait_items
521530
}
@@ -613,6 +622,10 @@ impl MacResult for DummyResult {
613622
Some(SmallVec::new())
614623
}
615624

625+
fn make_trait_impl_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
626+
Some(SmallVec::new())
627+
}
628+
616629
fn make_trait_items(self: Box<DummyResult>) -> Option<SmallVec<[P<ast::AssocItem>; 1]>> {
617630
Some(SmallVec::new())
618631
}

0 commit comments

Comments
 (0)