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