Skip to content

Commit 781f995

Browse files
authored
Rollup merge of rust-lang#145216 - eval-exec:fix-145125-enum-rustdoc, r=fmease
rustdoc: correct negative-to-implicit discriminant display This PR want to fix rust-lang#145125 In: https://github.com/rust-lang/rust/blob/7f7b8ef27d86c865a7ab20c7c42f50811c6a914d/compiler/rustc_middle/src/ty/util.rs#L33-L38 the `Discr`'s `val` field is `u128`, so we can't use `discr.val as i128` to represent `Discr`'s signed value. We should use `Discr`'s `Display` trait to display signed value. https://github.com/rust-lang/rust/blob/7f7b8ef27d86c865a7ab20c7c42f50811c6a914d/compiler/rustc_middle/src/ty/util.rs#L60-L73
2 parents bc71652 + 20a134f commit 781f995

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

src/librustdoc/html/render/print_item.rs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1656,11 +1656,9 @@ fn display_c_like_variant(
16561656
} else if should_show_enum_discriminant {
16571657
let adt_def = cx.tcx().adt_def(enum_def_id);
16581658
let discr = adt_def.discriminant_for_variant(cx.tcx(), index);
1659-
if discr.ty.is_signed() {
1660-
write!(w, "{} = {}", name.as_str(), discr.val as i128)?;
1661-
} else {
1662-
write!(w, "{} = {}", name.as_str(), discr.val)?;
1663-
}
1659+
// Use `discr`'s `Display` impl to render the value with the correct
1660+
// signedness, including proper sign-extension for signed types.
1661+
write!(w, "{} = {}", name.as_str(), discr)?;
16641662
} else {
16651663
write!(w, "{name}")?;
16661664
}

tests/rustdoc/enum/enum-variant-value.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,3 +189,25 @@ pub use bar::P;
189189
//@ has - '//*[@id="variant.A"]/h3' 'A(u32)'
190190
//@ matches - '//*[@id="variant.B"]/h3' '^B$'
191191
pub use bar::Q;
192+
193+
// Ensure signed implicit discriminants are rendered correctly after a negative explicit value.
194+
//@ has 'foo/enum.R.html'
195+
//@ has - '//*[@class="rust item-decl"]/code' 'A = -2,'
196+
//@ has - '//*[@class="rust item-decl"]/code' 'B = -1,'
197+
//@ matches - '//*[@id="variant.A"]/h3' '^A = -2$'
198+
//@ matches - '//*[@id="variant.B"]/h3' '^B = -1$'
199+
pub enum R {
200+
A = -2,
201+
B,
202+
}
203+
204+
// Also check that incrementing -1 yields 0 for the next implicit variant.
205+
//@ has 'foo/enum.S.html'
206+
//@ has - '//*[@class="rust item-decl"]/code' 'A = -1,'
207+
//@ has - '//*[@class="rust item-decl"]/code' 'B = 0,'
208+
//@ matches - '//*[@id="variant.A"]/h3' '^A = -1$'
209+
//@ matches - '//*[@id="variant.B"]/h3' '^B = 0$'
210+
pub enum S {
211+
A = -1,
212+
B,
213+
}

0 commit comments

Comments
 (0)