Skip to content

[rustdoc] Unify type aliases rendering with other ADT #140863

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

Merged
merged 8 commits into from
May 26, 2025
Merged
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
168 changes: 100 additions & 68 deletions src/librustdoc/clean/types.rs
Original file line number Diff line number Diff line change
@@ -610,6 +610,9 @@ impl Item {
UnionItem(ref union_) => Some(union_.has_stripped_entries()),
EnumItem(ref enum_) => Some(enum_.has_stripped_entries()),
VariantItem(ref v) => v.has_stripped_entries(),
TypeAliasItem(ref type_alias) => {
type_alias.inner_type.as_ref().and_then(|t| t.has_stripped_entries())
}
_ => None,
}
}
@@ -761,14 +764,11 @@ impl Item {
Some(tcx.visibility(def_id))
}

pub(crate) fn attributes(&self, tcx: TyCtxt<'_>, cache: &Cache, is_json: bool) -> Vec<String> {
pub(crate) fn attributes_without_repr(&self, tcx: TyCtxt<'_>, is_json: bool) -> Vec<String> {
const ALLOWED_ATTRIBUTES: &[Symbol] =
&[sym::export_name, sym::link_section, sym::no_mangle, sym::non_exhaustive];

use rustc_abi::IntegerType;

let mut attrs: Vec<String> = self
.attrs
self.attrs
.other_attrs
.iter()
.filter_map(|attr| {
@@ -796,74 +796,28 @@ impl Item {
None
}
})
.collect();
.collect()
}

// Add #[repr(...)]
if let Some(def_id) = self.def_id()
&& let ItemType::Struct | ItemType::Enum | ItemType::Union = self.type_()
{
let adt = tcx.adt_def(def_id);
let repr = adt.repr();
let mut out = Vec::new();
if repr.c() {
out.push("C");
}
if repr.transparent() {
// Render `repr(transparent)` iff the non-1-ZST field is public or at least one
// field is public in case all fields are 1-ZST fields.
let render_transparent = is_json
|| cache.document_private
|| adt
.all_fields()
.find(|field| {
let ty =
field.ty(tcx, ty::GenericArgs::identity_for_item(tcx, field.did));
tcx.layout_of(
ty::TypingEnv::post_analysis(tcx, field.did).as_query_input(ty),
)
.is_ok_and(|layout| !layout.is_1zst())
})
.map_or_else(
|| adt.all_fields().any(|field| field.vis.is_public()),
|field| field.vis.is_public(),
);
pub(crate) fn attributes_and_repr(
&self,
tcx: TyCtxt<'_>,
cache: &Cache,
is_json: bool,
) -> Vec<String> {
let mut attrs = self.attributes_without_repr(tcx, is_json);

if render_transparent {
out.push("transparent");
}
}
if repr.simd() {
out.push("simd");
}
let pack_s;
if let Some(pack) = repr.pack {
pack_s = format!("packed({})", pack.bytes());
out.push(&pack_s);
}
let align_s;
if let Some(align) = repr.align {
align_s = format!("align({})", align.bytes());
out.push(&align_s);
}
let int_s;
if let Some(int) = repr.int {
int_s = match int {
IntegerType::Pointer(is_signed) => {
format!("{}size", if is_signed { 'i' } else { 'u' })
}
IntegerType::Fixed(size, is_signed) => {
format!("{}{}", if is_signed { 'i' } else { 'u' }, size.size().bytes() * 8)
}
};
out.push(&int_s);
}
if !out.is_empty() {
attrs.push(format!("#[repr({})]", out.join(", ")));
}
if let Some(repr_attr) = self.repr(tcx, cache, is_json) {
attrs.push(repr_attr);
}
attrs
}

/// Returns a stringified `#[repr(...)]` attribute.
pub(crate) fn repr(&self, tcx: TyCtxt<'_>, cache: &Cache, is_json: bool) -> Option<String> {
repr_attributes(tcx, cache, self.def_id()?, self.type_(), is_json)
}

pub fn is_doc_hidden(&self) -> bool {
self.attrs.is_doc_hidden()
}
@@ -873,6 +827,73 @@ impl Item {
}
}

pub(crate) fn repr_attributes(
tcx: TyCtxt<'_>,
cache: &Cache,
def_id: DefId,
item_type: ItemType,
is_json: bool,
) -> Option<String> {
use rustc_abi::IntegerType;

if !matches!(item_type, ItemType::Struct | ItemType::Enum | ItemType::Union) {
return None;
}
let adt = tcx.adt_def(def_id);
let repr = adt.repr();
let mut out = Vec::new();
if repr.c() {
out.push("C");
}
if repr.transparent() {
// Render `repr(transparent)` iff the non-1-ZST field is public or at least one
// field is public in case all fields are 1-ZST fields.
let render_transparent = cache.document_private
|| is_json
|| adt
.all_fields()
.find(|field| {
let ty = field.ty(tcx, ty::GenericArgs::identity_for_item(tcx, field.did));
tcx.layout_of(ty::TypingEnv::post_analysis(tcx, field.did).as_query_input(ty))
.is_ok_and(|layout| !layout.is_1zst())
})
.map_or_else(
|| adt.all_fields().any(|field| field.vis.is_public()),
|field| field.vis.is_public(),
);

if render_transparent {
out.push("transparent");
}
}
if repr.simd() {
out.push("simd");
}
let pack_s;
if let Some(pack) = repr.pack {
pack_s = format!("packed({})", pack.bytes());
out.push(&pack_s);
}
let align_s;
if let Some(align) = repr.align {
align_s = format!("align({})", align.bytes());
out.push(&align_s);
}
let int_s;
if let Some(int) = repr.int {
int_s = match int {
IntegerType::Pointer(is_signed) => {
format!("{}size", if is_signed { 'i' } else { 'u' })
}
IntegerType::Fixed(size, is_signed) => {
format!("{}{}", if is_signed { 'i' } else { 'u' }, size.size().bytes() * 8)
}
};
out.push(&int_s);
}
if !out.is_empty() { Some(format!("#[repr({})]", out.join(", "))) } else { None }
}

#[derive(Clone, Debug)]
pub(crate) enum ItemKind {
ExternCrateItem {
@@ -2107,7 +2128,7 @@ impl Enum {
self.variants.iter().any(|f| f.is_stripped())
}

pub(crate) fn variants(&self) -> impl Iterator<Item = &Item> {
pub(crate) fn non_stripped_variants(&self) -> impl Iterator<Item = &Item> {
self.variants.iter().filter(|v| !v.is_stripped())
}
}
@@ -2345,6 +2366,17 @@ pub(crate) enum TypeAliasInnerType {
Struct { ctor_kind: Option<CtorKind>, fields: Vec<Item> },
}

impl TypeAliasInnerType {
fn has_stripped_entries(&self) -> Option<bool> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't this make more sense as has_stripped_variants? Am I missing something?

Ofc if we're doing that we should rename the other has_stripped_entries for consistency, I think that seems pretty in line with all the other refactoring going on here.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe I'm the one who missed something. 😆

A type alias can be an alias of an enum, a union or a struct. Of these three, 2 have fields and one has variants. So in this case, neither "fields" nor "variants" can be used.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah, you're right. really it's the other has_stripped_entries that look odd, since in those cases we do actually know if its a field or variant. i guess it makes sense to keep the names the same, and i suppose the function body is simple enough it doesn't need a doc comment.

Some(match self {
Self::Enum { variants, .. } => variants.iter().any(|v| v.is_stripped()),
Self::Union { fields } | Self::Struct { fields, .. } => {
fields.iter().any(|f| f.is_stripped())
}
})
}
}

#[derive(Clone, Debug)]
pub(crate) struct TypeAlias {
pub(crate) type_: Type,
24 changes: 21 additions & 3 deletions src/librustdoc/html/render/mod.rs
Original file line number Diff line number Diff line change
@@ -1194,18 +1194,36 @@ fn render_assoc_item(
// a whitespace prefix and newline.
fn render_attributes_in_pre(it: &clean::Item, prefix: &str, cx: &Context<'_>) -> impl fmt::Display {
fmt::from_fn(move |f| {
for a in it.attributes(cx.tcx(), cx.cache(), false) {
for a in it.attributes_and_repr(cx.tcx(), cx.cache(), false) {
writeln!(f, "{prefix}{a}")?;
}
Ok(())
})
}

struct CodeAttribute(String);

fn render_code_attribute(code_attr: CodeAttribute, w: &mut impl fmt::Write) {
write!(w, "<div class=\"code-attribute\">{}</div>", code_attr.0).unwrap();
}

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

/// used for type aliases to only render their `repr` attribute.
fn render_repr_attributes_in_code(
w: &mut impl fmt::Write,
cx: &Context<'_>,
def_id: DefId,
item_type: ItemType,
) {
if let Some(repr) = clean::repr_attributes(cx.tcx(), cx.cache(), def_id, item_type, false) {
render_code_attribute(CodeAttribute(repr), w);
}
}

341 changes: 205 additions & 136 deletions src/librustdoc/html/render/print_item.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/librustdoc/html/render/sidebar.rs
Original file line number Diff line number Diff line change
@@ -599,7 +599,7 @@ fn sidebar_enum<'a>(
deref_id_map: &'a DefIdMap<String>,
) {
let mut variants = e
.variants()
.non_stripped_variants()
.filter_map(|v| v.name)
.map(|name| Link::new(format!("variant.{name}"), name.to_string()))
.collect::<Vec<_>>();
9 changes: 5 additions & 4 deletions src/librustdoc/html/templates/item_union.html
Original file line number Diff line number Diff line change
@@ -2,15 +2,16 @@
{{ self.render_attributes_in_pre()|safe }}
{{ self.render_union()|safe }}
</code></pre>
{{ self.document()|safe }}
{% if self.fields_iter().peek().is_some() %}
{% if !self.is_type_alias %}
{{ self.document()|safe }}
{% endif %}
{% if self.fields_iter().next().is_some() %}
<h2 id="fields" class="fields section-header"> {# #}
Fields<a href="#fields" class="anchor">§</a> {# #}
</h2>
{% for (field, ty) in self.fields_iter() %}
{% let name = field.name.expect("union field name") %}
<span id="structfield.{{ name }}" {#+ #}
class="{{ ItemType::StructField +}} section-header"> {# #}
<span id="structfield.{{ name }}" class="{{ ItemType::StructField +}} section-header"> {# #}
<a href="#structfield.{{ name }}" class="anchor field">§</a> {# #}
<code>{{ name }}: {{+ self.print_ty(ty)|safe }}</code> {# #}
</span>
2 changes: 1 addition & 1 deletion src/librustdoc/json/conversions.rs
Original file line number Diff line number Diff line change
@@ -40,7 +40,7 @@ impl JsonRenderer<'_> {
})
.collect();
let docs = item.opt_doc_value();
let attrs = item.attributes(self.tcx, self.cache(), true);
let attrs = item.attributes_and_repr(self.tcx, self.cache(), true);
let span = item.span(self.tcx);
let visibility = item.visibility(self.tcx);
let clean::ItemInner { name, item_id, .. } = *item.inner;
42 changes: 42 additions & 0 deletions tests/rustdoc/type-alias/repr.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// This test ensures that the `repr` attribute is displayed in type aliases.
//
// Regression test for <https://github.com/rust-lang/rust/issues/140739>.

#![crate_name = "foo"]

/// bla
#[repr(C)]
pub struct Foo1;

//@ has 'foo/type.Bar1.html'
//@ has - '//*[@class="rust item-decl"]/code' '#[repr(C)]pub struct Bar1;'
// Ensures that we see the doc comment of the type alias and not of the aliased type.
//@ has - '//*[@class="toggle top-doc"]/*[@class="docblock"]' 'bar'
/// bar
pub type Bar1 = Foo1;

/// bla
#[repr(C)]
pub union Foo2 {
pub a: u8,
}

//@ has 'foo/type.Bar2.html'
//@ matches - '//*[@class="rust item-decl"]' '#\[repr\(C\)\]\npub union Bar2 \{*'
// Ensures that we see the doc comment of the type alias and not of the aliased type.
//@ has - '//*[@class="toggle top-doc"]/*[@class="docblock"]' 'bar'
/// bar
pub type Bar2 = Foo2;

/// bla
#[repr(C)]
pub enum Foo3 {
A,
}

//@ has 'foo/type.Bar3.html'
//@ matches - '//*[@class="rust item-decl"]' '#\[repr\(C\)\]pub enum Bar3 \{*'
// Ensures that we see the doc comment of the type alias and not of the aliased type.
//@ has - '//*[@class="toggle top-doc"]/*[@class="docblock"]' 'bar'
/// bar
pub type Bar3 = Foo3;
2 changes: 1 addition & 1 deletion tests/rustdoc/type-layout.rs
Original file line number Diff line number Diff line change
@@ -61,7 +61,7 @@ pub type TypeAlias = X;
pub type GenericTypeAlias = (Generic<(u32, ())>, Generic<u32>);

// Regression test for the rustdoc equivalent of #85103.
//@ hasraw type_layout/type.Edges.html 'Encountered an error during type layout; the type failed to be normalized.'
//@ hasraw type_layout/type.Edges.html 'Unable to compute type layout, possibly due to this type having generic parameters. Layout can only be computed for concrete, fully-instantiated types.'
pub type Edges<'a, E> = std::borrow::Cow<'a, [E]>;

//@ !hasraw type_layout/trait.MyTrait.html 'Size: '