Skip to content

Commit 64fa12a

Browse files
committed
rustdoc: hide repr(transparent) if it isn't part of the public ABI
1 parent cbcf9a5 commit 64fa12a

File tree

10 files changed

+152
-42
lines changed

10 files changed

+152
-42
lines changed

src/doc/rustdoc/src/advanced-features.md

+20
Original file line numberDiff line numberDiff line change
@@ -110,3 +110,23 @@ https://doc.rust-lang.org/stable/std/?search=%s&go_to_first=true
110110

111111
This URL adds the `go_to_first=true` query parameter which can be appended to any `rustdoc` search URL
112112
to automatically go to the first result.
113+
114+
## `#[repr(transparent)]`: Documenting the transparent representation
115+
116+
You can read more about `#[repr(transparent)]` itself in the [Rust Reference][repr-trans-ref] and
117+
in the [Rustonomicon][repr-trans-nomicon].
118+
119+
Since this representation is only considered part of the public ABI if the single field with non-trivial
120+
size or alignment is public and if the documentation does not state otherwise, Rustdoc helpfully displays
121+
the attribute if and only if the non-1-ZST field is public or at least one field is public in case all
122+
fields are 1-ZST fields. The term *1-ZST* refers to types that are one-aligned and zero-sized.
123+
124+
It would seem that one can manually hide the attribute with `#[cfg_attr(not(doc), repr(transparent))]`
125+
if one wishes to declare the representation as private even if the non-1-ZST field is public.
126+
However, due to [current limitations][cross-crate-cfg-doc], this method is not always guaranteed to work.
127+
Therefore, if you would like to do so, you should always write it down in prose independently of whether
128+
you use `cfg_attr` or not.
129+
130+
[repr-trans-ref]: https://doc.rust-lang.org/reference/type-layout.html#the-transparent-representation
131+
[repr-trans-nomicon]: https://doc.rust-lang.org/nomicon/other-reprs.html#reprtransparent
132+
[cross-crate-cfg-doc]: https://github.com/rust-lang/rust/issues/114952

src/librustdoc/clean/types.rs

+36-15
Original file line numberDiff line numberDiff line change
@@ -709,12 +709,16 @@ impl Item {
709709
Some(tcx.visibility(def_id))
710710
}
711711

712-
pub(crate) fn attributes(&self, tcx: TyCtxt<'_>, keep_as_is: bool) -> Vec<String> {
712+
pub(crate) fn attributes(
713+
&self,
714+
tcx: TyCtxt<'_>,
715+
cache: &Cache,
716+
keep_as_is: bool,
717+
) -> Vec<String> {
713718
const ALLOWED_ATTRIBUTES: &[Symbol] =
714-
&[sym::export_name, sym::link_section, sym::no_mangle, sym::repr, sym::non_exhaustive];
719+
&[sym::export_name, sym::link_section, sym::no_mangle, sym::non_exhaustive];
715720

716721
use rustc_abi::IntegerType;
717-
use rustc_middle::ty::ReprFlags;
718722

719723
let mut attrs: Vec<String> = self
720724
.attrs
@@ -735,20 +739,38 @@ impl Item {
735739
}
736740
})
737741
.collect();
738-
if let Some(def_id) = self.def_id() &&
739-
!def_id.is_local() &&
740-
// This check is needed because `adt_def` will panic if not a compatible type otherwise...
741-
matches!(self.type_(), ItemType::Struct | ItemType::Enum | ItemType::Union)
742+
if !keep_as_is
743+
&& let Some(def_id) = self.def_id()
744+
&& let ItemType::Struct | ItemType::Enum | ItemType::Union = self.type_()
742745
{
743-
let repr = tcx.adt_def(def_id).repr();
746+
let adt = tcx.adt_def(def_id);
747+
let repr = adt.repr();
744748
let mut out = Vec::new();
745-
if repr.flags.contains(ReprFlags::IS_C) {
749+
if repr.c() {
746750
out.push("C");
747751
}
748-
if repr.flags.contains(ReprFlags::IS_TRANSPARENT) {
749-
out.push("transparent");
752+
if repr.transparent() {
753+
// Render `repr(transparent)` iff the non-1-ZST field is public or at least one
754+
// field is public in case all fields are 1-ZST fields.
755+
let render_transparent = cache.document_private
756+
|| adt
757+
.all_fields()
758+
.find(|field| {
759+
let ty =
760+
field.ty(tcx, ty::GenericArgs::identity_for_item(tcx, field.did));
761+
tcx.layout_of(tcx.param_env(field.did).and(ty))
762+
.is_ok_and(|layout| !layout.is_1zst())
763+
})
764+
.map_or_else(
765+
|| adt.all_fields().any(|field| field.vis.is_public()),
766+
|field| field.vis.is_public(),
767+
);
768+
769+
if render_transparent {
770+
out.push("transparent");
771+
}
750772
}
751-
if repr.flags.contains(ReprFlags::IS_SIMD) {
773+
if repr.simd() {
752774
out.push("simd");
753775
}
754776
let pack_s;
@@ -773,10 +795,9 @@ impl Item {
773795
};
774796
out.push(&int_s);
775797
}
776-
if out.is_empty() {
777-
return Vec::new();
798+
if !out.is_empty() {
799+
attrs.push(format!("#[repr({})]", out.join(", ")));
778800
}
779-
attrs.push(format!("#[repr({})]", out.join(", ")));
780801
}
781802
attrs
782803
}

src/librustdoc/html/render/mod.rs

+8-8
Original file line numberDiff line numberDiff line change
@@ -856,10 +856,10 @@ fn assoc_method(
856856
let (indent, indent_str, end_newline) = if parent == ItemType::Trait {
857857
header_len += 4;
858858
let indent_str = " ";
859-
write!(w, "{}", render_attributes_in_pre(meth, indent_str, tcx));
859+
write!(w, "{}", render_attributes_in_pre(meth, indent_str, cx));
860860
(4, indent_str, Ending::NoNewline)
861861
} else {
862-
render_attributes_in_code(w, meth, tcx);
862+
render_attributes_in_code(w, meth, cx);
863863
(0, "", Ending::Newline)
864864
};
865865
w.reserve(header_len + "<a href=\"\" class=\"fn\">{".len() + "</a>".len());
@@ -1035,13 +1035,13 @@ fn render_assoc_item(
10351035

10361036
// When an attribute is rendered inside a `<pre>` tag, it is formatted using
10371037
// a whitespace prefix and newline.
1038-
fn render_attributes_in_pre<'a, 'b: 'a>(
1038+
fn render_attributes_in_pre<'a, 'tcx: 'a>(
10391039
it: &'a clean::Item,
10401040
prefix: &'a str,
1041-
tcx: TyCtxt<'b>,
1042-
) -> impl fmt::Display + Captures<'a> + Captures<'b> {
1041+
cx: &'a Context<'tcx>,
1042+
) -> impl fmt::Display + Captures<'a> + Captures<'tcx> {
10431043
crate::html::format::display_fn(move |f| {
1044-
for a in it.attributes(tcx, false) {
1044+
for a in it.attributes(cx.tcx(), cx.cache(), false) {
10451045
writeln!(f, "{prefix}{a}")?;
10461046
}
10471047
Ok(())
@@ -1050,8 +1050,8 @@ fn render_attributes_in_pre<'a, 'b: 'a>(
10501050

10511051
// When an attribute is rendered inside a <code> tag, it is formatted using
10521052
// a div to produce a newline after it.
1053-
fn render_attributes_in_code(w: &mut impl fmt::Write, it: &clean::Item, tcx: TyCtxt<'_>) {
1054-
for attr in it.attributes(tcx, false) {
1053+
fn render_attributes_in_code(w: &mut impl fmt::Write, it: &clean::Item, cx: &Context<'_>) {
1054+
for attr in it.attributes(cx.tcx(), cx.cache(), false) {
10551055
write!(w, "<div class=\"code-attribute\">{attr}</div>").unwrap();
10561056
}
10571057
}

src/librustdoc/html/render/print_item.rs

+11-12
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,7 @@ macro_rules! item_template_methods {
117117
fn render_attributes_in_pre<'b>(&'b self) -> impl fmt::Display + Captures<'a> + 'b + Captures<'cx> {
118118
display_fn(move |f| {
119119
let (item, cx) = self.item_and_mut_cx();
120-
let tcx = cx.tcx();
121-
let v = render_attributes_in_pre(item, "", tcx);
120+
let v = render_attributes_in_pre(item, "", &cx);
122121
write!(f, "{v}")
123122
})
124123
}
@@ -656,7 +655,7 @@ fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &cle
656655
w,
657656
"{attrs}{vis}{constness}{asyncness}{unsafety}{abi}fn \
658657
{name}{generics}{decl}{notable_traits}{where_clause}",
659-
attrs = render_attributes_in_pre(it, "", tcx),
658+
attrs = render_attributes_in_pre(it, "", cx),
660659
vis = visibility,
661660
constness = constness,
662661
asyncness = asyncness,
@@ -691,7 +690,7 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
691690
write!(
692691
w,
693692
"{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}",
694-
attrs = render_attributes_in_pre(it, "", tcx),
693+
attrs = render_attributes_in_pre(it, "", cx),
695694
vis = visibility_print_with_space(it.visibility(tcx), it.item_id, cx),
696695
unsafety = t.unsafety(tcx).print_with_space(),
697696
is_auto = if t.is_auto(tcx) { "auto " } else { "" },
@@ -1170,7 +1169,7 @@ fn item_trait_alias(
11701169
write!(
11711170
w,
11721171
"{attrs}trait {name}{generics}{where_b} = {bounds};",
1173-
attrs = render_attributes_in_pre(it, "", cx.tcx()),
1172+
attrs = render_attributes_in_pre(it, "", cx),
11741173
name = it.name.unwrap(),
11751174
generics = t.generics.print(cx),
11761175
where_b = print_where_clause(&t.generics, cx, 0, Ending::Newline),
@@ -1198,7 +1197,7 @@ fn item_opaque_ty(
11981197
write!(
11991198
w,
12001199
"{attrs}type {name}{generics}{where_clause} = impl {bounds};",
1201-
attrs = render_attributes_in_pre(it, "", cx.tcx()),
1200+
attrs = render_attributes_in_pre(it, "", cx),
12021201
name = it.name.unwrap(),
12031202
generics = t.generics.print(cx),
12041203
where_clause = print_where_clause(&t.generics, cx, 0, Ending::Newline),
@@ -1223,7 +1222,7 @@ fn item_type_alias(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &c
12231222
write!(
12241223
w,
12251224
"{attrs}{vis}type {name}{generics}{where_clause} = {type_};",
1226-
attrs = render_attributes_in_pre(it, "", cx.tcx()),
1225+
attrs = render_attributes_in_pre(it, "", cx),
12271226
vis = visibility_print_with_space(it.visibility(cx.tcx()), it.item_id, cx),
12281227
name = it.name.unwrap(),
12291228
generics = t.generics.print(cx),
@@ -1408,7 +1407,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
14081407
let tcx = cx.tcx();
14091408
let count_variants = e.variants().count();
14101409
wrap_item(w, |w| {
1411-
render_attributes_in_code(w, it, tcx);
1410+
render_attributes_in_code(w, it, cx);
14121411
write!(
14131412
w,
14141413
"{}enum {}{}",
@@ -1644,7 +1643,7 @@ fn item_primitive(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Ite
16441643
fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
16451644
wrap_item(w, |w| {
16461645
let tcx = cx.tcx();
1647-
render_attributes_in_code(w, it, tcx);
1646+
render_attributes_in_code(w, it, cx);
16481647

16491648
write!(
16501649
w,
@@ -1693,7 +1692,7 @@ fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &cle
16931692

16941693
fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
16951694
wrap_item(w, |w| {
1696-
render_attributes_in_code(w, it, cx.tcx());
1695+
render_attributes_in_code(w, it, cx);
16971696
render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
16981697
});
16991698

@@ -1753,7 +1752,7 @@ fn item_fields(
17531752

17541753
fn item_static(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
17551754
wrap_item(w, |buffer| {
1756-
render_attributes_in_code(buffer, it, cx.tcx());
1755+
render_attributes_in_code(buffer, it, cx);
17571756
write!(
17581757
buffer,
17591758
"{vis}static {mutability}{name}: {typ}",
@@ -1771,7 +1770,7 @@ fn item_static(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item,
17711770
fn item_foreign_type(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item) {
17721771
wrap_item(w, |buffer| {
17731772
buffer.write_str("extern {\n").unwrap();
1774-
render_attributes_in_code(buffer, it, cx.tcx());
1773+
render_attributes_in_code(buffer, it, cx);
17751774
write!(
17761775
buffer,
17771776
" {}type {};\n}}",

src/librustdoc/json/conversions.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ use rustdoc_json_types::*;
1818

1919
use crate::clean::{self, ItemId};
2020
use crate::formats::item_type::ItemType;
21+
use crate::formats::FormatRenderer;
2122
use crate::json::JsonRenderer;
2223
use crate::passes::collect_intra_doc_links::UrlFragment;
2324

@@ -41,7 +42,7 @@ impl JsonRenderer<'_> {
4142
})
4243
.collect();
4344
let docs = item.opt_doc_value();
44-
let attrs = item.attributes(self.tcx, true);
45+
let attrs = item.attributes(self.tcx, self.cache(), true);
4546
let span = item.span(self.tcx);
4647
let visibility = item.visibility(self.tcx);
4748
let clean::Item { name, item_id, .. } = item;
+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
// aux-crate:attributes=attributes.rs
2+
// edition:2021
3+
#![crate_name = "user"]
4+
5+
// @has 'user/struct.NonExhaustive.html'
6+
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[non_exhaustive]'
7+
pub use attributes::NonExhaustive;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
#[non_exhaustive]
2+
pub struct NonExhaustive;

tests/rustdoc/inline_cross/auxiliary/repr.rs

+21-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ pub struct ReprSimd {
1010
}
1111
#[repr(transparent)]
1212
pub struct ReprTransparent {
13-
field: u8,
13+
pub field: u8,
1414
}
1515
#[repr(isize)]
1616
pub enum ReprIsize {
@@ -20,3 +20,23 @@ pub enum ReprIsize {
2020
pub enum ReprU8 {
2121
Bla,
2222
}
23+
24+
#[repr(transparent)] // private
25+
pub struct ReprTransparentPrivField {
26+
field: u32, // non-1-ZST field
27+
}
28+
29+
#[repr(transparent)] // public
30+
pub struct ReprTransparentPriv1ZstFields {
31+
marker0: Marker,
32+
pub main: u64, // non-1-ZST field
33+
marker1: Marker,
34+
}
35+
36+
#[repr(transparent)] // private
37+
pub struct ReprTransparentPrivFieldPub1ZstFields {
38+
main: [u16; 0], // non-1-ZST field
39+
pub marker: Marker,
40+
}
41+
42+
pub struct Marker; // 1-ZST

tests/rustdoc/inline_cross/repr.rs

+16-5
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,32 @@ extern crate repr;
99

1010
// @has 'foo/struct.ReprC.html'
1111
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(C, align(8))]'
12-
#[doc(inline)]
1312
pub use repr::ReprC;
1413
// @has 'foo/struct.ReprSimd.html'
1514
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(simd, packed(2))]'
16-
#[doc(inline)]
1715
pub use repr::ReprSimd;
1816
// @has 'foo/struct.ReprTransparent.html'
1917
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
20-
#[doc(inline)]
2118
pub use repr::ReprTransparent;
2219
// @has 'foo/enum.ReprIsize.html'
2320
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(isize)]'
24-
#[doc(inline)]
2521
pub use repr::ReprIsize;
2622
// @has 'foo/enum.ReprU8.html'
2723
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(u8)]'
28-
#[doc(inline)]
2924
pub use repr::ReprU8;
25+
26+
// Regression test for <https://github.com/rust-lang/rust/issues/90435>.
27+
// Check that we show `#[repr(transparent)]` iff the non-1-ZST field is public or at least one
28+
// field is public in case all fields are 1-ZST fields.
29+
30+
// @has 'foo/struct.ReprTransparentPrivField.html'
31+
// @!has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
32+
pub use repr::ReprTransparentPrivField;
33+
34+
// @has 'foo/struct.ReprTransparentPriv1ZstFields.html'
35+
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
36+
pub use repr::ReprTransparentPriv1ZstFields;
37+
38+
// @has 'foo/struct.ReprTransparentPrivFieldPub1ZstFields.html'
39+
// @!has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
40+
pub use repr::ReprTransparentPrivFieldPub1ZstFields;

tests/rustdoc/repr.rs

+29
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Regression test for <https://github.com/rust-lang/rust/issues/90435>.
2+
// Check that we show `#[repr(transparent)]` iff the non-1-ZST field is public or at least one
3+
// field is public in case all fields are 1-ZST fields.
4+
5+
// @has 'repr/struct.ReprTransparentPrivField.html'
6+
// @!has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
7+
#[repr(transparent)] // private
8+
pub struct ReprTransparentPrivField {
9+
field: u32, // non-1-ZST field
10+
}
11+
12+
// @has 'repr/struct.ReprTransparentPriv1ZstFields.html'
13+
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
14+
#[repr(transparent)] // public
15+
pub struct ReprTransparentPriv1ZstFields {
16+
marker0: Marker,
17+
pub main: u64, // non-1-ZST field
18+
marker1: Marker,
19+
}
20+
21+
// @has 'repr/struct.ReprTransparentPub1ZstField.html'
22+
// @has - '//*[@class="rust item-decl"]//*[@class="code-attribute"]' '#[repr(transparent)]'
23+
#[repr(transparent)] // public
24+
pub struct ReprTransparentPub1ZstField {
25+
marker0: Marker,
26+
pub marker1: Marker,
27+
}
28+
29+
struct Marker; // 1-ZST

0 commit comments

Comments
 (0)