Skip to content

Commit a7c9170

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

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
@@ -706,12 +706,16 @@ impl Item {
706706
Some(tcx.visibility(def_id))
707707
}
708708

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

713718
use rustc_abi::IntegerType;
714-
use rustc_middle::ty::ReprFlags;
715719

716720
let mut attrs: Vec<String> = self
717721
.attrs
@@ -732,20 +736,38 @@ impl Item {
732736
}
733737
})
734738
.collect();
735-
if let Some(def_id) = self.def_id() &&
736-
!def_id.is_local() &&
737-
// This check is needed because `adt_def` will panic if not a compatible type otherwise...
738-
matches!(self.type_(), ItemType::Struct | ItemType::Enum | ItemType::Union)
739+
if !keep_as_is
740+
&& let Some(def_id) = self.def_id()
741+
&& let ItemType::Struct | ItemType::Enum | ItemType::Union = self.type_()
739742
{
740-
let repr = tcx.adt_def(def_id).repr();
743+
let adt = tcx.adt_def(def_id);
744+
let repr = adt.repr();
741745
let mut out = Vec::new();
742-
if repr.flags.contains(ReprFlags::IS_C) {
746+
if repr.c() {
743747
out.push("C");
744748
}
745-
if repr.flags.contains(ReprFlags::IS_TRANSPARENT) {
746-
out.push("transparent");
749+
if repr.transparent() {
750+
// Render `repr(transparent)` iff the non-1-ZST field is public or at least one
751+
// field is public in case all fields are 1-ZST fields.
752+
let render_transparent = cache.document_private
753+
|| adt
754+
.all_fields()
755+
.find(|field| {
756+
let ty =
757+
field.ty(tcx, ty::GenericArgs::identity_for_item(tcx, field.did));
758+
tcx.layout_of(tcx.param_env(field.did).and(ty))
759+
.is_ok_and(|layout| !layout.is_1zst())
760+
})
761+
.map_or_else(
762+
|| adt.all_fields().any(|field| field.vis.is_public()),
763+
|field| field.vis.is_public(),
764+
);
765+
766+
if render_transparent {
767+
out.push("transparent");
768+
}
747769
}
748-
if repr.flags.contains(ReprFlags::IS_SIMD) {
770+
if repr.simd() {
749771
out.push("simd");
750772
}
751773
let pack_s;
@@ -770,10 +792,9 @@ impl Item {
770792
};
771793
out.push(&int_s);
772794
}
773-
if out.is_empty() {
774-
return Vec::new();
795+
if !out.is_empty() {
796+
attrs.push(format!("#[repr({})]", out.join(", ")));
775797
}
776-
attrs.push(format!("#[repr({})]", out.join(", ")));
777798
}
778799
attrs
779800
}

src/librustdoc/html/render/mod.rs

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

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

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

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),
@@ -1333,7 +1332,7 @@ fn item_enum(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, e: &clean::
13331332
let tcx = cx.tcx();
13341333
let count_variants = e.variants().count();
13351334
wrap_item(w, |mut w| {
1336-
render_attributes_in_code(w, it, tcx);
1335+
render_attributes_in_code(w, it, cx);
13371336
write!(
13381337
w,
13391338
"{}enum {}{}",
@@ -1538,7 +1537,7 @@ fn item_primitive(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Ite
15381537
fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &clean::Constant) {
15391538
wrap_item(w, |w| {
15401539
let tcx = cx.tcx();
1541-
render_attributes_in_code(w, it, tcx);
1540+
render_attributes_in_code(w, it, cx);
15421541

15431542
write!(
15441543
w,
@@ -1587,7 +1586,7 @@ fn item_constant(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, c: &cle
15871586

15881587
fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Struct) {
15891588
wrap_item(w, |w| {
1590-
render_attributes_in_code(w, it, cx.tcx());
1589+
render_attributes_in_code(w, it, cx);
15911590
render_struct(w, it, Some(&s.generics), s.ctor_kind, &s.fields, "", true, cx);
15921591
});
15931592

@@ -1637,7 +1636,7 @@ fn item_struct(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, s: &clean
16371636

16381637
fn item_static(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item, s: &clean::Static) {
16391638
wrap_item(w, |buffer| {
1640-
render_attributes_in_code(buffer, it, cx.tcx());
1639+
render_attributes_in_code(buffer, it, cx);
16411640
write!(
16421641
buffer,
16431642
"{vis}static {mutability}{name}: {typ}",
@@ -1655,7 +1654,7 @@ fn item_static(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item,
16551654
fn item_foreign_type(w: &mut impl fmt::Write, cx: &mut Context<'_>, it: &clean::Item) {
16561655
wrap_item(w, |buffer| {
16571656
buffer.write_str("extern {\n").unwrap();
1658-
render_attributes_in_code(buffer, it, cx.tcx());
1657+
render_attributes_in_code(buffer, it, cx);
16591658
write!(
16601659
buffer,
16611660
" {}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
use crate::clean::utils::print_const_expr;
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)