Skip to content
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

rustdoc: Add unstable CLI option to show basic type layout information #83501

Merged
merged 15 commits into from
May 12, 2021
Merged
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
2 changes: 2 additions & 0 deletions src/bootstrap/doc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -549,6 +549,7 @@ impl Step for Rustc {
cargo.rustdocflag("--enable-index-page");
cargo.rustdocflag("-Zunstable-options");
cargo.rustdocflag("-Znormalize-docs");
cargo.rustdocflag("--show-type-layout");
compile::rustc_cargo(builder, &mut cargo, target);

// Only include compiler crates, no dependencies of those, such as `libc`.
Expand Down Expand Up @@ -648,6 +649,7 @@ impl Step for Rustdoc {

cargo.rustdocflag("--document-private-items");
cargo.rustdocflag("--enable-index-page");
cargo.rustdocflag("--show-type-layout");
cargo.rustdocflag("-Zunstable-options");
builder.run(&mut cargo.into());
}
Expand Down
4 changes: 4 additions & 0 deletions src/librustdoc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ crate struct RenderOptions {
crate document_hidden: bool,
/// If `true`, generate a JSON file in the crate folder instead of HTML redirection files.
crate generate_redirect_map: bool,
/// Show the memory layout of types in the docs.
crate show_type_layout: bool,
crate unstable_features: rustc_feature::UnstableFeatures,
crate emit: Vec<EmitType>,
}
Expand Down Expand Up @@ -636,6 +638,7 @@ impl Options {
let document_hidden = matches.opt_present("document-hidden-items");
let run_check = matches.opt_present("check");
let generate_redirect_map = matches.opt_present("generate-redirect-map");
let show_type_layout = matches.opt_present("show-type-layout");

let (lint_opts, describe_lints, lint_cap) = get_cmd_lint_options(matches, error_format);

Expand Down Expand Up @@ -695,6 +698,7 @@ impl Options {
document_private,
document_hidden,
generate_redirect_map,
show_type_layout,
unstable_features: rustc_feature::UnstableFeatures::from_environment(
crate_name.as_deref(),
),
Expand Down
4 changes: 4 additions & 0 deletions src/librustdoc/html/render/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ crate struct SharedContext<'tcx> {
crate include_sources: bool,
/// The local file sources we've emitted and their respective url-paths.
crate local_sources: FxHashMap<PathBuf, String>,
/// Show the memory layout of types in the docs.
pub(super) show_type_layout: bool,
/// Whether the collapsed pass ran
collapsed: bool,
/// The base-URL of the issue tracker for when an item has been tagged with
Expand Down Expand Up @@ -373,6 +375,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
generate_search_filter,
unstable_features,
generate_redirect_map,
show_type_layout,
..
} = options;

Expand Down Expand Up @@ -446,6 +449,7 @@ impl<'tcx> FormatRenderer<'tcx> for Context<'tcx> {
all: RefCell::new(AllTypes::new()),
errors: receiver,
redirections: if generate_redirect_map { Some(Default::default()) } else { None },
show_type_layout,
};

// Add the default themes to the `Vec` of stylepaths
Expand Down
78 changes: 74 additions & 4 deletions src/librustdoc/html/render/print_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use rustc_hir as hir;
use rustc_hir::def::CtorKind;
use rustc_hir::def_id::DefId;
use rustc_middle::middle::stability;
use rustc_middle::ty::layout::LayoutError;
use rustc_middle::ty::TyCtxt;
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
Expand Down Expand Up @@ -830,11 +831,12 @@ fn item_typedef(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::T

document(w, cx, it, None);

let def_id = it.def_id.expect_real();
// Render any items associated directly to this alias, as otherwise they
// won't be visible anywhere in the docs. It would be nice to also show
// associated items from the aliased type (see discussion in #32077), but
// we need #14072 to make sense of the generics.
render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
}

fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Union) {
Expand All @@ -846,6 +848,7 @@ fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Uni
});

document(w, cx, it, None);

let mut fields = s
.fields
.iter()
Expand Down Expand Up @@ -880,7 +883,9 @@ fn item_union(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Uni
document(w, cx, field, Some(it));
}
}
render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
let def_id = it.def_id.expect_real();
render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
document_type_layout(w, cx, def_id);
}

fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum) {
Expand Down Expand Up @@ -940,6 +945,7 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum
});

document(w, cx, it, None);

if !e.variants.is_empty() {
write!(
w,
Expand Down Expand Up @@ -1014,7 +1020,9 @@ fn item_enum(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, e: &clean::Enum
render_stability_since(w, variant, it, cx.tcx());
}
}
render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
let def_id = it.def_id.expect_real();
render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
document_type_layout(w, cx, def_id);
}

fn item_macro(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, t: &clean::Macro) {
Expand Down Expand Up @@ -1114,6 +1122,7 @@ fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St
});

document(w, cx, it, None);

let mut fields = s
.fields
.iter()
Expand Down Expand Up @@ -1152,7 +1161,9 @@ fn item_struct(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::St
}
}
}
render_assoc_items(w, cx, it, it.def_id.expect_real(), AssocItemRender::All)
let def_id = it.def_id.expect_real();
render_assoc_items(w, cx, it, def_id, AssocItemRender::All);
document_type_layout(w, cx, def_id);
}

fn item_static(w: &mut Buffer, cx: &Context<'_>, it: &clean::Item, s: &clean::Static) {
Expand Down Expand Up @@ -1522,3 +1533,62 @@ fn document_non_exhaustive(w: &mut Buffer, item: &clean::Item) {
w.write_str("</div></details>");
}
}

fn document_type_layout(w: &mut Buffer, cx: &Context<'_>, ty_def_id: DefId) {
if !cx.shared.show_type_layout {
return;
}

writeln!(w, "<h2 class=\"small-section-header\">Layout</h2>");
writeln!(w, "<div class=\"docblock\">");

let tcx = cx.tcx();
let param_env = tcx.param_env(ty_def_id);
let ty = tcx.type_of(ty_def_id);
match tcx.layout_of(param_env.and(ty)) {
Ok(ty_layout) => {
writeln!(
w,
"<div class=\"warning\"><p><strong>Note:</strong> Most layout information is \
completely unstable and may be different between compiler versions and platforms. \
The only exception is types with certain <code>repr(...)</code> attributes. \
Please see the Rust Reference’s \
<a href=\"https://doc.rust-lang.org/reference/type-layout.html\">“Type Layout”</a> \
chapter for details on type layout guarantees.</p></div>"
);
if ty_layout.layout.abi.is_unsized() {
writeln!(w, "<p><strong>Size:</strong> (unsized)</p>");
} else {
let bytes = ty_layout.layout.size.bytes();
writeln!(
w,
"<p><strong>Size:</strong> {size} byte{pl}</p>",
size = bytes,
pl = if bytes == 1 { "" } else { "s" },
);
}
}
// 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>`.
Err(LayoutError::Unknown(_)) => {
writeln!(
w,
"<p><strong>Note:</strong> Unable to compute type layout, \
possibly due to this type having generic parameters. \
Layout can only be computed for concrete, fully-instantiated types.</p>"
);
}
// This kind of error probably can't happen with valid code, but we don't
// want to panic and prevent the docs from building, so we just let the
// user know that we couldn't compute the layout.
Err(LayoutError::SizeOverflow(_)) => {
writeln!(
w,
"<p><strong>Note:</strong> Encountered an error during type layout; \
camelid marked this conversation as resolved.
Show resolved Hide resolved
the type was too big.</p>"
);
}
}

writeln!(w, "</div>");
}
3 changes: 3 additions & 0 deletions src/librustdoc/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,9 @@ fn opts() -> Vec<RustcOptGroup> {
)
}),
unstable("no-run", |o| o.optflag("", "no-run", "Compile doctests without running them")),
unstable("show-type-layout", |o| {
o.optflag("", "show-type-layout", "Include the memory layout of types in the docs")
}),
camelid marked this conversation as resolved.
Show resolved Hide resolved
]
}

Expand Down
4 changes: 4 additions & 0 deletions src/test/rustdoc/type-layout-flag-required.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// Tests that `--show-type-layout` is required in order to show layout info.

// @!has type_layout_flag_required/struct.Foo.html 'Size: '
pub struct Foo(usize);
54 changes: 54 additions & 0 deletions src/test/rustdoc/type-layout.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// compile-flags: --show-type-layout -Z unstable-options

// @has type_layout/struct.Foo.html 'Size: '
// @has - ' bytes'
pub struct Foo {
pub a: usize,
b: Vec<String>,
}

// @has type_layout/enum.Bar.html 'Size: '
// @has - ' bytes'
pub enum Bar<'a> {
A(String),
camelid marked this conversation as resolved.
Show resolved Hide resolved
B(&'a str, (std::collections::HashMap<String, usize>, Foo)),
}

// @has type_layout/union.Baz.html 'Size: '
// @has - ' bytes'
pub union Baz {
a: &'static str,
b: usize,
c: &'static [u8],
}

// @has type_layout/struct.X.html 'Size: '
// @has - ' bytes'
pub struct X(usize);

// @has type_layout/struct.Y.html 'Size: '
camelid marked this conversation as resolved.
Show resolved Hide resolved
// @has - '1 byte'
// @!has - ' bytes'
pub struct Y(u8);

// @has type_layout/struct.Z.html 'Size: '
// @has - '0 bytes'
pub struct Z;

// We can't compute layout for generic types.
// @has type_layout/struct.Generic.html 'Unable to compute type layout, possibly due to this type having generic parameters'
// @!has - 'Size: '
pub struct Generic<T>(T);

// We *can*, however, compute layout for types that are only generic over lifetimes,
// because lifetimes are a type-system construct.
// @has type_layout/struct.GenericLifetimes.html 'Size: '
// @has - ' bytes'
pub struct GenericLifetimes<'a>(&'a str);

// @has type_layout/struct.Unsized.html 'Size: '
// @has - '(unsized)'
camelid marked this conversation as resolved.
Show resolved Hide resolved
pub struct Unsized([u8]);

// @!has type_layout/trait.MyTrait.html 'Size: '
pub trait MyTrait {}
camelid marked this conversation as resolved.
Show resolved Hide resolved