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