Sub topic 13
Enforcing documentation with lints
Earlier chapters showed how to write documentation. This chapter shows how to make the compiler complain when documentation is missing or broken. It assumes you can build a library crate with Cargo, write /// and //! comments, and use intra-doc links. It also assumes you have seen the # Errors, # Panics, and # Safety sections.
Three tools report documentation problems, and each owns different lints:
rustcownsmissing_docs.rustdocowns the lints in therustdoc::namespace.- Clippy owns the lints that check the conventional sections.
You enable and escalate them with attributes, with a Cargo manifest table, or with command-line flags.
Which tool runs which lint
A lint runs only when its tool runs. cargo build never reports a broken intra-doc link, because only cargo doc runs the rustdoc lints. cargo clippy runs the Clippy lints and the rustc lints together.
The `missing_docs` lint
missing_docs warns about public items that have no doc comment. It is set to allow by default, so it does nothing until you turn it on:
#![warn(missing_docs)]Put this at the top of lib.rs, before the first item. The lint covers the following:
- The crate itself, which needs a
//!comment. - Public modules, functions, structs, enums, traits, constants, and type aliases.
- Public struct fields and enum variants.
- Public trait methods.
The lint does not cover private items, or public items that cannot be reached from outside the crate. It also skips trait implementations, because the trait's own documentation already describes them.
You can use a stricter level instead:
#![deny(missing_docs)]With deny, a missing comment is a compile error. That is harsh during everyday development, when you are sketching code that has no docs yet. A common compromise is warn in the source and a strict flag in CI, described later.
The Clippy documentation lints
missing_docs only checks that some comment exists. It cannot tell whether the comment has the sections a reader needs. Clippy covers that.
| Lint | Default | What it reports |
|---|---|---|
| `clippy::missing_errors_doc` | pedantic (off) | A public function returns `Result` but has no `# Errors` section. |
| `clippy::missing_panics_doc` | pedantic (off) | A public function can panic (for example through `panic!`, `unwrap`, `expect`, or `assert!`) but has no `# Panics` section. |
| `clippy::missing_safety_doc` | warn | A public `unsafe fn` has no `# Safety` section. |
| `clippy::undocumented_unsafe_blocks` | restriction (off) | An `unsafe` block has no `// SAFETY:` comment above it. |
| `clippy::doc_markdown` | pedantic (off) | Code-like words in docs (such as `HashMap`) are not wrapped in backticks. |
| `clippy::missing_docs_in_private_items` | restriction (off) | Any item, including private ones, has no docs. |
Only missing_safety_doc is on by default. You enable the others by name:
#![warn(clippy::missing_errors_doc, clippy::missing_panics_doc)]Clippy cannot tell whether your # Errors text is any good. It checks that the heading exists, nothing more.
A worked example
This lib.rs has three problems. The first is undocumented, the second hides an error path, and the third hides a panic path:
//! Helpers for parsing ports.
#![warn(missing_docs)]
#![warn(clippy::missing_errors_doc, clippy::missing_panics_doc)]
use std::num::ParseIntError;
pub struct Config {
pub port: u16,
}
/// Parses a decimal port number.
pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse()
}
/// Returns the first port in a comma-separated list.
pub fn first_port(list: &str) -> u16 {
list.split(',')
.next()
.expect("split yields at least one item")
.trim()
.parse()
.expect("first entry must be a valid port")
}cargo clippy reports three warnings:
Configand itsportfield are missing documentation, frommissing_docs.parse_portreturnsResultwith no# Errorssection, frommissing_errors_doc.first_portcallsexpectwith no# Panicssection, frommissing_panics_doc.
Here is the fixed version:
//! Helpers for parsing ports.
#![warn(missing_docs)]
#![warn(clippy::missing_errors_doc, clippy::missing_panics_doc)]
use std::num::ParseIntError;
/// Server settings.
pub struct Config {
/// The TCP port to listen on.
pub port: u16,
}
/// Parses a decimal port number.
///
/// # Errors
///
/// Returns [`ParseIntError`] if `s` is not a valid `u16`.
///
/// # Examples
///
/// ```
/// assert_eq!(mycrate::parse_port(" 8080 ")?, 8080);
/// # Ok::<(), std::num::ParseIntError>(())
/// ```
pub fn parse_port(s: &str) -> Result<u16, ParseIntError> {
s.trim().parse()
}
/// Returns the first port in a comma-separated list.
///
/// # Panics
///
/// Panics if the first entry is not a valid `u16`.
///
/// # Examples
///
/// ```
/// assert_eq!(mycrate::first_port("80,443"), 80);
/// ```
pub fn first_port(list: &str) -> u16 {
list.split(',')
.next()
.expect("split yields at least one item")
.trim()
.parse()
.expect("first entry must be a valid port")
}The Panics section describes the case a caller can cause. The expect on split can never fail, and you do not need to document it. Clippy cannot tell the two apart, which is why you still have to read its warnings with judgment.
The rustdoc lints
The rustdoc:: lints check the documentation text itself. These are the ones you will meet most often:
| Lint | Default | What it reports |
|---|---|---|
| `rustdoc::broken_intra_doc_links` | warn | A link such as [`Foo`] points at an item that does not resolve. |
| `rustdoc::private_intra_doc_links` | warn | Public docs link to a private item, so the link is dead in the published docs. |
| `rustdoc::bare_urls` | warn | A URL is written without `<...>` or Markdown link syntax. |
| `rustdoc::invalid_html_tags` | warn | Unclosed or unknown HTML tags appear in docs, often from unescaped generics like `Vec<u8>` outside backticks. |
| `rustdoc::invalid_codeblock_attributes` | warn | A code fence has an attribute that looks like a typo, such as `should_panic` misspelled. |
| `rustdoc::missing_crate_level_docs` | allow | The crate root has no `//!` documentation. |
| `rustdoc::private_doc_tests` | allow | A private item contains a doc test that no reader will ever see. |
To turn a warning into an error, use an attribute:
#![deny(rustdoc::broken_intra_doc_links)]There is also a group name, rustdoc::all, that covers every rustdoc lint. Use it when you want to be strict without listing each lint.
rustdoc::missing_doc_code_examples also exists. It reports public items that have no example. It is nightly-only and unstable, so you cannot use it on stable Rust.
Configuring lints in `Cargo.toml`
Since Rust 1.74 you can keep all lint levels in the manifest instead of scattering attributes across source files:
[lints.rust]
missing_docs = "warn"
[lints.rustdoc]
broken_intra_doc_links = "deny"
bare_urls = "deny"
[lints.clippy]
missing_errors_doc = "warn"
missing_panics_doc = "warn"This applies to every target in the package, and workspace members can inherit a shared table with [lints] workspace = true. A source-level attribute still overrides the manifest for the item or module it applies to.
Turning off a lint for one item
Sometimes a public item really needs no comment, such as a re-exported type documented elsewhere. Suppress the lint on that item only, and leave the crate-wide setting in place:
#[allow(missing_docs)]
pub struct Internal;On Rust 1.81 and later, #[expect(missing_docs)] is a better choice. It does the same job, but it warns you when the suppression is no longer needed, so stale exceptions do not pile up.
Making warnings fail the build
A warning that nobody reads protects nothing. Make the lints fail the build in CI, where an unnoticed warning would otherwise be merged:
cargo clippy --all-targets -- -D warnings
RUSTDOCFLAGS="-D warnings" cargo doc --no-depsThe first command makes every rustc and Clippy warning an error. The second makes every rustdoc warning an error. The --no-deps flag keeps the check on your own crate.
Be aware of one trade-off. -D warnings also fails on warnings that a newer compiler adds. If your CI uses the latest stable toolchain, a Rust release can break your build with no change in your code. Either pin the toolchain version or accept that occasional cleanup.
Lint levels set in your source do not affect your users. Cargo caps lints in dependencies from registries, so a deny(missing_docs) in your crate never breaks a downstream build.
Common mistakes
- Expecting
cargo buildto report a broken link. Onlycargo docruns the rustdoc lints. - Enabling
missing_docsand assuming private items are covered. Useclippy::missing_docs_in_private_itemsif you want that. - Writing an empty
# Errorssection to silence Clippy. The lint passes, and the documentation is still useless. - Forgetting
--no-depsin CI and spending time on warnings that you cannot fix.
Exercise
A public function load(path: &str) -> Result<String, std::io::Error> has a doc comment with a summary and an example, but no # Errors section. You have #![warn(missing_docs)] at the top of lib.rs, and cargo build shows no warning. Why is there no warning, and what would you add to get one?
Show answer
missing_docs only checks that a doc comment exists, and this function has one. The check for a missing # Errors section belongs to Clippy's missing_errors_doc lint. It is off by default and runs only under cargo clippy. Add #![warn(clippy::missing_errors_doc)] (or missing_errors_doc = "warn" under [lints.clippy] in Cargo.toml) and run cargo clippy. Then write an # Errors section that says when load returns Err.
Exercise
Write the two commands that a CI job should run so that missing Clippy sections and broken intra-doc links both fail the build, without checking dependencies.
Show answer
cargo clippy --all-targets -- -D warnings fails on Clippy and rustc warnings, and RUSTDOCFLAGS="-D warnings" cargo doc --no-deps fails on rustdoc warnings such as broken intra-doc links. The Clippy lints for missing sections only fire if you have enabled them, for example with #![warn(clippy::missing_errors_doc, clippy::missing_panics_doc)].