Skip to content

Commit ecd7b48

Browse files
authored
Rollup merge of #41678 - GuillaumeGomez:rustdoc-test-warnings, r=alexcrichton
Add option to display warnings in rustdoc Part of #41574. r? @alexcrichton The output for this file: ```rust /// ``` /// fn foo(x: u32) {} /// /// foo(2); /// let x = 1; /// panic!(); /// ``` fn foo() {} /// ``` /// fn foo(x: u32) {} /// /// foo(2); /// let x = 1; /// ``` fn foo2() {} /// ``` /// fn foo(x: u32) {} /// /// foo(2); /// let x = 1; /// panic!(); /// ``` fn foo3() {} fn main() { } ``` is the following: ``` > ./build/x86_64-apple-darwin/stage1/bin/rustdoc -Z unstable-options --display-warnings --test test.rs running 3 tests test test.rs - foo (line 1) ... FAILED test test.rs - foo3 (line 18) ... FAILED test test.rs - foo2 (line 10) ... ok successes: ---- test.rs - foo2 (line 10) stdout ---- warning: unused variable: `x` --> <anon>:2:8 | 2 | fn foo(x: u32) {} | ^ | = note: #[warn(unused_variables)] on by default warning: unused variable: `x` --> <anon>:5:5 | 5 | let x = 1; | ^ | = note: #[warn(unused_variables)] on by default successes: test.rs - foo2 (line 10) failures: ---- test.rs - foo (line 1) stdout ---- warning: unused variable: `x` --> <anon>:2:8 | 2 | fn foo(x: u32) {} | ^ | = note: #[warn(unused_variables)] on by default warning: unused variable: `x` --> <anon>:5:5 | 5 | let x = 1; | ^ | = note: #[warn(unused_variables)] on by default thread 'rustc' panicked at 'test executable failed: thread 'main' panicked at 'explicit panic', <anon>:6 note: Run with `RUST_BACKTRACE=1` for a backtrace. ', src/librustdoc/test.rs:317 note: Run with `RUST_BACKTRACE=1` for a backtrace. ---- test.rs - foo3 (line 18) stdout ---- warning: unused variable: `x` --> <anon>:2:8 | 2 | fn foo(x: u32) {} | ^ | = note: #[warn(unused_variables)] on by default warning: unused variable: `x` --> <anon>:5:5 | 5 | let x = 1; | ^ | = note: #[warn(unused_variables)] on by default thread 'rustc' panicked at 'test executable failed: thread 'main' panicked at 'explicit panic', <anon>:6 note: Run with `RUST_BACKTRACE=1` for a backtrace. ', src/librustdoc/test.rs:317 failures: test.rs - foo (line 1) test.rs - foo3 (line 18) test result: FAILED. 1 passed; 2 failed; 0 ignored; 0 measured ```
2 parents b091d6e + d5863e9 commit ecd7b48

File tree

7 files changed

+89
-17
lines changed

7 files changed

+89
-17
lines changed

src/librustdoc/core.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,8 @@ pub fn run_core(search_paths: SearchPaths,
104104
externs: config::Externs,
105105
input: Input,
106106
triple: Option<String>,
107-
maybe_sysroot: Option<PathBuf>) -> (clean::Crate, RenderInfo)
107+
maybe_sysroot: Option<PathBuf>,
108+
allow_warnings: bool) -> (clean::Crate, RenderInfo)
108109
{
109110
// Parse, resolve, and typecheck the given crate.
110111

@@ -119,7 +120,7 @@ pub fn run_core(search_paths: SearchPaths,
119120
maybe_sysroot: maybe_sysroot,
120121
search_paths: search_paths,
121122
crate_types: vec![config::CrateTypeRlib],
122-
lint_opts: vec![(warning_lint, lint::Allow)],
123+
lint_opts: if !allow_warnings { vec![(warning_lint, lint::Allow)] } else { vec![] },
123124
lint_cap: Some(lint::Allow),
124125
externs: externs,
125126
target_triple: triple.unwrap_or(config::host_triple().to_string()),

src/librustdoc/lib.rs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,7 @@ pub fn opts() -> Vec<RustcOptGroup> {
173173
or `#![doc(html_playground_url=...)]`",
174174
"URL")),
175175
unstable(optflag("", "enable-commonmark", "to enable commonmark doc rendering/testing")),
176+
unstable(optflag("", "display-warnings", "to print code warnings when testing doc")),
176177
]
177178
}
178179

@@ -280,14 +281,16 @@ pub fn main_args(args: &[String]) -> isize {
280281
let crate_name = matches.opt_str("crate-name");
281282
let playground_url = matches.opt_str("playground-url");
282283
let maybe_sysroot = matches.opt_str("sysroot").map(PathBuf::from);
284+
let display_warnings = matches.opt_present("display-warnings");
283285

284286
match (should_test, markdown_input) {
285287
(true, true) => {
286-
return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type)
288+
return markdown::test(input, cfgs, libs, externs, test_args, maybe_sysroot, render_type,
289+
display_warnings)
287290
}
288291
(true, false) => {
289292
return test::run(input, cfgs, libs, externs, test_args, crate_name, maybe_sysroot,
290-
render_type)
293+
render_type, display_warnings)
291294
}
292295
(false, true) => return markdown::render(input,
293296
output.unwrap_or(PathBuf::from("doc")),
@@ -389,13 +392,15 @@ where R: 'static + Send, F: 'static + Send + FnOnce(Output) -> R {
389392

390393
let cr = PathBuf::from(cratefile);
391394
info!("starting to run rustc");
395+
let display_warnings = matches.opt_present("display-warnings");
392396

393397
let (tx, rx) = channel();
394398
rustc_driver::monitor(move || {
395399
use rustc::session::config::Input;
396400

397401
let (mut krate, renderinfo) =
398-
core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot);
402+
core::run_core(paths, cfgs, externs, Input::File(cr), triple, maybe_sysroot,
403+
display_warnings);
399404

400405
info!("finished with rustc");
401406

src/librustdoc/markdown.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ pub fn render(input: &str, mut output: PathBuf, matches: &getopts::Matches,
150150
/// Run any tests/code examples in the markdown file `input`.
151151
pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
152152
mut test_args: Vec<String>, maybe_sysroot: Option<PathBuf>,
153-
render_type: RenderType) -> isize {
153+
render_type: RenderType, display_warnings: bool) -> isize {
154154
let input_str = match load_string(input) {
155155
Ok(s) => s,
156156
Err(LoadStringError::ReadFail) => return 1,
@@ -166,6 +166,7 @@ pub fn test(input: &str, cfgs: Vec<String>, libs: SearchPaths, externs: Externs,
166166
old_find_testable_code(&input_str, &mut collector, DUMMY_SP);
167167
find_testable_code(&input_str, &mut collector, DUMMY_SP);
168168
test_args.insert(0, "rustdoctest".to_string());
169-
testing::test_main(&test_args, collector.tests);
169+
testing::test_main(&test_args, collector.tests,
170+
testing::Options::new().display_output(display_warnings));
170171
0
171172
}

src/librustdoc/test.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,8 @@ pub fn run(input: &str,
5858
mut test_args: Vec<String>,
5959
crate_name: Option<String>,
6060
maybe_sysroot: Option<PathBuf>,
61-
render_type: RenderType)
61+
render_type: RenderType,
62+
display_warnings: bool)
6263
-> isize {
6364
let input_path = PathBuf::from(input);
6465
let input = config::Input::File(input_path.clone());
@@ -127,7 +128,8 @@ pub fn run(input: &str,
127128
test_args.insert(0, "rustdoctest".to_string());
128129

129130
testing::test_main(&test_args,
130-
collector.tests.into_iter().collect());
131+
collector.tests.into_iter().collect(),
132+
testing::Options::new().display_output(display_warnings));
131133
0
132134
}
133135

src/libsyntax/test.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -442,7 +442,7 @@ We're going to be building a module that looks more or less like:
442442
mod __test {
443443
extern crate test (name = "test", vers = "...");
444444
fn main() {
445-
test::test_main_static(&::os::args()[], tests)
445+
test::test_main_static(&::os::args()[], tests, test::Options::new())
446446
}
447447
448448
static tests : &'static [test::TestDescAndFn] = &[
@@ -478,7 +478,7 @@ fn mk_main(cx: &mut TestCtxt) -> P<ast::Item> {
478478
// pub fn main() {
479479
// #![main]
480480
// use std::slice::AsSlice;
481-
// test::test_main_static(::std::os::args().as_slice(), TESTS);
481+
// test::test_main_static(::std::os::args().as_slice(), TESTS, test::Options::new());
482482
// }
483483

484484
let sp = ignored_span(cx, DUMMY_SP);

src/libtest/lib.rs

Lines changed: 68 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ pub mod test {
7676
pub use {Bencher, TestName, TestResult, TestDesc, TestDescAndFn, TestOpts, TrFailed,
7777
TrFailedMsg, TrIgnored, TrOk, Metric, MetricMap, StaticTestFn, StaticTestName,
7878
DynTestName, DynTestFn, run_test, test_main, test_main_static, filter_tests,
79-
parse_opts, StaticBenchFn, ShouldPanic};
79+
parse_opts, StaticBenchFn, ShouldPanic, Options};
8080
}
8181

8282
pub mod stats;
@@ -252,14 +252,34 @@ impl Clone for MetricMap {
252252
}
253253
}
254254

255+
/// In case we want to add other options as well, just add them in this struct.
256+
#[derive(Copy, Clone, Debug)]
257+
pub struct Options {
258+
display_output: bool,
259+
}
260+
261+
impl Options {
262+
pub fn new() -> Options {
263+
Options {
264+
display_output: false,
265+
}
266+
}
267+
268+
pub fn display_output(mut self, display_output: bool) -> Options {
269+
self.display_output = display_output;
270+
self
271+
}
272+
}
273+
255274
// The default console test runner. It accepts the command line
256275
// arguments and a vector of test_descs.
257-
pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>) {
258-
let opts = match parse_opts(args) {
276+
pub fn test_main(args: &[String], tests: Vec<TestDescAndFn>, options: Options) {
277+
let mut opts = match parse_opts(args) {
259278
Some(Ok(o)) => o,
260279
Some(Err(msg)) => panic!("{:?}", msg),
261280
None => return,
262281
};
282+
opts.options = options;
263283
if opts.list {
264284
if let Err(e) = list_tests_console(&opts, tests) {
265285
panic!("io error when listing tests: {:?}", e);
@@ -301,16 +321,17 @@ pub fn test_main_static(tests: &[TestDescAndFn]) {
301321
}
302322
})
303323
.collect();
304-
test_main(&args, owned_tests)
324+
test_main(&args, owned_tests, Options::new())
305325
}
306326

307-
#[derive(Copy, Clone)]
327+
#[derive(Copy, Clone, Debug)]
308328
pub enum ColorConfig {
309329
AutoColor,
310330
AlwaysColor,
311331
NeverColor,
312332
}
313333

334+
#[derive(Debug)]
314335
pub struct TestOpts {
315336
pub list: bool,
316337
pub filter: Option<String>,
@@ -324,6 +345,7 @@ pub struct TestOpts {
324345
pub quiet: bool,
325346
pub test_threads: Option<usize>,
326347
pub skip: Vec<String>,
348+
pub options: Options,
327349
}
328350

329351
impl TestOpts {
@@ -342,6 +364,7 @@ impl TestOpts {
342364
quiet: false,
343365
test_threads: None,
344366
skip: vec![],
367+
options: Options::new(),
345368
}
346369
}
347370
}
@@ -481,6 +504,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
481504
quiet: quiet,
482505
test_threads: test_threads,
483506
skip: matches.opt_strs("skip"),
507+
options: Options::new(),
484508
};
485509

486510
Some(Ok(test_opts))
@@ -521,7 +545,9 @@ struct ConsoleTestState<T> {
521545
measured: usize,
522546
metrics: MetricMap,
523547
failures: Vec<(TestDesc, Vec<u8>)>,
548+
not_failures: Vec<(TestDesc, Vec<u8>)>,
524549
max_name_len: usize, // number of columns to fill when aligning names
550+
options: Options,
525551
}
526552

527553
impl<T: Write> ConsoleTestState<T> {
@@ -547,7 +573,9 @@ impl<T: Write> ConsoleTestState<T> {
547573
measured: 0,
548574
metrics: MetricMap::new(),
549575
failures: Vec::new(),
576+
not_failures: Vec::new(),
550577
max_name_len: 0,
578+
options: opts.options,
551579
})
552580
}
553581

@@ -703,9 +731,38 @@ impl<T: Write> ConsoleTestState<T> {
703731
Ok(())
704732
}
705733

734+
pub fn write_outputs(&mut self) -> io::Result<()> {
735+
self.write_plain("\nsuccesses:\n")?;
736+
let mut successes = Vec::new();
737+
let mut stdouts = String::new();
738+
for &(ref f, ref stdout) in &self.not_failures {
739+
successes.push(f.name.to_string());
740+
if !stdout.is_empty() {
741+
stdouts.push_str(&format!("---- {} stdout ----\n\t", f.name));
742+
let output = String::from_utf8_lossy(stdout);
743+
stdouts.push_str(&output);
744+
stdouts.push_str("\n");
745+
}
746+
}
747+
if !stdouts.is_empty() {
748+
self.write_plain("\n")?;
749+
self.write_plain(&stdouts)?;
750+
}
751+
752+
self.write_plain("\nsuccesses:\n")?;
753+
successes.sort();
754+
for name in &successes {
755+
self.write_plain(&format!(" {}\n", name))?;
756+
}
757+
Ok(())
758+
}
759+
706760
pub fn write_run_finish(&mut self) -> io::Result<bool> {
707761
assert!(self.passed + self.failed + self.ignored + self.measured == self.total);
708762

763+
if self.options.display_output {
764+
self.write_outputs()?;
765+
}
709766
let success = self.failed == 0;
710767
if !success {
711768
self.write_failures()?;
@@ -824,7 +881,10 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Resu
824881
st.write_log_result(&test, &result)?;
825882
st.write_result(&result)?;
826883
match result {
827-
TrOk => st.passed += 1,
884+
TrOk => {
885+
st.passed += 1;
886+
st.not_failures.push((test, stdout));
887+
}
828888
TrIgnored => st.ignored += 1,
829889
TrMetrics(mm) => {
830890
let tname = test.name;
@@ -901,6 +961,8 @@ fn should_sort_failures_before_printing_them() {
901961
max_name_len: 10,
902962
metrics: MetricMap::new(),
903963
failures: vec![(test_b, Vec::new()), (test_a, Vec::new())],
964+
options: Options::new(),
965+
not_failures: Vec::new(),
904966
};
905967

906968
st.write_failures().unwrap();

src/tools/compiletest/src/main.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,6 +336,7 @@ pub fn test_opts(config: &Config) -> test::TestOpts {
336336
test_threads: None,
337337
skip: vec![],
338338
list: false,
339+
options: test::Options::new(),
339340
}
340341
}
341342

0 commit comments

Comments
 (0)