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