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