Skip to content

Commit

Permalink
Parse unnamed fields and anonymous structs or unions
Browse files Browse the repository at this point in the history
Anonymous structs or unions are parsed as a special type of field,
instead of a gerenal kind of `Ty`.
  • Loading branch information
frank-king committed Sep 11, 2023
1 parent 6645a93 commit 1320961
Show file tree
Hide file tree
Showing 26 changed files with 590 additions and 178 deletions.
152 changes: 147 additions & 5 deletions compiler/rustc_ast/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2092,10 +2092,6 @@ pub enum TyKind {
Never,
/// A tuple (`(A, B, C, D,...)`).
Tup(ThinVec<P<Ty>>),
/// An anonymous struct type i.e. `struct { foo: Type }`
AnonStruct(ThinVec<FieldDef>),
/// An anonymous union type i.e. `union { bar: Type }`
AnonUnion(ThinVec<FieldDef>),
/// A path (`module::module::...::Type`), optionally
/// "qualified", e.g., `<Vec<T> as SomeTrait>::SomeType`.
///
Expand Down Expand Up @@ -2715,6 +2711,93 @@ impl VisibilityKind {
}
}

#[derive(Clone, Copy, Encodable, Decodable, Debug)]
pub enum AnonRecordKind {
Struct,
Union,
}

impl AnonRecordKind {
/// Returns the lowercase name.
pub fn name(self) -> &'static str {
match self {
Self::Struct => "struct",
Self::Union => "union",
}
}
}

/// An anonymous struct or union, i.e. `struct { foo: Foo }` or `union { foo: Foo }`.
#[derive(Clone, Encodable, Decodable, Debug)]
pub struct AnonRecord {
pub id: NodeId,
pub span: Span,
pub fields: ThinVec<FieldDef>,
pub kind: AnonRecordKind,
pub recovered: bool,
}

impl AnonRecord {
pub fn is_union(&self) -> bool {
matches!(self.kind, AnonRecordKind::Union)
}
pub fn is_struct(&self) -> bool {
matches!(self.kind, AnonRecordKind::Struct)
}
}

/// Type of fields in a struct, variant or union.
#[derive(Clone, Encodable, Decodable, Debug)]
pub enum FieldTy {
Ty(P<Ty>),
/// An anonymous struct or union, i.e. `struct { foo: Foo }` or `union { foo: Foo }`.
// AnonRecord(P<Item>),
AnonRecord(P<AnonRecord>),
}

impl From<P<Ty>> for FieldTy {
fn from(ty: P<Ty>) -> Self {
Self::Ty(ty)
}
}

impl From<AnonRecord> for FieldTy {
fn from(anon_record: AnonRecord) -> Self {
Self::AnonRecord(P(anon_record))
}
}

impl FieldTy {
pub fn id(&self) -> NodeId {
match self {
Self::Ty(ty) => ty.id,
Self::AnonRecord(anon_record) => anon_record.id,
}
}

pub fn span(&self) -> Span {
match self {
Self::Ty(ty) => ty.span,
Self::AnonRecord(anon_record) => anon_record.span,
}
}

pub fn as_ty(&self) -> Option<&P<Ty>> {
match self {
Self::Ty(ty) => Some(ty),
_ => None,
}
}

/// Expects a `Ty`, otherwise panics.
pub fn expect_ty(&self) -> &P<Ty> {
let FieldTy::Ty(ty) = &self else {
panic!("expect a type, found {self:?}");
};
ty
}
}

/// Field definition in a struct, variant or union.
///
/// E.g., `bar: usize` as in `struct Foo { bar: usize }`.
Expand All @@ -2726,7 +2809,7 @@ pub struct FieldDef {
pub vis: Visibility,
pub ident: Option<Ident>,

pub ty: P<Ty>,
pub ty: FieldTy,
pub is_placeholder: bool,
}

Expand Down Expand Up @@ -2756,6 +2839,27 @@ impl VariantData {
}
}

/// Return all fields of this variant, with anonymous structs or unions flattened.
pub fn all_fields(&self) -> AllFields<'_> {
AllFields { iters: smallvec::smallvec![self.fields().iter()] }
}

/// Return whether this variant contains inner anonymous unions.
pub fn find_inner_union(&self) -> Option<Span> {
// We only check the record-like structs
let VariantData::Struct(fields, ..) = self else { return None };
fn find_union(fields: &[FieldDef]) -> Option<Span> {
fields.iter().find_map(|field| {
let FieldTy::AnonRecord(anon_record) = &field.ty else { return None };
anon_record
.is_union()
.then(|| anon_record.span)
.or_else(|| find_union(&anon_record.fields))
})
}
find_union(&fields)
}

/// Return the `NodeId` of this variant's constructor, if it has one.
pub fn ctor_node_id(&self) -> Option<NodeId> {
match *self {
Expand All @@ -2765,6 +2869,44 @@ impl VariantData {
}
}

/// Iterator of all fields of a `VariantData`.
///
/// It iterates on the field tree in preorder, where the unnamed fields with anonymous structs or unions
/// are flattened to their inner fields.
pub struct AllFields<'a> {
iters: smallvec::SmallVec<[std::slice::Iter<'a, FieldDef>; 1]>,
}

impl<'a> Iterator for AllFields<'a> {
type Item = &'a FieldDef;

fn next(&mut self) -> Option<Self::Item> {
let mut top = self.iters.last_mut()?;
loop {
if let Some(field) = top.next() {
if let FieldTy::AnonRecord(anon_record) = &field.ty {
self.iters.push(anon_record.fields.iter());
top = self.iters.last_mut().unwrap();
continue;
}
return Some(field);
}
self.iters.pop();
top = self.iters.last_mut()?;
}
}

fn size_hint(&self) -> (usize, Option<usize>) {
match &self.iters[..] {
[] => (0, Some(0)),
[single] => (single.size_hint().0, None),
[first, .., last] => (first.size_hint().0 + last.size_hint().0, None),
}
}
}

impl std::iter::FusedIterator for AllFields<'_> {}

/// An item definition.
#[derive(Clone, Encodable, Decodable, Debug)]
pub struct Item<K = ItemKind> {
Expand Down
21 changes: 17 additions & 4 deletions compiler/rustc_ast/src/mut_visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ pub trait MutVisitor: Sized {
noop_visit_variant_data(vdata, self);
}

fn visit_anon_record(&mut self, anon_record: &mut AnonRecord) {
noop_visit_anon_record(anon_record, self);
}

fn flat_map_generic_param(&mut self, param: GenericParam) -> SmallVec<[GenericParam; 1]> {
noop_flat_map_generic_param(param, self)
}
Expand Down Expand Up @@ -510,9 +514,6 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) {
visit_vec(bounds, |bound| vis.visit_param_bound(bound));
}
TyKind::MacCall(mac) => vis.visit_mac_call(mac),
TyKind::AnonStruct(fields) | TyKind::AnonUnion(fields) => {
fields.flat_map_in_place(|field| vis.flat_map_field_def(field));
}
}
vis.visit_span(span);
visit_lazy_tts(tokens, vis);
Expand Down Expand Up @@ -978,6 +979,13 @@ pub fn noop_visit_variant_data<T: MutVisitor>(vdata: &mut VariantData, vis: &mut
}
}

pub fn noop_visit_anon_record<T: MutVisitor>(anon_record: &mut AnonRecord, vis: &mut T) {
let AnonRecord { span, id, fields, recovered: _recovered, kind: _kind } = anon_record;
vis.visit_span(span);
vis.visit_id(id);
fields.flat_map_in_place(|field| vis.flat_map_field_def(field));
}

pub fn noop_visit_trait_ref<T: MutVisitor>(TraitRef { path, ref_id }: &mut TraitRef, vis: &mut T) {
vis.visit_path(path);
vis.visit_id(ref_id);
Expand All @@ -999,7 +1007,12 @@ pub fn noop_flat_map_field_def<T: MutVisitor>(
visit_opt(ident, |ident| visitor.visit_ident(ident));
visitor.visit_vis(vis);
visitor.visit_id(id);
visitor.visit_ty(ty);
match ty {
FieldTy::Ty(ty) => {
visitor.visit_ty(ty);
}
FieldTy::AnonRecord(anon_record) => visitor.visit_anon_record(anon_record),
}
visit_attrs(attrs, visitor);
smallvec![fd]
}
Expand Down
12 changes: 8 additions & 4 deletions compiler/rustc_ast/src/visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,9 +438,6 @@ pub fn walk_ty<'a, V: Visitor<'a>>(visitor: &mut V, typ: &'a Ty) {
TyKind::Infer | TyKind::ImplicitSelf | TyKind::Err => {}
TyKind::MacCall(mac) => visitor.visit_mac_call(mac),
TyKind::Never | TyKind::CVarArgs => {}
TyKind::AnonStruct(ref fields, ..) | TyKind::AnonUnion(ref fields, ..) => {
walk_list!(visitor, visit_field_def, fields)
}
}
}

Expand Down Expand Up @@ -713,7 +710,14 @@ pub fn walk_field_def<'a, V: Visitor<'a>>(visitor: &mut V, field: &'a FieldDef)
if let Some(ident) = field.ident {
visitor.visit_ident(ident);
}
visitor.visit_ty(&field.ty);
match &field.ty {
FieldTy::Ty(ty) => {
visitor.visit_ty(ty);
}
FieldTy::AnonRecord(anon_record) => {
walk_list!(visitor, visit_field_def, &anon_record.fields);
}
}
walk_list!(visitor, visit_attribute, &field.attrs);
}

Expand Down
36 changes: 25 additions & 11 deletions compiler/rustc_ast_lowering/src/item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -709,17 +709,31 @@ impl<'hir> LoweringContext<'_, 'hir> {
}

fn lower_field_def(&mut self, (index, f): (usize, &FieldDef)) -> hir::FieldDef<'hir> {
let ty = if let TyKind::Path(qself, path) = &f.ty.kind {
let t = self.lower_path_ty(
&f.ty,
qself,
path,
ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
&ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy),
);
self.arena.alloc(t)
} else {
self.lower_ty(&f.ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy))
let ty = match &f.ty {
FieldTy::Ty(ty) if let TyKind::Path(qself, path) = &ty.kind => {
let t = self.lower_path_ty(
ty,
qself,
path,
ParamMode::ExplicitNamed, // no `'_` in declarations (Issue #61124)
&ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy),
);
self.arena.alloc(t)
}
FieldTy::Ty(ty) => {
self.lower_ty(ty, &ImplTraitContext::Disallowed(ImplTraitPosition::FieldTy))
}
FieldTy::AnonRecord(anon_record ) => {
let struct_or_union = anon_record.kind.name();
let hir_id = self.lower_node_id(anon_record.id);
let span = anon_record.span;
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
#[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)]
let kind = hir::TyKind::Err(self.tcx.sess.span_err(span, format!("anonymous {struct_or_union}s are unimplemented")));
let ty = hir::Ty { hir_id, kind, span };
self.arena.alloc(ty)
}
};
let hir_id = self.lower_node_id(f.id);
self.lower_attrs(hir_id, &f.attrs);
Expand Down
13 changes: 1 addition & 12 deletions compiler/rustc_ast_lowering/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@

#![feature(box_patterns)]
#![feature(let_chains)]
#![feature(if_let_guard)]
#![feature(never_type)]
#![recursion_limit = "256"]
#![deny(rustc::untranslatable_diagnostic)]
Expand Down Expand Up @@ -1303,18 +1304,6 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
TyKind::Err => {
hir::TyKind::Err(self.tcx.sess.delay_span_bug(t.span, "TyKind::Err lowered"))
}
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
#[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)]
TyKind::AnonStruct(ref _fields) => hir::TyKind::Err(
self.tcx.sess.span_err(t.span, "anonymous structs are unimplemented"),
),
// FIXME(unnamed_fields): IMPLEMENTATION IN PROGRESS
#[allow(rustc::untranslatable_diagnostic)]
#[allow(rustc::diagnostic_outside_of_impl)]
TyKind::AnonUnion(ref _fields) => hir::TyKind::Err(
self.tcx.sess.span_err(t.span, "anonymous unions are unimplemented"),
),
TyKind::Slice(ty) => hir::TyKind::Slice(self.lower_ty(ty, itctx)),
TyKind::Ptr(mt) => hir::TyKind::Ptr(self.lower_mt(mt, itctx)),
TyKind::Ref(region, mt) => {
Expand Down
Loading

0 comments on commit 1320961

Please sign in to comment.