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