Skip to content

Commit

Permalink
Report Layout of enum variants
Browse files Browse the repository at this point in the history
Followup of rust-lang#83501, Fixes rust-lang#86253.
  • Loading branch information
fee1-dead committed Aug 31, 2021
1 parent ac50a53 commit aff4cd5
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
36 changes: 35 additions & 1 deletion src/librustdoc/html/render/print_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ use rustc_data_structures::fx::FxHashMap;
use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_middle::bug;
use rustc_middle::middle::stability;
use rustc_middle::ty::layout::LayoutError;
use rustc_middle::ty::TyCtxt;
use rustc_middle::ty::{Adt, TyCtxt};
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
use rustc_target::abi::Variants;

use super::{
collect_paths_for_type, document, ensure_trailing_slash, item_ty_to_strs, notable_traits_decl,
Expand Down Expand Up @@ -1636,6 +1638,38 @@ fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
pl = if bytes == 1 { "" } else { "s" },
);
}
if let Variants::Multiple { variants, .. } = &ty_layout.layout.variants {
if !variants.is_empty() {
w.write_str(
"<p>\
<strong>Size for each variant:</strong>\
<ul>",
);

let adt = if let Adt(adt, _) = ty_layout.ty.kind() {
adt
} else {
bug!("not an adt")
};

for (index, layout) in variants.iter_enumerated() {
let ident = adt.variants[index].ident;
if layout.abi.is_unsized() {
writeln!(w, "<li><code>{name}</code> (unsized)</li>", name = ident);
} else {
let bytes = layout.size.bytes();
writeln!(
w,
"<li><code>{name}</code>: {size} byte{pl}</li>",
name = ident,
size = bytes,
pl = if bytes == 1 { "" } else { "s" },
);
}
}
w.write_str("</ul></p>");
}
}
}
// This kind of layout error can occur with valid code, e.g. if you try to
// get the layout of a generic type such as `Vec<T>`.
Expand Down
6 changes: 6 additions & 0 deletions src/test/rustdoc/type-layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,9 @@ pub struct Unsized([u8]);

// @!has type_layout/trait.MyTrait.html 'Size: '
pub trait MyTrait {}

// @has type_layout/enum.Variants.html '1 byte'
pub enum Variants {
A,
B(u8),
}

0 comments on commit aff4cd5

Please sign in to comment.