Skip to content

Commit c0c5a94

Browse files
committed
Lower anonymous structs or unions to HIR
1 parent 090d5ea commit c0c5a94

File tree

38 files changed

+289
-174
lines changed

38 files changed

+289
-174
lines changed

compiler/rustc_ast/src/ast.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2098,9 +2098,9 @@ pub enum TyKind {
20982098
/// A tuple (`(A, B, C, D,...)`).
20992099
Tup(ThinVec<P<Ty>>),
21002100
/// An anonymous struct type i.e. `struct { foo: Type }`
2101-
AnonStruct(ThinVec<FieldDef>),
2101+
AnonStruct(NodeId, ThinVec<FieldDef>),
21022102
/// An anonymous union type i.e. `union { bar: Type }`
2103-
AnonUnion(ThinVec<FieldDef>),
2103+
AnonUnion(NodeId, ThinVec<FieldDef>),
21042104
/// A path (`module::module::...::Type`), optionally
21052105
/// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
21062106
///

compiler/rustc_ast/src/mut_visit.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -514,7 +514,8 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) {
514514
visit_vec(bounds, |bound| vis.visit_param_bound(bound));
515515
}
516516
TyKind::MacCall(mac) => vis.visit_mac_call(mac),
517-
TyKind::AnonStruct(fields) | TyKind::AnonUnion(fields) => {
517+
TyKind::AnonStruct(id, fields) | TyKind::AnonUnion(id, fields) => {
518+
vis.visit_id(id);
518519
fields.flat_map_in_place(|field| vis.flat_map_field_def(field));
519520
}
520521
}

compiler/rustc_ast/src/visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) {
441441
TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err => {}
442442
TyKind::MacCall(mac) => visitor.visit_mac_call(mac),
443443
TyKind::Never | TyKind::CVarArgs => {}
444-
TyKind::AnonStruct(ref fields, ..) | TyKind::AnonUnion(ref fields, ..) => {
444+
TyKind::AnonStruct(_, ref fields) | TyKind::AnonUnion(_, ref fields) => {
445445
walk_list!(visitor, visit_field_def, fields)
446446
}
447447
}

compiler/rustc_ast_lowering/src/item.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -691,7 +691,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
691691
}
692692
}
693693

694-
fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
694+
pub(super) fn lower_field_def(
695+
&mut self,
696+
(index, f): (usize, &FieldDef),
697+
) -> hir::FieldDef<'hir> {
695698
let ty = if let TyKind::Path(qself, path) = &f.ty.kind {
696699
let t = self.lower_path_ty(
697700
&f.ty,

compiler/rustc_ast_lowering/src/lib.rs

+43-11
Original file line numberDiff line numberDiff line change
@@ -1358,17 +1358,49 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
13581358
TyKind::Err => {
13591359
hir::TyKind::Err(self.dcx().span_delayed_bug(t.span, "TyKind::Err lowered"))
13601360
}
1361-
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
1362-
#[allow(rustc::untranslatable_diagnostic)]
1363-
#[allow(rustc::diagnostic_outside_of_impl)]
1364-
TyKind::AnonStruct(ref _fields) => {
1365-
hir::TyKind::Err(self.dcx().span_err(t.span, "anonymous structs are unimplemented"))
1366-
}
1367-
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
1368-
#[allow(rustc::untranslatable_diagnostic)]
1369-
#[allow(rustc::diagnostic_outside_of_impl)]
1370-
TyKind::AnonUnion(ref _fields) => {
1371-
hir::TyKind::Err(self.dcx().span_err(t.span, "anonymous unions are unimplemented"))
1361+
// Lower the anonymous structs or unions in a nested lowering context.
1362+
//
1363+
// ```
1364+
// struct Foo {
1365+
// _: union {
1366+
// // ^__________________ <-- within the nested lowering context,
1367+
// /* fields */ // | we lower all fields defined into an
1368+
// } // | owner node of struct or union item
1369+
// // ^_____________________|
1370+
// }
1371+
//
1372+
TyKind::AnonStruct(def_node_id, fields) | TyKind::AnonUnion(def_node_id, fields) => {
1373+
let (def_kind, item_kind): (DefKind, fn(_, _) -> _) = match t.kind {
1374+
TyKind::AnonStruct(..) => (DefKind::Struct, hir::ItemKind::Struct),
1375+
TyKind::AnonUnion(..) => (DefKind::Union, hir::ItemKind::Union),
1376+
_ => unreachable!(),
1377+
};
1378+
let def_id = self.create_def(
1379+
self.current_hir_id_owner.def_id,
1380+
*def_node_id,
1381+
kw::Empty,
1382+
def_kind,
1383+
t.span,
1384+
);
1385+
debug!(?def_id);
1386+
let owner_id = hir::OwnerId { def_id };
1387+
self.with_hir_id_owner(*def_node_id, |this| {
1388+
let fields = this.arena.alloc_from_iter(
1389+
fields.iter().enumerate().map(|f| this.lower_field_def(f)),
1390+
);
1391+
let span = t.span;
1392+
let variant_data = hir::VariantData::Struct(fields, false);
1393+
// FIXME: capture the generics from the outer adt.
1394+
let generics = hir::Generics::empty();
1395+
hir::OwnerNode::Item(this.arena.alloc(hir::Item {
1396+
ident: Ident::new(kw::Empty, span),
1397+
owner_id,
1398+
kind: item_kind(variant_data, generics),
1399+
span: this.lower_span(span),
1400+
vis_span: this.lower_span(span.shrink_to_lo()),
1401+
}))
1402+
});
1403+
hir::TyKind::AnonAdt(hir::ItemId { owner_id })
13721404
}
13731405
TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
13741406
TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),

compiler/rustc_ast_passes/src/ast_validation.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -214,7 +214,7 @@ impl<'a> AstValidator<'a> {
214214
}
215215
}
216216
}
217-
TyKind::AnonStruct(ref fields, ..) | TyKind::AnonUnion(ref fields, ..) => {
217+
TyKind::AnonStruct(_, ref fields) | TyKind::AnonUnion(_, ref fields) => {
218218
walk_list!(self, visit_field_def, fields)
219219
}
220220
_ => visit::walk_ty(self, t),

compiler/rustc_ast_pretty/src/pprust/state.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -987,11 +987,11 @@ impl<'a> State<'a> {
987987
}
988988
self.pclose();
989989
}
990-
ast::TyKind::AnonStruct(fields) => {
990+
ast::TyKind::AnonStruct(_, fields) => {
991991
self.head("struct");
992992
self.print_record_struct_body(fields, ty.span);
993993
}
994-
ast::TyKind::AnonUnion(fields) => {
994+
ast::TyKind::AnonUnion(_, fields) => {
995995
self.head("union");
996996
self.print_record_struct_body(fields, ty.span);
997997
}

compiler/rustc_hir/src/def.rs

+2
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use rustc_data_structures::unord::UnordMap;
88
use rustc_macros::HashStable_Generic;
99
use rustc_span::def_id::{DefId, LocalDefId};
1010
use rustc_span::hygiene::MacroKind;
11+
use rustc_span::symbol::kw;
1112
use rustc_span::Symbol;
1213

1314
use std::array::IntoIter;
@@ -225,6 +226,7 @@ impl DefKind {
225226

226227
pub fn def_path_data(self, name: Symbol) -> DefPathData {
227228
match self {
229+
DefKind::Struct | DefKind::Union if name == kw::Empty => DefPathData::AnonAdt,
228230
DefKind::Mod
229231
| DefKind::Struct
230232
| DefKind::Union

compiler/rustc_hir/src/definitions.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,8 @@ pub enum DefPathData {
287287
/// An existential `impl Trait` type node.
288288
/// Argument position `impl Trait` have a `TypeNs` with their pretty-printed name.
289289
OpaqueTy,
290+
/// An anonymous struct or union type i.e. `struct { foo: Type }` or `union { bar: Type }`
291+
AnonAdt,
290292
}
291293

292294
impl Definitions {
@@ -409,8 +411,9 @@ impl DefPathData {
409411
match *self {
410412
TypeNs(name) if name == kw::Empty => None,
411413
TypeNs(name) | ValueNs(name) | MacroNs(name) | LifetimeNs(name) => Some(name),
414+
412415
Impl | ForeignMod | CrateRoot | Use | GlobalAsm | Closure | Ctor | AnonConst
413-
| OpaqueTy => None,
416+
| OpaqueTy | AnonAdt => None,
414417
}
415418
}
416419

@@ -431,6 +434,7 @@ impl DefPathData {
431434
Ctor => DefPathDataName::Anon { namespace: sym::constructor },
432435
AnonConst => DefPathDataName::Anon { namespace: sym::constant },
433436
OpaqueTy => DefPathDataName::Anon { namespace: sym::opaque },
437+
AnonAdt => DefPathDataName::Anon { namespace: sym::anon_adt },
434438
}
435439
}
436440
}

compiler/rustc_hir/src/hir.rs

+2
Original file line numberDiff line numberDiff line change
@@ -2569,6 +2569,8 @@ pub enum TyKind<'hir> {
25692569
Never,
25702570
/// A tuple (`(A, B, C, D, ...)`).
25712571
Tup(&'hir [Ty<'hir>]),
2572+
/// An anonymous struct or union type i.e. `struct { foo: Type }` or `union { foo: Type }`
2573+
AnonAdt(ItemId),
25722574
/// A path to a type definition (`module::module::...::Type`), or an
25732575
/// associated type (e.g., `<Vec<T> as Trait>::Type` or `<T>::Target`).
25742576
///

compiler/rustc_hir/src/intravisit.rs

+3
Original file line numberDiff line numberDiff line change
@@ -862,6 +862,9 @@ pub fn walk_ty<'v, V: Visitor<'v>>(visitor: &mut V, typ: &'v Ty<'v>) {
862862
}
863863
TyKind::Typeof(ref expression) => visitor.visit_anon_const(expression),
864864
TyKind::Infer | TyKind::Err(_) => {}
865+
TyKind::AnonAdt(item_id) => {
866+
visitor.visit_nested_item(item_id);
867+
}
865868
}
866869
}
867870

compiler/rustc_hir_analysis/src/astconv/mod.rs

+13
Original file line numberDiff line numberDiff line change
@@ -2356,6 +2356,19 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
23562356
hir::TyKind::Tup(fields) => {
23572357
Ty::new_tup_from_iter(tcx, fields.iter().map(|t| self.ast_ty_to_ty(t)))
23582358
}
2359+
hir::TyKind::AnonAdt(item_id) => {
2360+
let did = item_id.owner_id.def_id;
2361+
let adt_def = tcx.adt_def(did);
2362+
let generics = tcx.generics_of(did);
2363+
2364+
debug!("ast_ty_to_ty_inner(AnonAdt): generics={:?}", generics);
2365+
let args = ty::GenericArgs::for_item(tcx, did.to_def_id(), |param, _| {
2366+
tcx.mk_param_from_def(param)
2367+
});
2368+
debug!("ast_ty_to_ty_inner(AnonAdt): args={:?}", args);
2369+
2370+
Ty::new_adt(tcx, adt_def, tcx.mk_args(args))
2371+
}
23592372
hir::TyKind::BareFn(bf) => {
23602373
require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
23612374

compiler/rustc_hir_analysis/src/collect.rs

+74-8
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,65 @@ fn convert_enum_variant_types(tcx: TyCtxt<'_>, def_id: DefId) {
781781
}
782782
}
783783

784+
/*
785+
/// In a type definition, we check that unnamed field names are distinct.
786+
fn check_unnamed_fields_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>) {
787+
let mut seen_fields: FxHashMap<Ident, Option<Span>> = Default::default();
788+
fn check_fields_anon_adt_defn<'tcx>(tcx: TyCtxt<'tcx>, item: &hir::Item<'tcx>, seen_fields: &mut FxHashMap<Ident, Option<Span>>) {
789+
let fields = match &item.kind {
790+
hir::ItemKind::Struct(fields, _) | hir::ItemKind::Union(fields, _) => fields,
791+
_ => return,
792+
};
793+
for field in fields.fields() {
794+
if field.ident.name == kw::Underscore {
795+
if let hir::TyKind::AnonAdt(item_id) = field.ty.kind() {
796+
let item = tcx.hir().item(item_id);
797+
check_fields_anon_adt_defn(tcx, item, &mut *seen_fields);
798+
} else {
799+
let field_ty = match tcx.type_of(field.def_id).instantiate_identity().ty_adt_def() {
800+
Some(adt_ty) => adt_ty,
801+
None => {
802+
tcx.sess.emit_err(err);
803+
return;
804+
}
805+
};
806+
if let Some(def_id) = field_ty.did().as_local() {
807+
let item = tcx.hir().item(hir::ItemId { owner_id: hir::OwnerId { def_id }});
808+
check_fields_anon_adt_defn(tcx, item, &mut *seen_fields);
809+
}
810+
}
811+
field_ty.flags()
812+
let inner_adt_def = field_ty.ty_adt_def().expect("expect an adt");
813+
check_fields_anon_adt_defn(tcx, adt_def, &mut *seen_fields);
814+
} else {
815+
let span = field.did.as_local().map(|did| {
816+
let hir_id = tcx.hir().local_def_id_to_hir_id(did);
817+
tcx.hir().span(hir_id)
818+
});
819+
match seen_fields.get(&ident.normalize_to_macros_2_0()).cloned() {
820+
Some(Some(prev_span)) => {
821+
tcx.sess.emit_err(errors::FieldAlreadyDeclared {
822+
field_name: ident,
823+
span: f.span,
824+
prev_span,
825+
});
826+
}
827+
Some(None) => {
828+
tcx.sess.emit_err(errors::FieldAlreadyDeclared {
829+
field_name: f.ident,
830+
span: f.span,
831+
prev_span,
832+
});
833+
}
834+
None =>
835+
seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
836+
}
837+
}
838+
}
839+
}
840+
}
841+
*/
842+
784843
fn convert_variant(
785844
tcx: TyCtxt<'_>,
786845
variant_did: Option<LocalDefId>,
@@ -790,11 +849,17 @@ fn convert_variant(
790849
adt_kind: ty::AdtKind,
791850
parent_did: LocalDefId,
792851
) -> ty::VariantDef {
852+
let mut has_unnamed_fields = false;
793853
let mut seen_fields: FxHashMap<Ident, Span> = Default::default();
794854
let fields = def
795855
.fields()
796856
.iter()
797-
.map(|f| {
857+
.inspect(|f| {
858+
// Skip the unnamed field here, we will check it later.
859+
if f.ident.name == kw::Underscore {
860+
has_unnamed_fields = true;
861+
return;
862+
}
798863
let dup_span = seen_fields.get(&f.ident.normalize_to_macros_2_0()).cloned();
799864
if let Some(prev_span) = dup_span {
800865
tcx.dcx().emit_err(errors::FieldAlreadyDeclared {
@@ -805,12 +870,11 @@ fn convert_variant(
805870
} else {
806871
seen_fields.insert(f.ident.normalize_to_macros_2_0(), f.span);
807872
}
808-
809-
ty::FieldDef {
810-
did: f.def_id.to_def_id(),
811-
name: f.ident.name,
812-
vis: tcx.visibility(f.def_id),
813-
}
873+
})
874+
.map(|f| ty::FieldDef {
875+
did: f.def_id.to_def_id(),
876+
name: f.ident.name,
877+
vis: tcx.visibility(f.def_id),
814878
})
815879
.collect();
816880
let recovered = match def {
@@ -829,6 +893,7 @@ fn convert_variant(
829893
adt_kind == AdtKind::Struct && tcx.has_attr(parent_did, sym::non_exhaustive)
830894
|| variant_did
831895
.is_some_and(|variant_did| tcx.has_attr(variant_did, sym::non_exhaustive)),
896+
has_unnamed_fields,
832897
)
833898
}
834899

@@ -839,6 +904,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
839904
bug!("expected ADT to be an item");
840905
};
841906

907+
let is_anonymous = item.ident.name == kw::Empty;
842908
let repr = tcx.repr_options_of_def(def_id.to_def_id());
843909
let (kind, variants) = match &item.kind {
844910
ItemKind::Enum(def, _) => {
@@ -889,7 +955,7 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
889955
}
890956
_ => bug!("{:?} is not an ADT", item.owner_id.def_id),
891957
};
892-
tcx.mk_adt_def(def_id.to_def_id(), kind, variants, repr)
958+
tcx.mk_adt_def(def_id.to_def_id(), kind, variants, repr, is_anonymous)
893959
}
894960

895961
fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {

compiler/rustc_hir_pretty/src/lib.rs

+21-16
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,7 @@ impl<'a> State<'a> {
323323
hir::TyKind::Infer => {
324324
self.word("_");
325325
}
326+
hir::TyKind::AnonAdt(..) => self.word("/* anonymous adt */"),
326327
}
327328
self.end()
328329
}
@@ -723,26 +724,30 @@ impl<'a> State<'a> {
723724
}
724725
hir::VariantData::Struct { .. } => {
725726
self.print_where_clause(generics);
726-
self.nbsp();
727-
self.bopen();
728-
self.hardbreak_if_not_bol();
729-
730-
for field in struct_def.fields() {
731-
self.hardbreak_if_not_bol();
732-
self.maybe_print_comment(field.span.lo());
733-
self.print_outer_attributes(self.attrs(field.hir_id));
734-
self.print_ident(field.ident);
735-
self.word_nbsp(":");
736-
self.print_type(field.ty);
737-
self.word(",");
738-
}
739-
740-
self.bclose(span)
727+
self.print_variant_struct(span, struct_def.fields())
741728
}
742729
}
743730
}
744731

745-
fn print_variant(&mut self, v: &hir::Variant<'_>) {
732+
fn print_variant_struct(&mut self, span: rustc_span::Span, fields: &[hir::FieldDef<'_>]) {
733+
self.nbsp();
734+
self.bopen();
735+
self.hardbreak_if_not_bol();
736+
737+
for field in fields {
738+
self.hardbreak_if_not_bol();
739+
self.maybe_print_comment(field.span.lo());
740+
self.print_outer_attributes(self.attrs(field.hir_id));
741+
self.print_ident(field.ident);
742+
self.word_nbsp(":");
743+
self.print_type(field.ty);
744+
self.word(",");
745+
}
746+
747+
self.bclose(span)
748+
}
749+
750+
pub fn print_variant(&mut self, v: &hir::Variant<'_>) {
746751
self.head("");
747752
let generics = hir::Generics::empty();
748753
self.print_struct(&v.data, generics, v.ident.name, v.span, false);

0 commit comments

Comments
 (0)