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