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