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