]> git.lizzy.rs Git - rust.git/blob - src/librustdoc/test.rs
Fix error code failure check in rustdoc test
[rust.git] / src / librustdoc / test.rs
1 use rustc::hir;
2 use rustc::hir::intravisit;
3 use rustc::session::{self, config, DiagnosticOutput};
4 use rustc::util::common::ErrorReported;
5 use rustc_data_structures::sync::Lrc;
6 use rustc_feature::UnstableFeatures;
7 use rustc_interface::interface;
8 use rustc_span::edition::Edition;
9 use rustc_span::source_map::SourceMap;
10 use rustc_span::symbol::sym;
11 use rustc_span::{BytePos, FileName, Pos, Span, DUMMY_SP};
12 use rustc_target::spec::TargetTriple;
13 use std::env;
14 use std::io::{self, Write};
15 use std::panic;
16 use std::path::PathBuf;
17 use std::process::{self, Command, Stdio};
18 use std::str;
19 use syntax::ast;
20 use syntax::with_globals;
21 use tempfile::Builder as TempFileBuilder;
22 use testing;
23
24 use crate::clean::Attributes;
25 use crate::config::Options;
26 use crate::html::markdown::{self, ErrorCodes, Ignore, LangString};
27
28 #[derive(Clone, Default)]
29 pub struct TestOptions {
30     /// Whether to disable the default `extern crate my_crate;` when creating doctests.
31     pub no_crate_inject: bool,
32     /// Whether to emit compilation warnings when compiling doctests. Setting this will suppress
33     /// the default `#![allow(unused)]`.
34     pub display_warnings: bool,
35     /// Additional crate-level attributes to add to doctests.
36     pub attrs: Vec<String>,
37 }
38
39 pub fn run(options: Options) -> i32 {
40     let input = config::Input::File(options.input.clone());
41
42     let crate_types = if options.proc_macro_crate {
43         vec![config::CrateType::ProcMacro]
44     } else {
45         vec![config::CrateType::Dylib]
46     };
47
48     let sessopts = config::Options {
49         maybe_sysroot: options.maybe_sysroot.clone(),
50         search_paths: options.libs.clone(),
51         crate_types,
52         cg: options.codegen_options.clone(),
53         externs: options.externs.clone(),
54         unstable_features: UnstableFeatures::from_environment(),
55         lint_cap: Some(::rustc::lint::Level::Allow),
56         actually_rustdoc: true,
57         debugging_opts: config::DebuggingOptions { ..config::basic_debugging_options() },
58         edition: options.edition,
59         target_triple: options.target.clone(),
60         ..config::Options::default()
61     };
62
63     let mut cfgs = options.cfgs.clone();
64     cfgs.push("doc".to_owned());
65     cfgs.push("doctest".to_owned());
66     let config = interface::Config {
67         opts: sessopts,
68         crate_cfg: interface::parse_cfgspecs(cfgs),
69         input,
70         input_path: None,
71         output_file: None,
72         output_dir: None,
73         file_loader: None,
74         diagnostic_output: DiagnosticOutput::Default,
75         stderr: None,
76         crate_name: options.crate_name.clone(),
77         lint_caps: Default::default(),
78         register_lints: None,
79         override_queries: None,
80         registry: rustc_driver::diagnostics_registry(),
81     };
82
83     let mut test_args = options.test_args.clone();
84     let display_warnings = options.display_warnings;
85
86     let tests = interface::run_compiler(config, |compiler| {
87         compiler.enter(|queries| {
88             let lower_to_hir = queries.lower_to_hir()?;
89
90             let mut opts = scrape_test_config(lower_to_hir.peek().0.krate());
91             opts.display_warnings |= options.display_warnings;
92             let enable_per_target_ignores = options.enable_per_target_ignores;
93             let mut collector = Collector::new(
94                 queries.crate_name()?.peek().to_string(),
95                 options,
96                 false,
97                 opts,
98                 Some(compiler.source_map().clone()),
99                 None,
100                 enable_per_target_ignores,
101             );
102
103             let mut global_ctxt = queries.global_ctxt()?.take();
104
105             global_ctxt.enter(|tcx| {
106                 let krate = tcx.hir().krate();
107                 let mut hir_collector = HirCollector {
108                     sess: compiler.session(),
109                     collector: &mut collector,
110                     map: tcx.hir(),
111                     codes: ErrorCodes::from(
112                         compiler.session().opts.unstable_features.is_nightly_build(),
113                     ),
114                 };
115                 hir_collector.visit_testable("".to_string(), &krate.attrs, |this| {
116                     intravisit::walk_crate(this, krate);
117                 });
118             });
119
120             let ret: Result<_, ErrorReported> = Ok(collector.tests);
121             ret
122         })
123     })
124     .expect("compiler aborted in rustdoc!");
125
126     test_args.insert(0, "rustdoctest".to_string());
127
128     testing::test_main(
129         &test_args,
130         tests,
131         Some(testing::Options::new().display_output(display_warnings)),
132     );
133
134     0
135 }
136
137 // Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
138 fn scrape_test_config(krate: &::rustc::hir::Crate) -> TestOptions {
139     use syntax::print::pprust;
140
141     let mut opts =
142         TestOptions { no_crate_inject: false, display_warnings: false, attrs: Vec::new() };
143
144     let test_attrs: Vec<_> = krate
145         .attrs
146         .iter()
147         .filter(|a| a.check_name(sym::doc))
148         .flat_map(|a| a.meta_item_list().unwrap_or_else(Vec::new))
149         .filter(|a| a.check_name(sym::test))
150         .collect();
151     let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
152
153     for attr in attrs {
154         if attr.check_name(sym::no_crate_inject) {
155             opts.no_crate_inject = true;
156         }
157         if attr.check_name(sym::attr) {
158             if let Some(l) = attr.meta_item_list() {
159                 for item in l {
160                     opts.attrs.push(pprust::meta_list_item_to_string(item));
161                 }
162             }
163         }
164     }
165
166     opts
167 }
168
169 /// Documentation test failure modes.
170 enum TestFailure {
171     /// The test failed to compile.
172     CompileError,
173     /// The test is marked `compile_fail` but compiled successfully.
174     UnexpectedCompilePass,
175     /// The test failed to compile (as expected) but the compiler output did not contain all
176     /// expected error codes.
177     MissingErrorCodes(Vec<String>),
178     /// The test binary was unable to be executed.
179     ExecutionError(io::Error),
180     /// The test binary exited with a non-zero exit code.
181     ///
182     /// This typically means an assertion in the test failed or another form of panic occurred.
183     ExecutionFailure(process::Output),
184     /// The test is marked `should_panic` but the test binary executed successfully.
185     UnexpectedRunPass,
186 }
187
188 fn run_test(
189     test: &str,
190     cratename: &str,
191     filename: &FileName,
192     line: usize,
193     options: Options,
194     should_panic: bool,
195     no_run: bool,
196     as_test_harness: bool,
197     runtool: Option<String>,
198     runtool_args: Vec<String>,
199     target: TargetTriple,
200     compile_fail: bool,
201     mut error_codes: Vec<String>,
202     opts: &TestOptions,
203     edition: Edition,
204 ) -> Result<(), TestFailure> {
205     let (test, line_offset) = make_test(test, Some(cratename), as_test_harness, opts, edition);
206
207     // FIXME(#44940): if doctests ever support path remapping, then this filename
208     // needs to be the result of `SourceMap::span_to_unmapped_path`.
209     let path = match filename {
210         FileName::Real(path) => path.clone(),
211         _ => PathBuf::from(r"doctest.rs"),
212     };
213
214     enum DirState {
215         Temp(tempfile::TempDir),
216         Perm(PathBuf),
217     }
218
219     impl DirState {
220         fn path(&self) -> &std::path::Path {
221             match self {
222                 DirState::Temp(t) => t.path(),
223                 DirState::Perm(p) => p.as_path(),
224             }
225         }
226     }
227
228     let outdir = if let Some(mut path) = options.persist_doctests {
229         path.push(format!(
230             "{}_{}",
231             filename.to_string().rsplit('/').next().unwrap().replace(".", "_"),
232             line
233         ));
234         std::fs::create_dir_all(&path).expect("Couldn't create directory for doctest executables");
235
236         DirState::Perm(path)
237     } else {
238         DirState::Temp(
239             TempFileBuilder::new()
240                 .prefix("rustdoctest")
241                 .tempdir()
242                 .expect("rustdoc needs a tempdir"),
243         )
244     };
245     let output_file = outdir.path().join("rust_out");
246
247     let rustc_binary = options
248         .test_builder
249         .as_ref()
250         .map(|v| &**v)
251         .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
252     let mut compiler = Command::new(&rustc_binary);
253     compiler.arg("--crate-type").arg("bin");
254     for cfg in &options.cfgs {
255         compiler.arg("--cfg").arg(&cfg);
256     }
257     if let Some(sysroot) = options.maybe_sysroot {
258         compiler.arg("--sysroot").arg(sysroot);
259     }
260     compiler.arg("--edition").arg(&edition.to_string());
261     compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", path);
262     compiler.env("UNSTABLE_RUSTDOC_TEST_LINE", format!("{}", line as isize - line_offset as isize));
263     compiler.arg("-o").arg(&output_file);
264     if as_test_harness {
265         compiler.arg("--test");
266     }
267     for lib_str in &options.lib_strs {
268         compiler.arg("-L").arg(&lib_str);
269     }
270     for extern_str in &options.extern_strs {
271         compiler.arg("--extern").arg(&extern_str);
272     }
273     compiler.arg("-Ccodegen-units=1");
274     for codegen_options_str in &options.codegen_options_strs {
275         compiler.arg("-C").arg(&codegen_options_str);
276     }
277     for debugging_option_str in &options.debugging_options_strs {
278         compiler.arg("-Z").arg(&debugging_option_str);
279     }
280     if no_run {
281         compiler.arg("--emit=metadata");
282     }
283     compiler.arg("--target").arg(target.to_string());
284
285     compiler.arg("-");
286     compiler.stdin(Stdio::piped());
287     compiler.stderr(Stdio::piped());
288
289     let mut child = compiler.spawn().expect("Failed to spawn rustc process");
290     {
291         let stdin = child.stdin.as_mut().expect("Failed to open stdin");
292         stdin.write_all(test.as_bytes()).expect("could write out test sources");
293     }
294     let output = child.wait_with_output().expect("Failed to read stdout");
295
296     struct Bomb<'a>(&'a str);
297     impl Drop for Bomb<'_> {
298         fn drop(&mut self) {
299             eprint!("{}", self.0);
300         }
301     }
302     let out = str::from_utf8(&output.stderr).unwrap();
303     let _bomb = Bomb(&out);
304     match (output.status.success(), compile_fail) {
305         (true, true) => {
306             return Err(TestFailure::UnexpectedCompilePass);
307         }
308         (true, false) => {}
309         (false, true) => {
310             if !error_codes.is_empty() {
311                 error_codes.retain(|err| !out.contains(&format!("error[{}]: ", err)));
312
313                 if !error_codes.is_empty() {
314                     return Err(TestFailure::MissingErrorCodes(error_codes));
315                 }
316             }
317         }
318         (false, false) => {
319             return Err(TestFailure::CompileError);
320         }
321     }
322
323     if no_run {
324         return Ok(());
325     }
326
327     // Run the code!
328     let mut cmd;
329
330     if let Some(tool) = runtool {
331         cmd = Command::new(tool);
332         cmd.arg(output_file);
333         cmd.args(runtool_args);
334     } else {
335         cmd = Command::new(output_file);
336     }
337
338     match cmd.output() {
339         Err(e) => return Err(TestFailure::ExecutionError(e)),
340         Ok(out) => {
341             if should_panic && out.status.success() {
342                 return Err(TestFailure::UnexpectedRunPass);
343             } else if !should_panic && !out.status.success() {
344                 return Err(TestFailure::ExecutionFailure(out));
345             }
346         }
347     }
348
349     Ok(())
350 }
351
352 /// Transforms a test into code that can be compiled into a Rust binary, and returns the number of
353 /// lines before the test code begins.
354 pub fn make_test(
355     s: &str,
356     cratename: Option<&str>,
357     dont_insert_main: bool,
358     opts: &TestOptions,
359     edition: Edition,
360 ) -> (String, usize) {
361     let (crate_attrs, everything_else, crates) = partition_source(s);
362     let everything_else = everything_else.trim();
363     let mut line_offset = 0;
364     let mut prog = String::new();
365
366     if opts.attrs.is_empty() && !opts.display_warnings {
367         // If there aren't any attributes supplied by #![doc(test(attr(...)))], then allow some
368         // lints that are commonly triggered in doctests. The crate-level test attributes are
369         // commonly used to make tests fail in case they trigger warnings, so having this there in
370         // that case may cause some tests to pass when they shouldn't have.
371         prog.push_str("#![allow(unused)]\n");
372         line_offset += 1;
373     }
374
375     // Next, any attributes that came from the crate root via #![doc(test(attr(...)))].
376     for attr in &opts.attrs {
377         prog.push_str(&format!("#![{}]\n", attr));
378         line_offset += 1;
379     }
380
381     // Now push any outer attributes from the example, assuming they
382     // are intended to be crate attributes.
383     prog.push_str(&crate_attrs);
384     prog.push_str(&crates);
385
386     // Uses libsyntax to parse the doctest and find if there's a main fn and the extern
387     // crate already is included.
388     let result = rustc_driver::catch_fatal_errors(|| {
389         with_globals(edition, || {
390             use errors::emitter::EmitterWriter;
391             use errors::Handler;
392             use rustc_parse::maybe_new_parser_from_source_str;
393             use rustc_span::source_map::FilePathMapping;
394             use syntax::sess::ParseSess;
395
396             let filename = FileName::anon_source_code(s);
397             let source = crates + &everything_else;
398
399             // Any errors in parsing should also appear when the doctest is compiled for real, so just
400             // send all the errors that libsyntax emits directly into a `Sink` instead of stderr.
401             let cm = Lrc::new(SourceMap::new(FilePathMapping::empty()));
402             let emitter =
403                 EmitterWriter::new(box io::sink(), None, false, false, false, None, false);
404             // FIXME(misdreavus): pass `-Z treat-err-as-bug` to the doctest parser
405             let handler = Handler::with_emitter(false, None, box emitter);
406             let sess = ParseSess::with_span_handler(handler, cm);
407
408             let mut found_main = false;
409             let mut found_extern_crate = cratename.is_none();
410             let mut found_macro = false;
411
412             let mut parser = match maybe_new_parser_from_source_str(&sess, filename, source) {
413                 Ok(p) => p,
414                 Err(errs) => {
415                     for mut err in errs {
416                         err.cancel();
417                     }
418
419                     return (found_main, found_extern_crate, found_macro);
420                 }
421             };
422
423             loop {
424                 match parser.parse_item() {
425                     Ok(Some(item)) => {
426                         if !found_main {
427                             if let ast::ItemKind::Fn(..) = item.kind {
428                                 if item.ident.name == sym::main {
429                                     found_main = true;
430                                 }
431                             }
432                         }
433
434                         if !found_extern_crate {
435                             if let ast::ItemKind::ExternCrate(original) = item.kind {
436                                 // This code will never be reached if `cratename` is none because
437                                 // `found_extern_crate` is initialized to `true` if it is none.
438                                 let cratename = cratename.unwrap();
439
440                                 match original {
441                                     Some(name) => found_extern_crate = name.as_str() == cratename,
442                                     None => found_extern_crate = item.ident.as_str() == cratename,
443                                 }
444                             }
445                         }
446
447                         if !found_macro {
448                             if let ast::ItemKind::Mac(..) = item.kind {
449                                 found_macro = true;
450                             }
451                         }
452
453                         if found_main && found_extern_crate {
454                             break;
455                         }
456                     }
457                     Ok(None) => break,
458                     Err(mut e) => {
459                         e.cancel();
460                         break;
461                     }
462                 }
463             }
464
465             (found_main, found_extern_crate, found_macro)
466         })
467     });
468     let (already_has_main, already_has_extern_crate, found_macro) = match result {
469         Ok(result) => result,
470         Err(ErrorReported) => {
471             // If the parser panicked due to a fatal error, pass the test code through unchanged.
472             // The error will be reported during compilation.
473             return (s.to_owned(), 0);
474         }
475     };
476
477     // If a doctest's `fn main` is being masked by a wrapper macro, the parsing loop above won't
478     // see it. In that case, run the old text-based scan to see if they at least have a main
479     // function written inside a macro invocation. See
480     // https://github.com/rust-lang/rust/issues/56898
481     let already_has_main = if found_macro && !already_has_main {
482         s.lines()
483             .map(|line| {
484                 let comment = line.find("//");
485                 if let Some(comment_begins) = comment { &line[0..comment_begins] } else { line }
486             })
487             .any(|code| code.contains("fn main"))
488     } else {
489         already_has_main
490     };
491
492     // Don't inject `extern crate std` because it's already injected by the
493     // compiler.
494     if !already_has_extern_crate && !opts.no_crate_inject && cratename != Some("std") {
495         if let Some(cratename) = cratename {
496             // Make sure its actually used if not included.
497             if s.contains(cratename) {
498                 prog.push_str(&format!("extern crate {};\n", cratename));
499                 line_offset += 1;
500             }
501         }
502     }
503
504     // FIXME: This code cannot yet handle no_std test cases yet
505     if dont_insert_main || already_has_main || prog.contains("![no_std]") {
506         prog.push_str(everything_else);
507     } else {
508         let returns_result = everything_else.trim_end().ends_with("(())");
509         let (main_pre, main_post) = if returns_result {
510             (
511                 "fn main() { fn _inner() -> Result<(), impl core::fmt::Debug> {",
512                 "}\n_inner().unwrap() }",
513             )
514         } else {
515             ("fn main() {\n", "\n}")
516         };
517         prog.extend([main_pre, everything_else, main_post].iter().cloned());
518         line_offset += 1;
519     }
520
521     debug!("final doctest:\n{}", prog);
522
523     (prog, line_offset)
524 }
525
526 // FIXME(aburka): use a real parser to deal with multiline attributes
527 fn partition_source(s: &str) -> (String, String, String) {
528     #[derive(Copy, Clone, PartialEq)]
529     enum PartitionState {
530         Attrs,
531         Crates,
532         Other,
533     }
534     let mut state = PartitionState::Attrs;
535     let mut before = String::new();
536     let mut crates = String::new();
537     let mut after = String::new();
538
539     for line in s.lines() {
540         let trimline = line.trim();
541
542         // FIXME(misdreavus): if a doc comment is placed on an extern crate statement, it will be
543         // shunted into "everything else"
544         match state {
545             PartitionState::Attrs => {
546                 state = if trimline.starts_with("#![")
547                     || trimline.chars().all(|c| c.is_whitespace())
548                     || (trimline.starts_with("//") && !trimline.starts_with("///"))
549                 {
550                     PartitionState::Attrs
551                 } else if trimline.starts_with("extern crate")
552                     || trimline.starts_with("#[macro_use] extern crate")
553                 {
554                     PartitionState::Crates
555                 } else {
556                     PartitionState::Other
557                 };
558             }
559             PartitionState::Crates => {
560                 state = if trimline.starts_with("extern crate")
561                     || trimline.starts_with("#[macro_use] extern crate")
562                     || trimline.chars().all(|c| c.is_whitespace())
563                     || (trimline.starts_with("//") && !trimline.starts_with("///"))
564                 {
565                     PartitionState::Crates
566                 } else {
567                     PartitionState::Other
568                 };
569             }
570             PartitionState::Other => {}
571         }
572
573         match state {
574             PartitionState::Attrs => {
575                 before.push_str(line);
576                 before.push_str("\n");
577             }
578             PartitionState::Crates => {
579                 crates.push_str(line);
580                 crates.push_str("\n");
581             }
582             PartitionState::Other => {
583                 after.push_str(line);
584                 after.push_str("\n");
585             }
586         }
587     }
588
589     debug!("before:\n{}", before);
590     debug!("crates:\n{}", crates);
591     debug!("after:\n{}", after);
592
593     (before, after, crates)
594 }
595
596 pub trait Tester {
597     fn add_test(&mut self, test: String, config: LangString, line: usize);
598     fn get_line(&self) -> usize {
599         0
600     }
601     fn register_header(&mut self, _name: &str, _level: u32) {}
602 }
603
604 pub struct Collector {
605     pub tests: Vec<testing::TestDescAndFn>,
606
607     // The name of the test displayed to the user, separated by `::`.
608     //
609     // In tests from Rust source, this is the path to the item
610     // e.g., `["std", "vec", "Vec", "push"]`.
611     //
612     // In tests from a markdown file, this is the titles of all headers (h1~h6)
613     // of the sections that contain the code block, e.g., if the markdown file is
614     // written as:
615     //
616     // ``````markdown
617     // # Title
618     //
619     // ## Subtitle
620     //
621     // ```rust
622     // assert!(true);
623     // ```
624     // ``````
625     //
626     // the `names` vector of that test will be `["Title", "Subtitle"]`.
627     names: Vec<String>,
628
629     options: Options,
630     use_headers: bool,
631     enable_per_target_ignores: bool,
632     cratename: String,
633     opts: TestOptions,
634     position: Span,
635     source_map: Option<Lrc<SourceMap>>,
636     filename: Option<PathBuf>,
637 }
638
639 impl Collector {
640     pub fn new(
641         cratename: String,
642         options: Options,
643         use_headers: bool,
644         opts: TestOptions,
645         source_map: Option<Lrc<SourceMap>>,
646         filename: Option<PathBuf>,
647         enable_per_target_ignores: bool,
648     ) -> Collector {
649         Collector {
650             tests: Vec::new(),
651             names: Vec::new(),
652             options,
653             use_headers,
654             enable_per_target_ignores,
655             cratename,
656             opts,
657             position: DUMMY_SP,
658             source_map,
659             filename,
660         }
661     }
662
663     fn generate_name(&self, line: usize, filename: &FileName) -> String {
664         format!("{} - {} (line {})", filename, self.names.join("::"), line)
665     }
666
667     pub fn set_position(&mut self, position: Span) {
668         self.position = position;
669     }
670
671     fn get_filename(&self) -> FileName {
672         if let Some(ref source_map) = self.source_map {
673             let filename = source_map.span_to_filename(self.position);
674             if let FileName::Real(ref filename) = filename {
675                 if let Ok(cur_dir) = env::current_dir() {
676                     if let Ok(path) = filename.strip_prefix(&cur_dir) {
677                         return path.to_owned().into();
678                     }
679                 }
680             }
681             filename
682         } else if let Some(ref filename) = self.filename {
683             filename.clone().into()
684         } else {
685             FileName::Custom("input".to_owned())
686         }
687     }
688 }
689
690 impl Tester for Collector {
691     fn add_test(&mut self, test: String, config: LangString, line: usize) {
692         let filename = self.get_filename();
693         let name = self.generate_name(line, &filename);
694         let cratename = self.cratename.to_string();
695         let opts = self.opts.clone();
696         let edition = config.edition.unwrap_or(self.options.edition.clone());
697         let options = self.options.clone();
698         let runtool = self.options.runtool.clone();
699         let runtool_args = self.options.runtool_args.clone();
700         let target = self.options.target.clone();
701         let target_str = target.to_string();
702
703         debug!("creating test {}: {}", name, test);
704         self.tests.push(testing::TestDescAndFn {
705             desc: testing::TestDesc {
706                 name: testing::DynTestName(name.clone()),
707                 ignore: match config.ignore {
708                     Ignore::All => true,
709                     Ignore::None => false,
710                     Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
711                 },
712                 // compiler failures are test failures
713                 should_panic: testing::ShouldPanic::No,
714                 allow_fail: config.allow_fail,
715                 test_type: testing::TestType::DocTest,
716             },
717             testfn: testing::DynTestFn(box move || {
718                 let res = run_test(
719                     &test,
720                     &cratename,
721                     &filename,
722                     line,
723                     options,
724                     config.should_panic,
725                     config.no_run,
726                     config.test_harness,
727                     runtool,
728                     runtool_args,
729                     target,
730                     config.compile_fail,
731                     config.error_codes,
732                     &opts,
733                     edition,
734                 );
735
736                 if let Err(err) = res {
737                     match err {
738                         TestFailure::CompileError => {
739                             eprint!("Couldn't compile the test.");
740                         }
741                         TestFailure::UnexpectedCompilePass => {
742                             eprint!("Test compiled successfully, but it's marked `compile_fail`.");
743                         }
744                         TestFailure::UnexpectedRunPass => {
745                             eprint!("Test executable succeeded, but it's marked `should_panic`.");
746                         }
747                         TestFailure::MissingErrorCodes(codes) => {
748                             eprint!("Some expected error codes were not found: {:?}", codes);
749                         }
750                         TestFailure::ExecutionError(err) => {
751                             eprint!("Couldn't run the test: {}", err);
752                             if err.kind() == io::ErrorKind::PermissionDenied {
753                                 eprint!(" - maybe your tempdir is mounted with noexec?");
754                             }
755                         }
756                         TestFailure::ExecutionFailure(out) => {
757                             let reason = if let Some(code) = out.status.code() {
758                                 format!("exit code {}", code)
759                             } else {
760                                 String::from("terminated by signal")
761                             };
762
763                             eprintln!("Test executable failed ({}).", reason);
764
765                             // FIXME(#12309): An unfortunate side-effect of capturing the test
766                             // executable's output is that the relative ordering between the test's
767                             // stdout and stderr is lost. However, this is better than the
768                             // alternative: if the test executable inherited the parent's I/O
769                             // handles the output wouldn't be captured at all, even on success.
770                             //
771                             // The ordering could be preserved if the test process' stderr was
772                             // redirected to stdout, but that functionality does not exist in the
773                             // standard library, so it may not be portable enough.
774                             let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
775                             let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
776
777                             if !stdout.is_empty() || !stderr.is_empty() {
778                                 eprintln!();
779
780                                 if !stdout.is_empty() {
781                                     eprintln!("stdout:\n{}", stdout);
782                                 }
783
784                                 if !stderr.is_empty() {
785                                     eprintln!("stderr:\n{}", stderr);
786                                 }
787                             }
788                         }
789                     }
790
791                     panic::resume_unwind(box ());
792                 }
793             }),
794         });
795     }
796
797     fn get_line(&self) -> usize {
798         if let Some(ref source_map) = self.source_map {
799             let line = self.position.lo().to_usize();
800             let line = source_map.lookup_char_pos(BytePos(line as u32)).line;
801             if line > 0 { line - 1 } else { line }
802         } else {
803             0
804         }
805     }
806
807     fn register_header(&mut self, name: &str, level: u32) {
808         if self.use_headers {
809             // We use these headings as test names, so it's good if
810             // they're valid identifiers.
811             let name = name
812                 .chars()
813                 .enumerate()
814                 .map(|(i, c)| {
815                     if (i == 0 && rustc_lexer::is_id_start(c))
816                         || (i != 0 && rustc_lexer::is_id_continue(c))
817                     {
818                         c
819                     } else {
820                         '_'
821                     }
822                 })
823                 .collect::<String>();
824
825             // Here we try to efficiently assemble the header titles into the
826             // test name in the form of `h1::h2::h3::h4::h5::h6`.
827             //
828             // Suppose that originally `self.names` contains `[h1, h2, h3]`...
829             let level = level as usize;
830             if level <= self.names.len() {
831                 // ... Consider `level == 2`. All headers in the lower levels
832                 // are irrelevant in this new level. So we should reset
833                 // `self.names` to contain headers until <h2>, and replace that
834                 // slot with the new name: `[h1, name]`.
835                 self.names.truncate(level);
836                 self.names[level - 1] = name;
837             } else {
838                 // ... On the other hand, consider `level == 5`. This means we
839                 // need to extend `self.names` to contain five headers. We fill
840                 // in the missing level (<h4>) with `_`. Thus `self.names` will
841                 // become `[h1, h2, h3, "_", name]`.
842                 if level - 1 > self.names.len() {
843                     self.names.resize(level - 1, "_".to_owned());
844                 }
845                 self.names.push(name);
846             }
847         }
848     }
849 }
850
851 struct HirCollector<'a, 'hir> {
852     sess: &'a session::Session,
853     collector: &'a mut Collector,
854     map: &'a hir::map::Map<'hir>,
855     codes: ErrorCodes,
856 }
857
858 impl<'a, 'hir> HirCollector<'a, 'hir> {
859     fn visit_testable<F: FnOnce(&mut Self)>(
860         &mut self,
861         name: String,
862         attrs: &[ast::Attribute],
863         nested: F,
864     ) {
865         let mut attrs = Attributes::from_ast(self.sess.diagnostic(), attrs);
866         if let Some(ref cfg) = attrs.cfg {
867             if !cfg.matches(&self.sess.parse_sess, Some(&self.sess.features_untracked())) {
868                 return;
869             }
870         }
871
872         let has_name = !name.is_empty();
873         if has_name {
874             self.collector.names.push(name);
875         }
876
877         attrs.collapse_doc_comments();
878         attrs.unindent_doc_comments();
879         // The collapse-docs pass won't combine sugared/raw doc attributes, or included files with
880         // anything else, this will combine them for us.
881         if let Some(doc) = attrs.collapsed_doc_value() {
882             self.collector.set_position(attrs.span.unwrap_or(DUMMY_SP));
883             markdown::find_testable_code(
884                 &doc,
885                 self.collector,
886                 self.codes,
887                 self.collector.enable_per_target_ignores,
888             );
889         }
890
891         nested(self);
892
893         if has_name {
894             self.collector.names.pop();
895         }
896     }
897 }
898
899 impl<'a, 'hir> intravisit::Visitor<'hir> for HirCollector<'a, 'hir> {
900     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'hir> {
901         intravisit::NestedVisitorMap::All(&self.map)
902     }
903
904     fn visit_item(&mut self, item: &'hir hir::Item) {
905         let name = if let hir::ItemKind::Impl(.., ref ty, _) = item.kind {
906             self.map.hir_to_pretty_string(ty.hir_id)
907         } else {
908             item.ident.to_string()
909         };
910
911         self.visit_testable(name, &item.attrs, |this| {
912             intravisit::walk_item(this, item);
913         });
914     }
915
916     fn visit_trait_item(&mut self, item: &'hir hir::TraitItem) {
917         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
918             intravisit::walk_trait_item(this, item);
919         });
920     }
921
922     fn visit_impl_item(&mut self, item: &'hir hir::ImplItem) {
923         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
924             intravisit::walk_impl_item(this, item);
925         });
926     }
927
928     fn visit_foreign_item(&mut self, item: &'hir hir::ForeignItem) {
929         self.visit_testable(item.ident.to_string(), &item.attrs, |this| {
930             intravisit::walk_foreign_item(this, item);
931         });
932     }
933
934     fn visit_variant(
935         &mut self,
936         v: &'hir hir::Variant,
937         g: &'hir hir::Generics,
938         item_id: hir::HirId,
939     ) {
940         self.visit_testable(v.ident.to_string(), &v.attrs, |this| {
941             intravisit::walk_variant(this, v, g, item_id);
942         });
943     }
944
945     fn visit_struct_field(&mut self, f: &'hir hir::StructField) {
946         self.visit_testable(f.ident.to_string(), &f.attrs, |this| {
947             intravisit::walk_struct_field(this, f);
948         });
949     }
950
951     fn visit_macro_def(&mut self, macro_def: &'hir hir::MacroDef) {
952         self.visit_testable(macro_def.name.to_string(), &macro_def.attrs, |_| ());
953     }
954 }
955
956 #[cfg(test)]
957 mod tests;