How to document optional features in API docs

For example, in this tokio-rs doc, there is the

This is supported on crate feature rt only.

How do we add that do the docs? I can't find it anywhere; tokio's source code does not seem to have that explicitly.

It's an unstable attribute. Tracking issue. In the future it's hoped that the docs will get it right automatically, with the attribute only existing for a manual override.

1 Like

I'm a Tokio maintainer. Here are the steps to do this:

First you add this to your Cargo.toml:

all-features = true
rustdoc-args = ["--cfg", "docsrs"]

This will make compile your documentation with RUSTFLAGS="--cfg docsrs" set. We can use this to conditionally enable nightly features when building documentation, but not when building it normally.

Now you add this to your file:

#![cfg_attr(docsrs, feature(doc_cfg))]

Then, on anything that needs such an annotation, you add the following

#[cfg_attr(docsrs, doc(cfg(feature = "rt")))]

This supports all of the syntax that #[cfg(...)] does, including stuff like platform-specifiers and any/all. Tokio often sets this annotation using the macros in src/macros/ Note that the annotation works recursively, so putting it on a module also affects the stuff inside (sometimes, it's a bit flaky).

Finally, when building the documentation locally, you run the following command:

RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --all-features

Awesome, thanks a lot. I had to change it to RUSTDOCFLAGS="--cfg docsrs" to the local run. Tokio is using the same on the CI. So,

RUSTDOCFLAGS="--cfg docsrs" cargo +nightly doc --features full

seems sufficient here (RUSTFLAGS is not needed apparently).

Ah I mixed them up, yes. The RUSTFLAGS variable is for setting stuff in dependencies of the crate being documented. I edited the previous post.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.