rust-lang / rust

Empowering everyone to build reliable and efficient software.
https://www.rust-lang.org
Other
99.03k stars 12.79k forks source link

using `super` in doctests errors #130274

Open y86-dev opened 2 months ago

y86-dev commented 2 months ago

I tried this code:

/// ```
/// type Y = ();
/// mod m {
///     use super::Y;
///     fn f() -> Y {}
/// }
/// ```
pub struct X;

in lib.rs.

I expected to see this happen: successful cargo test

Instead, this happened:

cargo test
   Compiling rust v0.0.0 (/tmp/tmp)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 0.13s
     Running unittests src/lib.rs (target/debug/deps/rust-48a0867617020c3e)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s

   Doc-tests rust

running 1 test
test src/lib.rs - X (line 1) ... FAILED

failures:

---- src/lib.rs - X (line 1) stdout ----
error[E0432]: unresolved import `super::Y`
 --> src/lib.rs:4:9
  |
5 |     use super::Y;
  |         ^^^^^^^^ no `Y` in the root

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0432`.
Couldn't compile the test.

failures:
    src/lib.rs - X (line 1)

test result: FAILED. 0 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.02s

error: doctest failed, to rerun pass `--doc`

The same error happens when using super::Y directly in the return type.

Meta

rustc --version --verbose:

rustc 1.83.0-nightly (8d6b88b16 2024-09-11)
binary: rustc
commit-hash: 8d6b88b168e45ee1624699c19443c49665322a91
commit-date: 2024-09-11
host: x86_64-unknown-linux-gnu
release: 1.83.0-nightly
LLVM version: 19.1.0
Urgau commented 2 months ago

Each doctest is put in it's own function, and since super always refer to a module, it's expected that it won't find what's inside the doctest function, whenever that behaviour is something we want or not and can be fix is another thing.

fn doctest() {
    type Y = ();
    mod m {
        use super::Y;  // unresolved import `super::Y`
        fn f() -> Y {}
    }
}
fmease commented 2 months ago

cc #79260 the underlying rustc issue

Darksonn commented 2 months ago

Even if this is intended behavior, is there any chance we could include a note in the error explaining this?

ehuss commented 2 months ago

BTW, you can add fn main() {} to your doctest to make it work:

/// ```
/// type Y = ();
/// mod m {
///     use super::Y;
///     fn f() -> Y {}
/// }
/// # fn main() {}
/// ```
pub struct X;
Darksonn commented 1 month ago

I posted a question about this:

https://users.rust-lang.org/t/private-fields-in-macro-generated-structs/120052