Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 1107fc7

Browse files
authoredMar 25, 2025
Rollup merge of rust-lang#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

Lines changed: 3 additions & 1 deletion
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

Lines changed: 7 additions & 2 deletions
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

Lines changed: 12 additions & 4 deletions
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

Lines changed: 27 additions & 35 deletions
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

Lines changed: 0 additions & 2 deletions
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

Lines changed: 3 additions & 3 deletions
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

Lines changed: 3 additions & 3 deletions
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

Lines changed: 3 additions & 10 deletions
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

Lines changed: 14 additions & 1 deletion
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
}

‎compiler/rustc_expand/src/expand.rs

Lines changed: 86 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -188,9 +188,15 @@ ast_fragments! {
188188
ImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
189189
"impl item";
190190
many fn flat_map_assoc_item;
191-
fn visit_assoc_item(AssocCtxt::Impl);
191+
fn visit_assoc_item(AssocCtxt::Impl { of_trait: false });
192192
fn make_impl_items;
193193
}
194+
TraitImplItems(SmallVec<[P<ast::AssocItem>; 1]>) {
195+
"impl item";
196+
many fn flat_map_assoc_item;
197+
fn visit_assoc_item(AssocCtxt::Impl { of_trait: true });
198+
fn make_trait_impl_items;
199+
}
194200
ForeignItems(SmallVec<[P<ast::ForeignItem>; 1]>) {
195201
"foreign item";
196202
many fn flat_map_foreign_item;
@@ -257,6 +263,7 @@ impl AstFragmentKind {
257263
AstFragmentKind::Items
258264
| AstFragmentKind::TraitItems
259265
| AstFragmentKind::ImplItems
266+
| AstFragmentKind::TraitImplItems
260267
| AstFragmentKind::ForeignItems
261268
| AstFragmentKind::Crate => SupportsMacroExpansion::Yes { supports_inner_attrs: true },
262269
AstFragmentKind::Arms
@@ -306,6 +313,9 @@ impl AstFragmentKind {
306313
AstFragmentKind::ImplItems => {
307314
AstFragment::ImplItems(items.map(Annotatable::expect_impl_item).collect())
308315
}
316+
AstFragmentKind::TraitImplItems => {
317+
AstFragment::TraitImplItems(items.map(Annotatable::expect_impl_item).collect())
318+
}
309319
AstFragmentKind::TraitItems => {
310320
AstFragment::TraitItems(items.map(Annotatable::expect_trait_item).collect())
311321
}
@@ -347,10 +357,10 @@ pub enum InvocationKind {
347357
},
348358
Attr {
349359
attr: ast::Attribute,
350-
// Re-insertion position for inert attributes.
360+
/// Re-insertion position for inert attributes.
351361
pos: usize,
352362
item: Annotatable,
353-
// Required for resolving derive helper attributes.
363+
/// Required for resolving derive helper attributes.
354364
derives: Vec<ast::Path>,
355365
},
356366
Derive {
@@ -360,6 +370,8 @@ pub enum InvocationKind {
360370
},
361371
GlobDelegation {
362372
item: P<ast::AssocItem>,
373+
/// Whether this is a trait impl or an inherent impl
374+
of_trait: bool,
363375
},
364376
}
365377

@@ -388,7 +400,7 @@ impl Invocation {
388400
InvocationKind::Bang { span, .. } => *span,
389401
InvocationKind::Attr { attr, .. } => attr.span,
390402
InvocationKind::Derive { path, .. } => path.span,
391-
InvocationKind::GlobDelegation { item } => item.span,
403+
InvocationKind::GlobDelegation { item, .. } => item.span,
392404
}
393405
}
394406

@@ -397,7 +409,7 @@ impl Invocation {
397409
InvocationKind::Bang { span, .. } => span,
398410
InvocationKind::Attr { attr, .. } => &mut attr.span,
399411
InvocationKind::Derive { path, .. } => &mut path.span,
400-
InvocationKind::GlobDelegation { item } => &mut item.span,
412+
InvocationKind::GlobDelegation { item, .. } => &mut item.span,
401413
}
402414
}
403415
}
@@ -820,7 +832,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
820832
}
821833
_ => unreachable!(),
822834
},
823-
InvocationKind::GlobDelegation { item } => {
835+
InvocationKind::GlobDelegation { item, of_trait } => {
824836
let AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() };
825837
let suffixes = match ext {
826838
SyntaxExtensionKind::GlobDelegation(expander) => match expander.expand(self.cx)
@@ -829,7 +841,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
829841
ExpandResult::Retry(()) => {
830842
// Reassemble the original invocation for retrying.
831843
return ExpandResult::Retry(Invocation {
832-
kind: InvocationKind::GlobDelegation { item },
844+
kind: InvocationKind::GlobDelegation { item, of_trait },
833845
..invoc
834846
});
835847
}
@@ -847,7 +859,8 @@ impl<'a, 'b> MacroExpander<'a, 'b> {
847859
self.cx, deleg, &item, &suffixes, item.span, true,
848860
);
849861
fragment_kind.expect_from_annotatables(
850-
single_delegations.map(|item| Annotatable::AssocItem(P(item), AssocCtxt::Impl)),
862+
single_delegations
863+
.map(|item| Annotatable::AssocItem(P(item), AssocCtxt::Impl { of_trait })),
851864
)
852865
}
853866
})
@@ -973,6 +986,13 @@ pub fn parse_ast_fragment<'a>(
973986
}
974987
AstFragment::ImplItems(items)
975988
}
989+
AstFragmentKind::TraitImplItems => {
990+
let mut items = SmallVec::new();
991+
while let Some(item) = this.parse_impl_item(ForceCollect::No)? {
992+
items.extend(item);
993+
}
994+
AstFragment::TraitImplItems(items)
995+
}
976996
AstFragmentKind::ForeignItems => {
977997
let mut items = SmallVec::new();
978998
while let Some(item) = this.parse_foreign_item(ForceCollect::No)? {
@@ -1355,13 +1375,13 @@ impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, ImplItemTag>
13551375
type ItemKind = AssocItemKind;
13561376
const KIND: AstFragmentKind = AstFragmentKind::ImplItems;
13571377
fn to_annotatable(self) -> Annotatable {
1358-
Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl)
1378+
Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl { of_trait: false })
13591379
}
13601380
fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
13611381
fragment.make_impl_items()
13621382
}
13631383
fn walk_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1364-
walk_flat_map_assoc_item(visitor, self.wrapped, AssocCtxt::Impl)
1384+
walk_flat_map_assoc_item(visitor, self.wrapped, AssocCtxt::Impl { of_trait: false })
13651385
}
13661386
fn is_mac_call(&self) -> bool {
13671387
matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
@@ -1390,6 +1410,47 @@ impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, ImplItemTag>
13901410
}
13911411
}
13921412

1413+
struct TraitImplItemTag;
1414+
impl InvocationCollectorNode for AstNodeWrapper<P<ast::AssocItem>, TraitImplItemTag> {
1415+
type OutputTy = SmallVec<[P<ast::AssocItem>; 1]>;
1416+
type ItemKind = AssocItemKind;
1417+
const KIND: AstFragmentKind = AstFragmentKind::TraitImplItems;
1418+
fn to_annotatable(self) -> Annotatable {
1419+
Annotatable::AssocItem(self.wrapped, AssocCtxt::Impl { of_trait: true })
1420+
}
1421+
fn fragment_to_output(fragment: AstFragment) -> Self::OutputTy {
1422+
fragment.make_trait_impl_items()
1423+
}
1424+
fn walk_flat_map<V: MutVisitor>(self, visitor: &mut V) -> Self::OutputTy {
1425+
walk_flat_map_assoc_item(visitor, self.wrapped, AssocCtxt::Impl { of_trait: true })
1426+
}
1427+
fn is_mac_call(&self) -> bool {
1428+
matches!(self.wrapped.kind, AssocItemKind::MacCall(..))
1429+
}
1430+
fn take_mac_call(self) -> (P<ast::MacCall>, Self::AttrsTy, AddSemicolon) {
1431+
let item = self.wrapped.into_inner();
1432+
match item.kind {
1433+
AssocItemKind::MacCall(mac) => (mac, item.attrs, AddSemicolon::No),
1434+
_ => unreachable!(),
1435+
}
1436+
}
1437+
fn delegation(&self) -> Option<(&ast::DelegationMac, &ast::Item<Self::ItemKind>)> {
1438+
match &self.wrapped.kind {
1439+
AssocItemKind::DelegationMac(deleg) => Some((deleg, &self.wrapped)),
1440+
_ => None,
1441+
}
1442+
}
1443+
fn delegation_item_kind(deleg: Box<ast::Delegation>) -> Self::ItemKind {
1444+
AssocItemKind::Delegation(deleg)
1445+
}
1446+
fn from_item(item: ast::Item<Self::ItemKind>) -> Self {
1447+
AstNodeWrapper::new(P(item), TraitImplItemTag)
1448+
}
1449+
fn flatten_outputs(items: impl Iterator<Item = Self::OutputTy>) -> Self::OutputTy {
1450+
items.flatten().collect()
1451+
}
1452+
}
1453+
13931454
impl InvocationCollectorNode for P<ast::ForeignItem> {
13941455
const KIND: AstFragmentKind = AstFragmentKind::ForeignItems;
13951456
fn to_annotatable(self) -> Annotatable {
@@ -1855,9 +1916,10 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
18551916
fn collect_glob_delegation(
18561917
&mut self,
18571918
item: P<ast::AssocItem>,
1919+
of_trait: bool,
18581920
kind: AstFragmentKind,
18591921
) -> AstFragment {
1860-
self.collect(kind, InvocationKind::GlobDelegation { item })
1922+
self.collect(kind, InvocationKind::GlobDelegation { item, of_trait })
18611923
}
18621924

18631925
/// If `item` is an attribute invocation, remove the attribute and return it together with
@@ -2030,8 +2092,10 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
20302092
let Some(suffixes) = &deleg.suffixes else {
20312093
let traitless_qself =
20322094
matches!(&deleg.qself, Some(qself) if qself.position == 0);
2033-
let item = match node.to_annotatable() {
2034-
Annotatable::AssocItem(item, AssocCtxt::Impl) => item,
2095+
let (item, of_trait) = match node.to_annotatable() {
2096+
Annotatable::AssocItem(item, AssocCtxt::Impl { of_trait }) => {
2097+
(item, of_trait)
2098+
}
20352099
ann @ (Annotatable::Item(_)
20362100
| Annotatable::AssocItem(..)
20372101
| Annotatable::Stmt(_)) => {
@@ -2046,7 +2110,9 @@ impl<'a, 'b> InvocationCollector<'a, 'b> {
20462110
self.cx.dcx().emit_err(GlobDelegationTraitlessQpath { span });
20472111
return Default::default();
20482112
}
2049-
return self.collect_glob_delegation(item, Node::KIND).make_ast::<Node>();
2113+
return self
2114+
.collect_glob_delegation(item, of_trait, Node::KIND)
2115+
.make_ast::<Node>();
20502116
};
20512117

20522118
let single_delegations = build_single_delegations::<Node>(
@@ -2126,7 +2192,12 @@ impl<'a, 'b> MutVisitor for InvocationCollector<'a, 'b> {
21262192
) -> SmallVec<[P<ast::AssocItem>; 1]> {
21272193
match ctxt {
21282194
AssocCtxt::Trait => self.flat_map_node(AstNodeWrapper::new(node, TraitItemTag)),
2129-
AssocCtxt::Impl => self.flat_map_node(AstNodeWrapper::new(node, ImplItemTag)),
2195+
AssocCtxt::Impl { of_trait: false } => {
2196+
self.flat_map_node(AstNodeWrapper::new(node, ImplItemTag))
2197+
}
2198+
AssocCtxt::Impl { of_trait: true } => {
2199+
self.flat_map_node(AstNodeWrapper::new(node, TraitImplItemTag))
2200+
}
21302201
}
21312202
}
21322203

‎compiler/rustc_expand/src/placeholders.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,17 @@ pub(crate) fn placeholder(
8686
kind: ast::AssocItemKind::MacCall(mac_placeholder()),
8787
tokens: None,
8888
})]),
89+
AstFragmentKind::TraitImplItems => {
90+
AstFragment::TraitImplItems(smallvec![P(ast::AssocItem {
91+
id,
92+
span,
93+
ident,
94+
vis,
95+
attrs,
96+
kind: ast::AssocItemKind::MacCall(mac_placeholder()),
97+
tokens: None,
98+
})])
99+
}
89100
AstFragmentKind::ForeignItems => {
90101
AstFragment::ForeignItems(smallvec![P(ast::ForeignItem {
91102
id,
@@ -308,7 +319,8 @@ impl MutVisitor for PlaceholderExpander {
308319
let it = self.remove(item.id);
309320
match ctxt {
310321
AssocCtxt::Trait => it.make_trait_items(),
311-
AssocCtxt::Impl => it.make_impl_items(),
322+
AssocCtxt::Impl { of_trait: false } => it.make_impl_items(),
323+
AssocCtxt::Impl { of_trait: true } => it.make_trait_impl_items(),
312324
}
313325
}
314326
_ => walk_flat_map_assoc_item(self, item, ctxt),

‎compiler/rustc_lint/src/early.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,7 @@ impl<'ast, 'ecx, 'tcx, T: EarlyLintPass> ast_visit::Visitor<'ast>
241241
ast_visit::AssocCtxt::Trait => {
242242
lint_callback!(cx, check_trait_item, item);
243243
}
244-
ast_visit::AssocCtxt::Impl => {
244+
ast_visit::AssocCtxt::Impl { .. } => {
245245
lint_callback!(cx, check_impl_item, item);
246246
}
247247
}
@@ -250,7 +250,7 @@ impl<'ast, 'ecx, 'tcx, T: EarlyLintPass> ast_visit::Visitor<'ast>
250250
ast_visit::AssocCtxt::Trait => {
251251
lint_callback!(cx, check_trait_item_post, item);
252252
}
253-
ast_visit::AssocCtxt::Impl => {
253+
ast_visit::AssocCtxt::Impl { .. } => {
254254
lint_callback!(cx, check_impl_item_post, item);
255255
}
256256
}

‎compiler/rustc_resolve/src/build_reduced_graph.rs

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -884,10 +884,10 @@ impl<'a, 'ra, 'tcx> BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
884884
}
885885

886886
// These items do not add names to modules.
887-
ItemKind::Impl(box Impl { of_trait: Some(..), .. }) => {
888-
self.r.trait_impl_items.insert(local_def_id);
889-
}
890-
ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {}
887+
ItemKind::Impl(box Impl { of_trait: Some(..), .. })
888+
| ItemKind::Impl { .. }
889+
| ItemKind::ForeignMod(..)
890+
| ItemKind::GlobalAsm(..) => {}
891891

892892
ItemKind::MacroDef(..) | ItemKind::MacCall(_) | ItemKind::DelegationMac(..) => {
893893
unreachable!()
@@ -1377,7 +1377,7 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
13771377
AssocCtxt::Trait => {
13781378
self.visit_invoc_in_module(item.id);
13791379
}
1380-
AssocCtxt::Impl => {
1380+
AssocCtxt::Impl { .. } => {
13811381
let invoc_id = item.id.placeholder_to_expn_id();
13821382
if !self.r.glob_delegation_invoc_ids.contains(&invoc_id) {
13831383
self.r
@@ -1397,9 +1397,8 @@ impl<'a, 'ra, 'tcx> Visitor<'a> for BuildReducedGraphVisitor<'a, 'ra, 'tcx> {
13971397
let local_def_id = feed.key();
13981398
let def_id = local_def_id.to_def_id();
13991399

1400-
if !(ctxt == AssocCtxt::Impl
1401-
&& matches!(item.vis.kind, ast::VisibilityKind::Inherited)
1402-
&& self.r.trait_impl_items.contains(&self.r.tcx.local_parent(local_def_id)))
1400+
if !(matches!(ctxt, AssocCtxt::Impl { of_trait: true })
1401+
&& matches!(item.vis.kind, ast::VisibilityKind::Inherited))
14031402
{
14041403
// Trait impl item visibility is inherited from its trait when not specified
14051404
// explicitly. In that case we cannot determine it here in early resolve,

‎compiler/rustc_resolve/src/late.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3375,7 +3375,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
33753375
|i, s, c| MethodNotMemberOfTrait(i, s, c),
33763376
);
33773377

3378-
visit::walk_assoc_item(this, item, AssocCtxt::Impl)
3378+
visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
33793379
},
33803380
);
33813381

@@ -3409,7 +3409,7 @@ impl<'a, 'ast, 'ra: 'ast, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
34093409
|i, s, c| TypeNotMemberOfTrait(i, s, c),
34103410
);
34113411

3412-
visit::walk_assoc_item(this, item, AssocCtxt::Impl)
3412+
visit::walk_assoc_item(this, item, AssocCtxt::Impl { of_trait: true })
34133413
});
34143414
},
34153415
);

‎compiler/rustc_resolve/src/lib.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1191,10 +1191,6 @@ pub struct Resolver<'ra, 'tcx> {
11911191
/// and how the `impl Trait` fragments were introduced.
11921192
invocation_parents: FxHashMap<LocalExpnId, InvocationParent>,
11931193

1194-
/// Some way to know that we are in a *trait* impl in `visit_assoc_item`.
1195-
/// FIXME: Replace with a more general AST map (together with some other fields).
1196-
trait_impl_items: FxHashSet<LocalDefId>,
1197-
11981194
legacy_const_generic_args: FxHashMap<DefId, Option<Vec<usize>>>,
11991195
/// Amount of lifetime parameters for each item in the crate.
12001196
item_generics_num_lifetimes: FxHashMap<LocalDefId, usize>,
@@ -1558,7 +1554,6 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
15581554
def_id_to_node_id,
15591555
placeholder_field_indices: Default::default(),
15601556
invocation_parents,
1561-
trait_impl_items: Default::default(),
15621557
legacy_const_generic_args: Default::default(),
15631558
item_generics_num_lifetimes: Default::default(),
15641559
main_def: Default::default(),

‎compiler/rustc_resolve/src/macros.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ impl<'ra, 'tcx> ResolverExpand for Resolver<'ra, 'tcx> {
264264
}
265265
InvocationKind::Bang { ref mac, .. } => (&mac.path, MacroKind::Bang),
266266
InvocationKind::Derive { ref path, .. } => (path, MacroKind::Derive),
267-
InvocationKind::GlobDelegation { ref item } => {
267+
InvocationKind::GlobDelegation { ref item, .. } => {
268268
let ast::AssocItemKind::DelegationMac(deleg) = &item.kind else { unreachable!() };
269269
deleg_impl = Some(self.invocation_parent(invoc_id));
270270
// It is sufficient to consider glob delegation a bang macro for now.

‎src/tools/rustfmt/src/visitor.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,8 @@ impl<'b, 'a: 'b> FmtVisitor<'a> {
624624
// TODO(calebcartwright): Not sure the skip spans are correct
625625
let (ai, skip_span, assoc_ctxt) = match visitor_kind {
626626
AssocTraitItem(ai) => (*ai, ai.span(), visit::AssocCtxt::Trait),
627-
AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl),
627+
// There is no difference between trait and inherent assoc item formatting
628+
AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl { of_trait: false }),
628629
_ => unreachable!(),
629630
};
630631
skip_out_of_file_lines_range_visitor!(self, ai.span);

0 commit comments

Comments
 (0)
This repository has been archived.