Skip to content

rustdoc: Named constants in array sizes shouldn't be evaluated #102456

Open
@jmillikin

Description

@jmillikin

Current rustdoc behavior

Given the following code:

pub struct SomeStruct { _p: () }

#[cfg(target_os = "linux")]
const TARGET_STORAGE_SIZE: usize = 128;
#[cfg(not(target_os = "linux"))]
const TARGET_STORAGE_SIZE: usize = 256;

impl SomeStruct {
    /// How much storage to allocate for a call to
    /// [`some_method`](Self::some_method).
    pub const STORAGE_SIZE: usize = TARGET_STORAGE_SIZE;

    /// The user is expected to call this with an array of size
    /// `SomeStruct::STORAGE_SIZE`, whatever that happens to be.
    pub fn some_method(
        &self,
        storage: &mut [u8; SomeStruct::STORAGE_SIZE],
    ) {}
}

The user would be expected to call it like this:

let mut storage = [0u8; SomeStruct::STORAGE_SIZE];
some_struct.some_method(&mut storage);

Unfortunately, the rustdoc output is confusing because it evaluates the constant when formatting the function signature:

rustdoc-1

If a user were to copy-paste from the rustdoc'd function signature when writing the call site, they would write code like this, which would fail to compile on some platforms:

let mut storage = [0u8; 128];
some_struct.some_method(&mut storage);

Proposed new behavior

A better way to format this function signature would be to use the constant's name, if the constant is public:

rustdoc-2

An even niftier formatting would let the constant become a link:

rustdoc-3

Metadata

Metadata

Assignees

Labels

C-bugCategory: This is a bug.T-rustdocRelevant to the rustdoc team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions