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