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