1mod extracted;
2mod make;
3mod markdown;
4mod runner;
5mod rust;
6
7use std::fs::File;
8use std::io::{self, Write};
9use std::path::{Path, PathBuf};
10use std::process::{self, Command, Stdio};
11use std::sync::atomic::{AtomicUsize, Ordering};
12use std::sync::{Arc, Mutex};
13use std::{panic, str};
14
15pub(crate) use make::DocTestBuilder;
16pub(crate) use markdown::test as test_markdown;
17use rustc_data_structures::fx::{FxHashMap, FxIndexMap, FxIndexSet};
18use rustc_errors::emitter::HumanReadableErrorType;
19use rustc_errors::{ColorConfig, DiagCtxtHandle};
20use rustc_hir as hir;
21use rustc_hir::CRATE_HIR_ID;
22use rustc_hir::def_id::LOCAL_CRATE;
23use rustc_interface::interface;
24use rustc_session::config::{self, CrateType, ErrorOutputType, Input};
25use rustc_session::lint;
26use rustc_span::FileName;
27use rustc_span::edition::Edition;
28use rustc_span::symbol::sym;
29use rustc_target::spec::{Target, TargetTuple};
30use tempfile::{Builder as TempFileBuilder, TempDir};
31use tracing::debug;
32
33use self::rust::HirCollector;
34use crate::config::{Options as RustdocOptions, OutputFormat};
35use crate::html::markdown::{ErrorCodes, Ignore, LangString, MdRelLine};
36use crate::lint::init_lints;
37
38#[derive(Clone)]
40pub(crate) struct GlobalTestOptions {
41 pub(crate) crate_name: String,
43 pub(crate) no_crate_inject: bool,
45 pub(crate) insert_indent_space: bool,
48 pub(crate) attrs: Vec<String>,
50 pub(crate) args_file: PathBuf,
52}
53
54fn split_args(args: &str) -> Vec<String> {
56 let mut out = Vec::new();
57 let mut iter = args.chars();
58 let mut current = String::new();
59
60 while let Some(c) = iter.next() {
61 if c == '\\' {
62 if let Some(c) = iter.next() {
63 current.push(c);
65 }
66 } else if c == '"' || c == '\'' {
67 while let Some(new_c) = iter.next() {
68 if new_c == c {
69 break;
70 } else if new_c == '\\' {
71 if let Some(c) = iter.next() {
72 current.push(c);
74 }
75 } else {
76 current.push(new_c);
77 }
78 }
79 } else if " \n\t\r".contains(c) {
80 if !current.is_empty() {
81 out.push(current.clone());
82 current.clear();
83 }
84 } else {
85 current.push(c);
86 }
87 }
88 if !current.is_empty() {
89 out.push(current);
90 }
91 out
92}
93
94pub(crate) fn generate_args_file(file_path: &Path, options: &RustdocOptions) -> Result<(), String> {
95 let mut file = File::create(file_path)
96 .map_err(|error| format!("failed to create args file: {error:?}"))?;
97
98 let mut content = vec!["--crate-type=bin".to_string()];
100
101 for cfg in &options.cfgs {
102 content.push(format!("--cfg={cfg}"));
103 }
104 for check_cfg in &options.check_cfgs {
105 content.push(format!("--check-cfg={check_cfg}"));
106 }
107
108 for lib_str in &options.lib_strs {
109 content.push(format!("-L{lib_str}"));
110 }
111 for extern_str in &options.extern_strs {
112 content.push(format!("--extern={extern_str}"));
113 }
114 content.push("-Ccodegen-units=1".to_string());
115 for codegen_options_str in &options.codegen_options_strs {
116 content.push(format!("-C{codegen_options_str}"));
117 }
118 for unstable_option_str in &options.unstable_opts_strs {
119 content.push(format!("-Z{unstable_option_str}"));
120 }
121
122 for compilation_args in &options.doctest_compilation_args {
123 content.extend(split_args(compilation_args));
124 }
125
126 let content = content.join("\n");
127
128 file.write_all(content.as_bytes())
129 .map_err(|error| format!("failed to write arguments to temporary file: {error:?}"))?;
130 Ok(())
131}
132
133fn get_doctest_dir() -> io::Result<TempDir> {
134 TempFileBuilder::new().prefix("rustdoctest").tempdir()
135}
136
137pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions) {
138 let invalid_codeblock_attributes_name = crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name;
139
140 let allowed_lints = vec![
142 invalid_codeblock_attributes_name.to_owned(),
143 lint::builtin::UNKNOWN_LINTS.name.to_owned(),
144 lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_owned(),
145 ];
146
147 let (lint_opts, lint_caps) = init_lints(allowed_lints, options.lint_opts.clone(), |lint| {
148 if lint.name == invalid_codeblock_attributes_name {
149 None
150 } else {
151 Some((lint.name_lower(), lint::Allow))
152 }
153 });
154
155 debug!(?lint_opts);
156
157 let crate_types =
158 if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
159
160 let sessopts = config::Options {
161 maybe_sysroot: options.maybe_sysroot.clone(),
162 search_paths: options.libs.clone(),
163 crate_types,
164 lint_opts,
165 lint_cap: Some(options.lint_cap.unwrap_or(lint::Forbid)),
166 cg: options.codegen_options.clone(),
167 externs: options.externs.clone(),
168 unstable_features: options.unstable_features,
169 actually_rustdoc: true,
170 edition: options.edition,
171 target_triple: options.target.clone(),
172 crate_name: options.crate_name.clone(),
173 remap_path_prefix: options.remap_path_prefix.clone(),
174 ..config::Options::default()
175 };
176
177 let mut cfgs = options.cfgs.clone();
178 cfgs.push("doc".to_owned());
179 cfgs.push("doctest".to_owned());
180 let config = interface::Config {
181 opts: sessopts,
182 crate_cfg: cfgs,
183 crate_check_cfg: options.check_cfgs.clone(),
184 input: input.clone(),
185 output_file: None,
186 output_dir: None,
187 file_loader: None,
188 locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
189 lint_caps,
190 psess_created: None,
191 hash_untracked_state: None,
192 register_lints: Some(Box::new(crate::lint::register_lints)),
193 override_queries: None,
194 make_codegen_backend: None,
195 registry: rustc_driver::diagnostics_registry(),
196 ice_file: None,
197 using_internal_features: &rustc_driver::USING_INTERNAL_FEATURES,
198 expanded_args: options.expanded_args.clone(),
199 };
200
201 let externs = options.externs.clone();
202 let json_unused_externs = options.json_unused_externs;
203
204 let temp_dir = match get_doctest_dir()
205 .map_err(|error| format!("failed to create temporary directory: {error:?}"))
206 {
207 Ok(temp_dir) => temp_dir,
208 Err(error) => return crate::wrap_return(dcx, Err(error)),
209 };
210 let args_path = temp_dir.path().join("rustdoc-cfgs");
211 crate::wrap_return(dcx, generate_args_file(&args_path, &options));
212
213 let extract_doctests = options.output_format == OutputFormat::Doctest;
214 let result = interface::run_compiler(config, |compiler| {
215 let krate = rustc_interface::passes::parse(&compiler.sess);
216
217 let collector = rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
218 let crate_name = tcx.crate_name(LOCAL_CRATE).to_string();
219 let crate_attrs = tcx.hir().attrs(CRATE_HIR_ID);
220 let opts = scrape_test_config(crate_name, crate_attrs, args_path);
221 let enable_per_target_ignores = options.enable_per_target_ignores;
222
223 let hir_collector = HirCollector::new(
224 ErrorCodes::from(compiler.sess.opts.unstable_features.is_nightly_build()),
225 enable_per_target_ignores,
226 tcx,
227 );
228 let tests = hir_collector.collect_crate();
229 if extract_doctests {
230 let mut collector = extracted::ExtractedDocTests::new();
231 tests.into_iter().for_each(|t| collector.add_test(t, &opts, &options));
232
233 let stdout = std::io::stdout();
234 let mut stdout = stdout.lock();
235 if let Err(error) = serde_json::ser::to_writer(&mut stdout, &collector) {
236 eprintln!();
237 Err(format!("Failed to generate JSON output for doctests: {error:?}"))
238 } else {
239 Ok(None)
240 }
241 } else {
242 let mut collector = CreateRunnableDocTests::new(options, opts);
243 tests.into_iter().for_each(|t| collector.add_test(t));
244
245 Ok(Some(collector))
246 }
247 });
248 compiler.sess.dcx().abort_if_errors();
249
250 collector
251 });
252
253 let CreateRunnableDocTests {
254 standalone_tests,
255 mergeable_tests,
256 rustdoc_options,
257 opts,
258 unused_extern_reports,
259 compiling_test_count,
260 ..
261 } = match result {
262 Ok(Some(collector)) => collector,
263 Ok(None) => return,
264 Err(error) => {
265 eprintln!("{error}");
266 std::process::exit(1);
267 }
268 };
269
270 run_tests(opts, &rustdoc_options, &unused_extern_reports, standalone_tests, mergeable_tests);
271
272 let compiling_test_count = compiling_test_count.load(Ordering::SeqCst);
273
274 if json_unused_externs.is_enabled() {
277 let unused_extern_reports: Vec<_> =
278 std::mem::take(&mut unused_extern_reports.lock().unwrap());
279 if unused_extern_reports.len() == compiling_test_count {
280 let extern_names =
281 externs.iter().map(|(name, _)| name).collect::<FxIndexSet<&String>>();
282 let mut unused_extern_names = unused_extern_reports
283 .iter()
284 .map(|uexts| uexts.unused_extern_names.iter().collect::<FxIndexSet<&String>>())
285 .fold(extern_names, |uextsa, uextsb| {
286 uextsa.intersection(&uextsb).copied().collect::<FxIndexSet<&String>>()
287 })
288 .iter()
289 .map(|v| (*v).clone())
290 .collect::<Vec<String>>();
291 unused_extern_names.sort();
292 let lint_level = unused_extern_reports
294 .iter()
295 .map(|uexts| uexts.lint_level.as_str())
296 .max_by_key(|v| match *v {
297 "warn" => 1,
298 "deny" => 2,
299 "forbid" => 3,
300 v => unreachable!("Invalid lint level '{v}'"),
304 })
305 .unwrap_or("warn")
306 .to_string();
307 let uext = UnusedExterns { lint_level, unused_extern_names };
308 let unused_extern_json = serde_json::to_string(&uext).unwrap();
309 eprintln!("{unused_extern_json}");
310 }
311 }
312}
313
314pub(crate) fn run_tests(
315 opts: GlobalTestOptions,
316 rustdoc_options: &Arc<RustdocOptions>,
317 unused_extern_reports: &Arc<Mutex<Vec<UnusedExterns>>>,
318 mut standalone_tests: Vec<test::TestDescAndFn>,
319 mergeable_tests: FxIndexMap<Edition, Vec<(DocTestBuilder, ScrapedDocTest)>>,
320) {
321 let mut test_args = Vec::with_capacity(rustdoc_options.test_args.len() + 1);
322 test_args.insert(0, "rustdoctest".to_string());
323 test_args.extend_from_slice(&rustdoc_options.test_args);
324 if rustdoc_options.nocapture {
325 test_args.push("--nocapture".to_string());
326 }
327
328 let mut nb_errors = 0;
329 let mut ran_edition_tests = 0;
330 let target_str = rustdoc_options.target.to_string();
331
332 for (edition, mut doctests) in mergeable_tests {
333 if doctests.is_empty() {
334 continue;
335 }
336 doctests.sort_by(|(_, a), (_, b)| a.name.cmp(&b.name));
337
338 let mut tests_runner = runner::DocTestRunner::new();
339
340 let rustdoc_test_options = IndividualTestOptions::new(
341 rustdoc_options,
342 &Some(format!("merged_doctest_{edition}")),
343 PathBuf::from(format!("doctest_{edition}.rs")),
344 );
345
346 for (doctest, scraped_test) in &doctests {
347 tests_runner.add_test(doctest, scraped_test, &target_str);
348 }
349 if let Ok(success) = tests_runner.run_merged_tests(
350 rustdoc_test_options,
351 edition,
352 &opts,
353 &test_args,
354 rustdoc_options,
355 ) {
356 ran_edition_tests += 1;
357 if !success {
358 nb_errors += 1;
359 }
360 continue;
361 }
362 debug!("Failed to compile compatible doctests for edition {} all at once", edition);
365 for (doctest, scraped_test) in doctests {
366 doctest.generate_unique_doctest(
367 &scraped_test.text,
368 scraped_test.langstr.test_harness,
369 &opts,
370 Some(&opts.crate_name),
371 );
372 standalone_tests.push(generate_test_desc_and_fn(
373 doctest,
374 scraped_test,
375 opts.clone(),
376 Arc::clone(rustdoc_options),
377 unused_extern_reports.clone(),
378 ));
379 }
380 }
381
382 if ran_edition_tests == 0 || !standalone_tests.is_empty() {
385 standalone_tests.sort_by(|a, b| a.desc.name.as_slice().cmp(b.desc.name.as_slice()));
386 test::test_main(&test_args, standalone_tests, None);
387 }
388 if nb_errors != 0 {
389 std::process::exit(101);
391 }
392}
393
394fn scrape_test_config(
396 crate_name: String,
397 attrs: &[hir::Attribute],
398 args_file: PathBuf,
399) -> GlobalTestOptions {
400 use rustc_ast_pretty::pprust;
401
402 let mut opts = GlobalTestOptions {
403 crate_name,
404 no_crate_inject: false,
405 attrs: Vec::new(),
406 insert_indent_space: false,
407 args_file,
408 };
409
410 let test_attrs: Vec<_> = attrs
411 .iter()
412 .filter(|a| a.has_name(sym::doc))
413 .flat_map(|a| a.meta_item_list().unwrap_or_default())
414 .filter(|a| a.has_name(sym::test))
415 .collect();
416 let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
417
418 for attr in attrs {
419 if attr.has_name(sym::no_crate_inject) {
420 opts.no_crate_inject = true;
421 }
422 if attr.has_name(sym::attr)
423 && let Some(l) = attr.meta_item_list()
424 {
425 for item in l {
426 opts.attrs.push(pprust::meta_list_item_to_string(item));
427 }
428 }
429 }
430
431 opts
432}
433
434enum TestFailure {
436 CompileError,
438 UnexpectedCompilePass,
440 MissingErrorCodes(Vec<String>),
443 ExecutionError(io::Error),
445 ExecutionFailure(process::Output),
449 UnexpectedRunPass,
451}
452
453enum DirState {
454 Temp(tempfile::TempDir),
455 Perm(PathBuf),
456}
457
458impl DirState {
459 fn path(&self) -> &std::path::Path {
460 match self {
461 DirState::Temp(t) => t.path(),
462 DirState::Perm(p) => p.as_path(),
463 }
464 }
465}
466
467#[derive(serde::Serialize, serde::Deserialize)]
472pub(crate) struct UnusedExterns {
473 lint_level: String,
475 unused_extern_names: Vec<String>,
477}
478
479fn add_exe_suffix(input: String, target: &TargetTuple) -> String {
480 let exe_suffix = match target {
481 TargetTuple::TargetTuple(_) => Target::expect_builtin(target).options.exe_suffix,
482 TargetTuple::TargetJson { contents, .. } => {
483 Target::from_json(contents.parse().unwrap()).unwrap().0.options.exe_suffix
484 }
485 };
486 input + &exe_suffix
487}
488
489fn wrapped_rustc_command(rustc_wrappers: &[PathBuf], rustc_binary: &Path) -> Command {
490 let mut args = rustc_wrappers.iter().map(PathBuf::as_path).chain([rustc_binary]);
491
492 let exe = args.next().expect("unable to create rustc command");
493 let mut command = Command::new(exe);
494 for arg in args {
495 command.arg(arg);
496 }
497
498 command
499}
500
501pub(crate) struct RunnableDocTest {
508 full_test_code: String,
509 full_test_line_offset: usize,
510 test_opts: IndividualTestOptions,
511 global_opts: GlobalTestOptions,
512 langstr: LangString,
513 line: usize,
514 edition: Edition,
515 no_run: bool,
516 is_multiple_tests: bool,
517}
518
519impl RunnableDocTest {
520 fn path_for_merged_doctest(&self) -> PathBuf {
521 self.test_opts.outdir.path().join(format!("doctest_{}.rs", self.edition))
522 }
523}
524
525fn run_test(
530 doctest: RunnableDocTest,
531 rustdoc_options: &RustdocOptions,
532 supports_color: bool,
533 report_unused_externs: impl Fn(UnusedExterns),
534) -> Result<(), TestFailure> {
535 let langstr = &doctest.langstr;
536 let rust_out = add_exe_suffix("rust_out".to_owned(), &rustdoc_options.target);
538 let output_file = doctest.test_opts.outdir.path().join(rust_out);
539
540 let rustc_binary = rustdoc_options
541 .test_builder
542 .as_deref()
543 .unwrap_or_else(|| rustc_interface::util::rustc_path().expect("found rustc"));
544 let mut compiler = wrapped_rustc_command(&rustdoc_options.test_builder_wrappers, rustc_binary);
545
546 compiler.arg(format!("@{}", doctest.global_opts.args_file.display()));
547
548 if let Some(sysroot) = &rustdoc_options.maybe_sysroot {
549 compiler.arg(format!("--sysroot={}", sysroot.display()));
550 }
551
552 compiler.arg("--edition").arg(doctest.edition.to_string());
553 if !doctest.is_multiple_tests {
554 compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", &doctest.test_opts.path);
556 compiler.env(
557 "UNSTABLE_RUSTDOC_TEST_LINE",
558 format!("{}", doctest.line as isize - doctest.full_test_line_offset as isize),
559 );
560 }
561 compiler.arg("-o").arg(&output_file);
562 if langstr.test_harness {
563 compiler.arg("--test");
564 }
565 if rustdoc_options.json_unused_externs.is_enabled() && !langstr.compile_fail {
566 compiler.arg("--error-format=json");
567 compiler.arg("--json").arg("unused-externs");
568 compiler.arg("-W").arg("unused_crate_dependencies");
569 compiler.arg("-Z").arg("unstable-options");
570 }
571
572 if doctest.no_run && !langstr.compile_fail && rustdoc_options.persist_doctests.is_none() {
573 compiler.arg("--emit=metadata");
576 }
577 compiler.arg("--target").arg(match &rustdoc_options.target {
578 TargetTuple::TargetTuple(s) => s,
579 TargetTuple::TargetJson { path_for_rustdoc, .. } => {
580 path_for_rustdoc.to_str().expect("target path must be valid unicode")
581 }
582 });
583 if let ErrorOutputType::HumanReadable(kind, color_config) = rustdoc_options.error_format {
584 let short = kind.short();
585 let unicode = kind == HumanReadableErrorType::Unicode;
586
587 if short {
588 compiler.arg("--error-format").arg("short");
589 }
590 if unicode {
591 compiler.arg("--error-format").arg("human-unicode");
592 }
593
594 match color_config {
595 ColorConfig::Never => {
596 compiler.arg("--color").arg("never");
597 }
598 ColorConfig::Always => {
599 compiler.arg("--color").arg("always");
600 }
601 ColorConfig::Auto => {
602 compiler.arg("--color").arg(if supports_color { "always" } else { "never" });
603 }
604 }
605 }
606
607 if doctest.is_multiple_tests {
610 compiler.arg("--error-format=short");
612 let input_file = doctest.path_for_merged_doctest();
613 if std::fs::write(&input_file, &doctest.full_test_code).is_err() {
614 return Err(TestFailure::CompileError);
617 }
618 compiler.arg(input_file);
619 if !rustdoc_options.nocapture {
620 compiler.stderr(Stdio::null());
623 }
624 } else {
625 compiler.arg("-");
626 compiler.stdin(Stdio::piped());
627 compiler.stderr(Stdio::piped());
628 }
629
630 debug!("compiler invocation for doctest: {compiler:?}");
631
632 let mut child = compiler.spawn().expect("Failed to spawn rustc process");
633 let output = if doctest.is_multiple_tests {
634 let status = child.wait().expect("Failed to wait");
635 process::Output { status, stdout: Vec::new(), stderr: Vec::new() }
636 } else {
637 let stdin = child.stdin.as_mut().expect("Failed to open stdin");
638 stdin.write_all(doctest.full_test_code.as_bytes()).expect("could write out test sources");
639 child.wait_with_output().expect("Failed to read stdout")
640 };
641
642 struct Bomb<'a>(&'a str);
643 impl Drop for Bomb<'_> {
644 fn drop(&mut self) {
645 eprint!("{}", self.0);
646 }
647 }
648 let mut out = str::from_utf8(&output.stderr)
649 .unwrap()
650 .lines()
651 .filter(|l| {
652 if let Ok(uext) = serde_json::from_str::<UnusedExterns>(l) {
653 report_unused_externs(uext);
654 false
655 } else {
656 true
657 }
658 })
659 .intersperse_with(|| "\n")
660 .collect::<String>();
661
662 if !out.is_empty() {
665 out.push('\n');
666 }
667
668 let _bomb = Bomb(&out);
669 match (output.status.success(), langstr.compile_fail) {
670 (true, true) => {
671 return Err(TestFailure::UnexpectedCompilePass);
672 }
673 (true, false) => {}
674 (false, true) => {
675 if !langstr.error_codes.is_empty() {
676 let missing_codes: Vec<String> = langstr
680 .error_codes
681 .iter()
682 .filter(|err| !out.contains(&format!("error[{err}]")))
683 .cloned()
684 .collect();
685
686 if !missing_codes.is_empty() {
687 return Err(TestFailure::MissingErrorCodes(missing_codes));
688 }
689 }
690 }
691 (false, false) => {
692 return Err(TestFailure::CompileError);
693 }
694 }
695
696 if doctest.no_run {
697 return Ok(());
698 }
699
700 let mut cmd;
702
703 let output_file = make_maybe_absolute_path(output_file);
704 if let Some(tool) = &rustdoc_options.runtool {
705 let tool = make_maybe_absolute_path(tool.into());
706 cmd = Command::new(tool);
707 cmd.args(&rustdoc_options.runtool_args);
708 cmd.arg(&output_file);
709 } else {
710 cmd = Command::new(&output_file);
711 if doctest.is_multiple_tests {
712 cmd.env("RUSTDOC_DOCTEST_BIN_PATH", &output_file);
713 }
714 }
715 if let Some(run_directory) = &rustdoc_options.test_run_directory {
716 cmd.current_dir(run_directory);
717 }
718
719 let result = if doctest.is_multiple_tests || rustdoc_options.nocapture {
720 cmd.status().map(|status| process::Output {
721 status,
722 stdout: Vec::new(),
723 stderr: Vec::new(),
724 })
725 } else {
726 cmd.output()
727 };
728 match result {
729 Err(e) => return Err(TestFailure::ExecutionError(e)),
730 Ok(out) => {
731 if langstr.should_panic && out.status.success() {
732 return Err(TestFailure::UnexpectedRunPass);
733 } else if !langstr.should_panic && !out.status.success() {
734 return Err(TestFailure::ExecutionFailure(out));
735 }
736 }
737 }
738
739 Ok(())
740}
741
742fn make_maybe_absolute_path(path: PathBuf) -> PathBuf {
748 if path.components().count() == 1 {
749 path
751 } else {
752 std::env::current_dir().map(|c| c.join(&path)).unwrap_or_else(|_| path)
753 }
754}
755struct IndividualTestOptions {
756 outdir: DirState,
757 path: PathBuf,
758}
759
760impl IndividualTestOptions {
761 fn new(options: &RustdocOptions, test_id: &Option<String>, test_path: PathBuf) -> Self {
762 let outdir = if let Some(ref path) = options.persist_doctests {
763 let mut path = path.clone();
764 path.push(test_id.as_deref().unwrap_or("<doctest>"));
765
766 if let Err(err) = std::fs::create_dir_all(&path) {
767 eprintln!("Couldn't create directory for doctest executables: {err}");
768 panic::resume_unwind(Box::new(()));
769 }
770
771 DirState::Perm(path)
772 } else {
773 DirState::Temp(get_doctest_dir().expect("rustdoc needs a tempdir"))
774 };
775
776 Self { outdir, path: test_path }
777 }
778}
779
780#[derive(Debug)]
790pub(crate) struct ScrapedDocTest {
791 filename: FileName,
792 line: usize,
793 langstr: LangString,
794 text: String,
795 name: String,
796}
797
798impl ScrapedDocTest {
799 fn new(
800 filename: FileName,
801 line: usize,
802 logical_path: Vec<String>,
803 langstr: LangString,
804 text: String,
805 ) -> Self {
806 let mut item_path = logical_path.join("::");
807 item_path.retain(|c| c != ' ');
808 if !item_path.is_empty() {
809 item_path.push(' ');
810 }
811 let name =
812 format!("{} - {item_path}(line {line})", filename.prefer_remapped_unconditionaly());
813
814 Self { filename, line, langstr, text, name }
815 }
816 fn edition(&self, opts: &RustdocOptions) -> Edition {
817 self.langstr.edition.unwrap_or(opts.edition)
818 }
819
820 fn no_run(&self, opts: &RustdocOptions) -> bool {
821 self.langstr.no_run || opts.no_run
822 }
823 fn path(&self) -> PathBuf {
824 match &self.filename {
825 FileName::Real(path) => {
826 if let Some(local_path) = path.local_path() {
827 local_path.to_path_buf()
828 } else {
829 unreachable!("doctest from a different crate");
831 }
832 }
833 _ => PathBuf::from(r"doctest.rs"),
834 }
835 }
836}
837
838pub(crate) trait DocTestVisitor {
839 fn visit_test(&mut self, test: String, config: LangString, rel_line: MdRelLine);
840 fn visit_header(&mut self, _name: &str, _level: u32) {}
841}
842
843struct CreateRunnableDocTests {
844 standalone_tests: Vec<test::TestDescAndFn>,
845 mergeable_tests: FxIndexMap<Edition, Vec<(DocTestBuilder, ScrapedDocTest)>>,
846
847 rustdoc_options: Arc<RustdocOptions>,
848 opts: GlobalTestOptions,
849 visited_tests: FxHashMap<(String, usize), usize>,
850 unused_extern_reports: Arc<Mutex<Vec<UnusedExterns>>>,
851 compiling_test_count: AtomicUsize,
852 can_merge_doctests: bool,
853}
854
855impl CreateRunnableDocTests {
856 fn new(rustdoc_options: RustdocOptions, opts: GlobalTestOptions) -> CreateRunnableDocTests {
857 let can_merge_doctests = rustdoc_options.edition >= Edition::Edition2024;
858 CreateRunnableDocTests {
859 standalone_tests: Vec::new(),
860 mergeable_tests: FxIndexMap::default(),
861 rustdoc_options: Arc::new(rustdoc_options),
862 opts,
863 visited_tests: FxHashMap::default(),
864 unused_extern_reports: Default::default(),
865 compiling_test_count: AtomicUsize::new(0),
866 can_merge_doctests,
867 }
868 }
869
870 fn add_test(&mut self, scraped_test: ScrapedDocTest) {
871 let file = scraped_test
873 .filename
874 .prefer_local()
875 .to_string_lossy()
876 .chars()
877 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
878 .collect::<String>();
879 let test_id = format!(
880 "{file}_{line}_{number}",
881 file = file,
882 line = scraped_test.line,
883 number = {
884 self.visited_tests
887 .entry((file.clone(), scraped_test.line))
888 .and_modify(|v| *v += 1)
889 .or_insert(0)
890 },
891 );
892
893 let edition = scraped_test.edition(&self.rustdoc_options);
894 let doctest = DocTestBuilder::new(
895 &scraped_test.text,
896 Some(&self.opts.crate_name),
897 edition,
898 self.can_merge_doctests,
899 Some(test_id),
900 Some(&scraped_test.langstr),
901 );
902 let is_standalone = !doctest.can_be_merged
903 || scraped_test.langstr.compile_fail
904 || scraped_test.langstr.test_harness
905 || scraped_test.langstr.standalone_crate
906 || self.rustdoc_options.nocapture
907 || self.rustdoc_options.test_args.iter().any(|arg| arg == "--show-output");
908 if is_standalone {
909 let test_desc = self.generate_test_desc_and_fn(doctest, scraped_test);
910 self.standalone_tests.push(test_desc);
911 } else {
912 self.mergeable_tests.entry(edition).or_default().push((doctest, scraped_test));
913 }
914 }
915
916 fn generate_test_desc_and_fn(
917 &mut self,
918 test: DocTestBuilder,
919 scraped_test: ScrapedDocTest,
920 ) -> test::TestDescAndFn {
921 if !scraped_test.langstr.compile_fail {
922 self.compiling_test_count.fetch_add(1, Ordering::SeqCst);
923 }
924
925 generate_test_desc_and_fn(
926 test,
927 scraped_test,
928 self.opts.clone(),
929 Arc::clone(&self.rustdoc_options),
930 self.unused_extern_reports.clone(),
931 )
932 }
933}
934
935fn generate_test_desc_and_fn(
936 test: DocTestBuilder,
937 scraped_test: ScrapedDocTest,
938 opts: GlobalTestOptions,
939 rustdoc_options: Arc<RustdocOptions>,
940 unused_externs: Arc<Mutex<Vec<UnusedExterns>>>,
941) -> test::TestDescAndFn {
942 let target_str = rustdoc_options.target.to_string();
943 let rustdoc_test_options =
944 IndividualTestOptions::new(&rustdoc_options, &test.test_id, scraped_test.path());
945
946 debug!("creating test {}: {}", scraped_test.name, scraped_test.text);
947 test::TestDescAndFn {
948 desc: test::TestDesc {
949 name: test::DynTestName(scraped_test.name.clone()),
950 ignore: match scraped_test.langstr.ignore {
951 Ignore::All => true,
952 Ignore::None => false,
953 Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
954 },
955 ignore_message: None,
956 source_file: "",
957 start_line: 0,
958 start_col: 0,
959 end_line: 0,
960 end_col: 0,
961 should_panic: test::ShouldPanic::No,
963 compile_fail: scraped_test.langstr.compile_fail,
964 no_run: scraped_test.no_run(&rustdoc_options),
965 test_type: test::TestType::DocTest,
966 },
967 testfn: test::DynTestFn(Box::new(move || {
968 doctest_run_fn(
969 rustdoc_test_options,
970 opts,
971 test,
972 scraped_test,
973 rustdoc_options,
974 unused_externs,
975 )
976 })),
977 }
978}
979
980fn doctest_run_fn(
981 test_opts: IndividualTestOptions,
982 global_opts: GlobalTestOptions,
983 doctest: DocTestBuilder,
984 scraped_test: ScrapedDocTest,
985 rustdoc_options: Arc<RustdocOptions>,
986 unused_externs: Arc<Mutex<Vec<UnusedExterns>>>,
987) -> Result<(), String> {
988 let report_unused_externs = |uext| {
989 unused_externs.lock().unwrap().push(uext);
990 };
991 let (full_test_code, full_test_line_offset) = doctest.generate_unique_doctest(
992 &scraped_test.text,
993 scraped_test.langstr.test_harness,
994 &global_opts,
995 Some(&global_opts.crate_name),
996 );
997 let runnable_test = RunnableDocTest {
998 full_test_code,
999 full_test_line_offset,
1000 test_opts,
1001 global_opts,
1002 langstr: scraped_test.langstr.clone(),
1003 line: scraped_test.line,
1004 edition: scraped_test.edition(&rustdoc_options),
1005 no_run: scraped_test.no_run(&rustdoc_options),
1006 is_multiple_tests: false,
1007 };
1008 let res =
1009 run_test(runnable_test, &rustdoc_options, doctest.supports_color, report_unused_externs);
1010
1011 if let Err(err) = res {
1012 match err {
1013 TestFailure::CompileError => {
1014 eprint!("Couldn't compile the test.");
1015 }
1016 TestFailure::UnexpectedCompilePass => {
1017 eprint!("Test compiled successfully, but it's marked `compile_fail`.");
1018 }
1019 TestFailure::UnexpectedRunPass => {
1020 eprint!("Test executable succeeded, but it's marked `should_panic`.");
1021 }
1022 TestFailure::MissingErrorCodes(codes) => {
1023 eprint!("Some expected error codes were not found: {codes:?}");
1024 }
1025 TestFailure::ExecutionError(err) => {
1026 eprint!("Couldn't run the test: {err}");
1027 if err.kind() == io::ErrorKind::PermissionDenied {
1028 eprint!(" - maybe your tempdir is mounted with noexec?");
1029 }
1030 }
1031 TestFailure::ExecutionFailure(out) => {
1032 eprintln!("Test executable failed ({reason}).", reason = out.status);
1033
1034 let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
1044 let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
1045
1046 if !stdout.is_empty() || !stderr.is_empty() {
1047 eprintln!();
1048
1049 if !stdout.is_empty() {
1050 eprintln!("stdout:\n{stdout}");
1051 }
1052
1053 if !stderr.is_empty() {
1054 eprintln!("stderr:\n{stderr}");
1055 }
1056 }
1057 }
1058 }
1059
1060 panic::resume_unwind(Box::new(()));
1061 }
1062 Ok(())
1063}
1064
1065#[cfg(test)] impl DocTestVisitor for Vec<usize> {
1067 fn visit_test(&mut self, _test: String, _config: LangString, rel_line: MdRelLine) {
1068 self.push(1 + rel_line.offset());
1069 }
1070}
1071
1072#[cfg(test)]
1073mod tests;