Skip to content

Commit

Permalink
Rollup merge of rust-lang#91259 - jyn514:doctest-warnings, r=Guillaum…
Browse files Browse the repository at this point in the history
…eGomez

Remove `--display-doctest-warnings`

`--display-doctest-warnings` can be replicated in full with other existing features, there's no
need to have a separate option for it. This removes the option and documents the combination of other features to replicate it.

This also fixes a bug where `--test-args=--show-output` had no effect.

cc `@ollie27,` rust-lang#73314 (comment)
Fixes rust-lang#41574

r? `@GuillaumeGomez`
  • Loading branch information
matthiaskrgr authored Nov 26, 2021
2 parents 404235e + 7e4bf4b commit 092477d
Show file tree
Hide file tree
Showing 8 changed files with 68 additions and 74 deletions.
10 changes: 10 additions & 0 deletions src/doc/rustdoc/src/documentation-tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,16 @@ conversion, so type inference fails because the type is not unique. Please note
that you must write the `(())` in one sequence without intermediate whitespace
so that `rustdoc` understands you want an implicit `Result`-returning function.

## Showing warnings in doctests

You can show warnings in doctests by running `rustdoc --test --test-args=--show-output`
(or, if you're using cargo, `cargo test --doc -- --show-output`).
By default, this will still hide `unused` warnings, since so many examples use private functions;
you can add `#![warn(unused)]` to the top of your example if you want to see unused variables or dead code warnings.
You can also use [`#![doc(test(attr(warn(unused))))]`][test-attr] in the crate root to enable warnings globally.

[test-attr]: ./the-doc-attribute.md#testattr

## Documenting macros

Here’s an example of documenting a macro:
Expand Down
16 changes: 0 additions & 16 deletions src/doc/rustdoc/src/unstable-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,22 +257,6 @@ all these files are linked from every page, changing where they are can be cumbe
specially cache them. This flag will rename all these files in the output to include the suffix in
the filename. For example, `light.css` would become `light-suf.css` with the above command.

### `--display-doctest-warnings`: display warnings when documenting or running documentation tests

Using this flag looks like this:

```bash
$ rustdoc src/lib.rs -Z unstable-options --display-doctest-warnings
$ rustdoc --test src/lib.rs -Z unstable-options --display-doctest-warnings
```

The intent behind this flag is to allow the user to see warnings that occur within their library or
their documentation tests, which are usually suppressed. However, [due to a
bug][issue-display-warnings], this flag doesn't 100% work as intended. See the linked issue for
details.

[issue-display-warnings]: https://github.com/rust-lang/rust/issues/41574

### `--extern-html-root-url`: control how rustdoc links to non-local crates

Using this flag looks like this:
Expand Down
6 changes: 0 additions & 6 deletions src/librustdoc/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,6 @@ crate struct Options {
///
/// Be aware: This option can come both from the CLI and from crate attributes!
crate manual_passes: Vec<String>,
/// Whether to display warnings during doc generation or while gathering doctests. By default,
/// all non-rustdoc-specific lints are allowed when generating docs.
crate display_doctest_warnings: bool,
/// Whether to run the `calculate-doc-coverage` pass, which counts the number of public items
/// with and without documentation.
crate show_coverage: bool,
Expand Down Expand Up @@ -197,7 +194,6 @@ impl fmt::Debug for Options {
.field("persist_doctests", &self.persist_doctests)
.field("default_passes", &self.default_passes)
.field("manual_passes", &self.manual_passes)
.field("display_doctest_warnings", &self.display_doctest_warnings)
.field("show_coverage", &self.show_coverage)
.field("crate_version", &self.crate_version)
.field("render_options", &self.render_options)
Expand Down Expand Up @@ -639,7 +635,6 @@ impl Options {
let proc_macro_crate = crate_types.contains(&CrateType::ProcMacro);
let playground_url = matches.opt_str("playground-url");
let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
let display_doctest_warnings = matches.opt_present("display-doctest-warnings");
let sort_modules_alphabetically = !matches.opt_present("sort-modules-by-appearance");
let resource_suffix = matches.opt_str("resource-suffix").unwrap_or_default();
let enable_minification = !matches.opt_present("disable-minification");
Expand Down Expand Up @@ -707,7 +702,6 @@ impl Options {
test_args,
default_passes,
manual_passes,
display_doctest_warnings,
show_coverage,
crate_version,
test_run_directory,
Expand Down
31 changes: 9 additions & 22 deletions src/librustdoc/doctest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,6 @@ use crate::passes::span_of_attrs;
crate struct TestOptions {
/// Whether to disable the default `extern crate my_crate;` when creating doctests.
crate no_crate_inject: bool,
/// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
/// the default `#![allow(unused)]`.
crate display_doctest_warnings: bool,
/// Additional crate-level attributes to add to doctests.
crate attrs: Vec<String>,
}
Expand All @@ -65,14 +62,16 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
}
});

debug!(?lint_opts);

let crate_types =
if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };

let sessopts = config::Options {
maybe_sysroot: options.maybe_sysroot.clone(),
search_paths: options.libs.clone(),
crate_types,
lint_opts: if !options.display_doctest_warnings { lint_opts } else { vec![] },
lint_opts,
lint_cap: Some(options.lint_cap.unwrap_or(lint::Forbid)),
cg: options.codegen_options.clone(),
externs: options.externs.clone(),
Expand Down Expand Up @@ -106,7 +105,6 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
};

let test_args = options.test_args.clone();
let display_doctest_warnings = options.display_doctest_warnings;
let nocapture = options.nocapture;
let externs = options.externs.clone();
let json_unused_externs = options.json_unused_externs;
Expand All @@ -118,8 +116,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
let collector = global_ctxt.enter(|tcx| {
let crate_attrs = tcx.hir().attrs(CRATE_HIR_ID);

let mut opts = scrape_test_config(crate_attrs);
opts.display_doctest_warnings |= options.display_doctest_warnings;
let opts = scrape_test_config(crate_attrs);
let enable_per_target_ignores = options.enable_per_target_ignores;
let mut collector = Collector::new(
tcx.crate_name(LOCAL_CRATE),
Expand Down Expand Up @@ -165,7 +162,7 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
Err(ErrorReported) => return Err(ErrorReported),
};

run_tests(test_args, nocapture, display_doctest_warnings, tests);
run_tests(test_args, nocapture, tests);

// Collect and warn about unused externs, but only if we've gotten
// reports for each doctest
Expand Down Expand Up @@ -208,29 +205,19 @@ crate fn run(options: Options) -> Result<(), ErrorReported> {
Ok(())
}

crate fn run_tests(
mut test_args: Vec<String>,
nocapture: bool,
display_doctest_warnings: bool,
tests: Vec<test::TestDescAndFn>,
) {
crate fn run_tests(mut test_args: Vec<String>, nocapture: bool, tests: Vec<test::TestDescAndFn>) {
test_args.insert(0, "rustdoctest".to_string());
if nocapture {
test_args.push("--nocapture".to_string());
}
test::test_main(
&test_args,
tests,
Some(test::Options::new().display_output(display_doctest_warnings)),
);
test::test_main(&test_args, tests, None);
}

// Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
fn scrape_test_config(attrs: &[ast::Attribute]) -> TestOptions {
use rustc_ast_pretty::pprust;

let mut opts =
TestOptions { no_crate_inject: false, display_doctest_warnings: false, attrs: Vec::new() };
let mut opts = TestOptions { no_crate_inject: false, attrs: Vec::new() };

let test_attrs: Vec<_> = attrs
.iter()
Expand Down Expand Up @@ -510,7 +497,7 @@ crate fn make_test(
let mut prog = String::new();
let mut supports_color = false;

if opts.attrs.is_empty() && !opts.display_doctest_warnings {
if opts.attrs.is_empty() {
// If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
// lints that are commonly triggered in doctests. The crate-level test attributes are
// commonly used to make tests fail in case they trigger warnings, so having this there in
Expand Down
17 changes: 1 addition & 16 deletions src/librustdoc/doctest/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ assert_eq!(2+2, 4);
fn make_test_no_crate_inject() {
// Even if you do use the crate within the test, setting `opts.no_crate_inject` will skip
// adding it anyway.
let opts =
TestOptions { no_crate_inject: true, display_doctest_warnings: false, attrs: vec![] };
let opts = TestOptions { no_crate_inject: true, attrs: vec![] };
let input = "use asdf::qwop;
assert_eq!(2+2, 4);";
let expected = "#![allow(unused)]
Expand Down Expand Up @@ -215,20 +214,6 @@ assert_eq!(2+2, 4);"
assert_eq!((output, len), (expected, 1));
}

#[test]
fn make_test_display_doctest_warnings() {
// If the user is asking to display doctest warnings, suppress the default `allow(unused)`.
let mut opts = TestOptions::default();
opts.display_doctest_warnings = true;
let input = "assert_eq!(2+2, 4);";
let expected = "fn main() {
assert_eq!(2+2, 4);
}"
.to_string();
let (output, len, _) = make_test(input, None, false, &opts, DEFAULT_EDITION, None);
assert_eq!((output, len), (expected, 1));
}

#[test]
fn make_test_issues_21299_33731() {
let opts = TestOptions::default();
Expand Down
8 changes: 1 addition & 7 deletions src/librustdoc/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ crate fn test(options: Options) -> Result<(), String> {
.map_err(|err| format!("{}: {}", options.input.display(), err))?;
let mut opts = TestOptions::default();
opts.no_crate_inject = true;
opts.display_doctest_warnings = options.display_doctest_warnings;
let mut collector = Collector::new(
Symbol::intern(&options.input.display().to_string()),
options.clone(),
Expand All @@ -146,11 +145,6 @@ crate fn test(options: Options) -> Result<(), String> {

find_testable_code(&input_str, &mut collector, codes, options.enable_per_target_ignores, None);

crate::doctest::run_tests(
options.test_args,
options.nocapture,
options.display_doctest_warnings,
collector.tests,
);
crate::doctest::run_tests(options.test_args, options.nocapture, collector.tests);
Ok(())
}
8 changes: 7 additions & 1 deletion src/test/rustdoc-ui/display-output.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
// Test that `--show-output` has an effect and `allow(unused)` can be overriden.

// check-pass
// compile-flags:-Zunstable-options --display-doctest-warnings --test
// edition:2018
// compile-flags:--test --test-args=--show-output
// normalize-stdout-test: "src/test/rustdoc-ui" -> "$$DIR"
// normalize-stdout-test "finished in \d+\.\d+s" -> "finished in $$TIME"

/// ```
/// #![warn(unused)]
/// let x = 12;
///
/// fn foo(x: &std::fmt::Display) {}
/// ```
pub fn foo() {}
46 changes: 40 additions & 6 deletions src/test/rustdoc-ui/display-output.stdout
Original file line number Diff line number Diff line change
@@ -1,24 +1,58 @@

running 1 test
test $DIR/display-output.rs - foo (line 6) ... ok
test $DIR/display-output.rs - foo (line 9) ... ok

successes:

---- $DIR/display-output.rs - foo (line 6) stdout ----
---- $DIR/display-output.rs - foo (line 9) stdout ----
warning: trait objects without an explicit `dyn` are deprecated
--> $DIR/display-output.rs:13:12
|
LL | fn foo(x: &std::fmt::Display) {}
| ^^^^^^^^^^^^^^^^^ help: use `dyn`: `dyn std::fmt::Display`
|
= note: `#[warn(bare_trait_objects)]` on by default
= warning: this is accepted in the current edition (Rust 2018) but is a hard error in Rust 2021!
= note: for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/warnings-promoted-to-error.html>

warning: unused variable: `x`
--> $DIR/display-output.rs:7:5
--> $DIR/display-output.rs:11:5
|
LL | let x = 12;
| ^ help: if this is intentional, prefix it with an underscore: `_x`
|
= note: `#[warn(unused_variables)]` on by default
note: the lint level is defined here
--> $DIR/display-output.rs:9:9
|
LL | #![warn(unused)]
| ^^^^^^
= note: `#[warn(unused_variables)]` implied by `#[warn(unused)]`

warning: unused variable: `x`
--> $DIR/display-output.rs:13:8
|
LL | fn foo(x: &std::fmt::Display) {}
| ^ help: if this is intentional, prefix it with an underscore: `_x`

warning: function is never used: `foo`
--> $DIR/display-output.rs:13:4
|
LL | fn foo(x: &std::fmt::Display) {}
| ^^^
|
note: the lint level is defined here
--> $DIR/display-output.rs:9:9
|
LL | #![warn(unused)]
| ^^^^^^
= note: `#[warn(dead_code)]` implied by `#[warn(unused)]`

warning: 1 warning emitted
warning: 4 warnings emitted



successes:
$DIR/display-output.rs - foo (line 6)
$DIR/display-output.rs - foo (line 9)

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in $TIME

0 comments on commit 092477d

Please sign in to comment.