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