Skip to content

Make single-variant "c-like" enums have no size. #20122

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 11 additions & 10 deletions src/librustc_trans/trans/adt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,17 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
dtor);
}

if cases.len() == 1 && cases[0].discr == 0 {
// Equivalent to a struct/tuple/newtype.
// (Typechecking will reject discriminant-sizing attrs.)
assert_eq!(hint, attr::ReprAny);
let mut ftys = cases[0].tys.clone();
if dtor { ftys.push(ty::mk_bool()); }
return Univariant(mk_struct(cx, ftys.as_slice(), false, t),
dtor);
}


if !dtor && cases.iter().all(|c| c.tys.len() == 0) {
// All bodies empty -> intlike
let discrs: Vec<u64> = cases.iter().map(|c| c.discr).collect();
Expand All @@ -212,16 +223,6 @@ fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
def_id)).as_slice());
}

if cases.len() == 1 {
// Equivalent to a struct/tuple/newtype.
// (Typechecking will reject discriminant-sizing attrs.)
assert_eq!(hint, attr::ReprAny);
let mut ftys = cases[0].tys.clone();
if dtor { ftys.push(ty::mk_bool()); }
return Univariant(mk_struct(cx, ftys.as_slice(), false, t),
dtor);
}

if !dtor && cases.len() == 2 && hint == attr::ReprAny {
// Nullable pointer optimization
let mut discr = 0;
Expand Down
12 changes: 12 additions & 0 deletions src/test/run-pass/type-sizes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ struct w {a: int, b: ()}
struct x {a: int, b: (), c: ()}
struct y {x: int}

enum c1 {
c1
}

enum c2 {
c2 = 1
}

pub fn main() {
assert_eq!(size_of::<u8>(), 1 as uint);
assert_eq!(size_of::<u32>(), 4 as uint);
Expand All @@ -34,4 +42,8 @@ pub fn main() {
assert_eq!(size_of::<w>(), size_of::<int>());
assert_eq!(size_of::<x>(), size_of::<int>());
assert_eq!(size_of::<int>(), size_of::<y>());

// Make sure enum sizes are correct
assert_eq!(size_of::<c1>(), 0 as uint);
assert_eq!(size_of::<c2>(), 1 as uint);
}