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