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