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