Re: [PATCH v2] rust: doctest: fix line numbers after crate-level attributes
From: David Gow
Date: Tue Nov 24 2026 - 02:03:24 EST
Le 08/11/2026 à 00:36, Younes Akhouayri via B4 Relay a écrit :
From: Younes Akhouayri <git@xxxxxxxxx>
When a doctest starts with a crate-level attribute such as
`#![expect(...)]`, KUnit reports failures one line too early, and
`line!()` returns a line number that is one too low.
This happens because `rustdoc` moves those attribute lines out of the
test body and puts them above the `main` function it generates. The
generator works out where the body starts by counting the lines above
`main`, but it does not know that some of those lines were moved there
from the body. So every line after a moved attribute is mapped one line
too early (or more, if there are several such attributes).
For example, adding `assert_eq!(36, 0);` as line 36 of
`rust/kernel/init.rs` (inside the doctest that starts with
`# #![expect(clippy::undocumented_unsafe_blocks)]`) gives:
# rust_doctest_kernel_init_rs_2: ASSERTION FAILED at rust/kernel/init.rs:35
Twelve in-tree doctests start like this, e.g. in `bits.rs`, `devres.rs`,
`init.rs` and `std_vendor.rs`.
A quick note that the ones in bits.rs are nested in a macro, so the location is dubious anyway, and this doesn't fix it. Others all looked good.
Fix it by counting the attribute lines that `rustdoc` moved (every
`#![...]` line above `main`, except the `#![allow(unused)]` that
`rustdoc` adds itself) and taking them into account when computing
where the body starts.
`rustdoc` always starts its output with that `#![allow(unused)]`, so
check for it before relying on the layout. If a future `rustdoc` (or a
crate-level `#![doc(test(attr(...)))]`) changes it, print a warning once
and keep the previous behaviour rather than failing the build: the tests
still run, only the reported line numbers would be off.
Only single-line attributes are handled, which covers every doctest in
the tree today.
With this change, the example above reports `rust/kernel/init.rs:36`,
and doctests without such attributes keep reporting the same lines as
before.
Fixes: a66d733da801 ("rust: support running Rust documentation tests as KUnit ones")
Signed-off-by: Younes Akhouayri <git@xxxxxxxxx>
---
Changes in v2:
- Check that the generated test starts with `#![allow(unused)]` before
subtracting the moved lines; otherwise warn once and keep the old
behaviour, instead of clamping with `saturating_sub` (Miguel).
- Note in the comment and commit message that only single-line
attributes are handled.
- Link to v1: https://patch.msgid.link/20261027-rust-doctest-line-fix-v1-1-0c13185a58b6@xxxxxxxxx
---
Thanks very much. This looks good to me!
Reviewed-by: David Gow <david@xxxxxxxxxxxx>
Cheers,
-- David