rustdoc/
doctest.rs

1mod extracted;
2mod make;
3mod markdown;
4mod runner;
5mod rust;
6
7use std::fs::File;
8use std::hash::{Hash, Hasher};
9use std::io::{self, Write};
10use std::path::{Path, PathBuf};
11use std::process::{self, Command, Stdio};
12use std::sync::atomic::{AtomicUsize, Ordering};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15use std::{panic, str};
16
17pub(crate) use make::{BuildDocTestBuilder, DocTestBuilder};
18pub(crate) use markdown::test as test_markdown;
19use rustc_data_structures::fx::{FxHashMap, FxHashSet, FxHasher, FxIndexMap, FxIndexSet};
20use rustc_errors::emitter::HumanReadableErrorType;
21use rustc_errors::{ColorConfig, DiagCtxtHandle};
22use rustc_hir as hir;
23use rustc_hir::CRATE_HIR_ID;
24use rustc_hir::def_id::LOCAL_CRATE;
25use rustc_interface::interface;
26use rustc_session::config::{self, CrateType, ErrorOutputType, Input};
27use rustc_session::lint;
28use rustc_span::edition::Edition;
29use rustc_span::symbol::sym;
30use rustc_span::{FileName, Span};
31use rustc_target::spec::{Target, TargetTuple};
32use tempfile::{Builder as TempFileBuilder, TempDir};
33use tracing::debug;
34
35use self::rust::HirCollector;
36use crate::config::{Options as RustdocOptions, OutputFormat};
37use crate::html::markdown::{ErrorCodes, Ignore, LangString, MdRelLine};
38use crate::lint::init_lints;
39
40/// Type used to display times (compilation and total) information for merged doctests.
41struct MergedDoctestTimes {
42    total_time: Instant,
43    /// Total time spent compiling all merged doctests.
44    compilation_time: Duration,
45    /// This field is used to keep track of how many merged doctests we (tried to) compile.
46    added_compilation_times: usize,
47}
48
49impl MergedDoctestTimes {
50    fn new() -> Self {
51        Self {
52            total_time: Instant::now(),
53            compilation_time: Duration::default(),
54            added_compilation_times: 0,
55        }
56    }
57
58    fn add_compilation_time(&mut self, duration: Duration) {
59        self.compilation_time += duration;
60        self.added_compilation_times += 1;
61    }
62
63    /// Returns `(total_time, compilation_time)`.
64    fn times_in_secs(&self) -> Option<(f64, f64)> {
65        // If no merged doctest was compiled, then there is nothing to display since the numbers
66        // displayed by `libtest` for standalone tests are already accurate (they include both
67        // compilation and runtime).
68        if self.added_compilation_times == 0 {
69            return None;
70        }
71        Some((self.total_time.elapsed().as_secs_f64(), self.compilation_time.as_secs_f64()))
72    }
73}
74
75/// Options that apply to all doctests in a crate or Markdown file (for `rustdoc foo.md`).
76#[derive(Clone)]
77pub(crate) struct GlobalTestOptions {
78    /// Name of the crate (for regular `rustdoc`) or Markdown file (for `rustdoc foo.md`).
79    pub(crate) crate_name: String,
80    /// Whether to disable the default `extern crate my_crate;` when creating doctests.
81    pub(crate) no_crate_inject: bool,
82    /// Whether inserting extra indent spaces in code block,
83    /// default is `false`, only `true` for generating code link of Rust playground
84    pub(crate) insert_indent_space: bool,
85    /// Path to file containing arguments for the invocation of rustc.
86    pub(crate) args_file: PathBuf,
87}
88
89pub(crate) fn generate_args_file(file_path: &Path, options: &RustdocOptions) -> Result<(), String> {
90    let mut file = File::create(file_path)
91        .map_err(|error| format!("failed to create args file: {error:?}"))?;
92
93    // We now put the common arguments into the file we created.
94    let mut content = vec![];
95
96    for cfg in &options.cfgs {
97        content.push(format!("--cfg={cfg}"));
98    }
99    for check_cfg in &options.check_cfgs {
100        content.push(format!("--check-cfg={check_cfg}"));
101    }
102
103    for lib_str in &options.lib_strs {
104        content.push(format!("-L{lib_str}"));
105    }
106    for extern_str in &options.extern_strs {
107        content.push(format!("--extern={extern_str}"));
108    }
109    content.push("-Ccodegen-units=1".to_string());
110    for codegen_options_str in &options.codegen_options_strs {
111        content.push(format!("-C{codegen_options_str}"));
112    }
113    for unstable_option_str in &options.unstable_opts_strs {
114        content.push(format!("-Z{unstable_option_str}"));
115    }
116
117    content.extend(options.doctest_build_args.clone());
118
119    let content = content.join("\n");
120
121    file.write_all(content.as_bytes())
122        .map_err(|error| format!("failed to write arguments to temporary file: {error:?}"))?;
123    Ok(())
124}
125
126fn get_doctest_dir() -> io::Result<TempDir> {
127    TempFileBuilder::new().prefix("rustdoctest").tempdir()
128}
129
130pub(crate) fn run(dcx: DiagCtxtHandle<'_>, input: Input, options: RustdocOptions) {
131    let invalid_codeblock_attributes_name = crate::lint::INVALID_CODEBLOCK_ATTRIBUTES.name;
132
133    // See core::create_config for what's going on here.
134    let allowed_lints = vec![
135        invalid_codeblock_attributes_name.to_owned(),
136        lint::builtin::UNKNOWN_LINTS.name.to_owned(),
137        lint::builtin::RENAMED_AND_REMOVED_LINTS.name.to_owned(),
138    ];
139
140    let (lint_opts, lint_caps) = init_lints(allowed_lints, options.lint_opts.clone(), |lint| {
141        if lint.name == invalid_codeblock_attributes_name {
142            None
143        } else {
144            Some((lint.name_lower(), lint::Allow))
145        }
146    });
147
148    debug!(?lint_opts);
149
150    let crate_types =
151        if options.proc_macro_crate { vec![CrateType::ProcMacro] } else { vec![CrateType::Rlib] };
152
153    let sessopts = config::Options {
154        sysroot: options.sysroot.clone(),
155        search_paths: options.libs.clone(),
156        crate_types,
157        lint_opts,
158        lint_cap: Some(options.lint_cap.unwrap_or(lint::Forbid)),
159        cg: options.codegen_options.clone(),
160        externs: options.externs.clone(),
161        unstable_features: options.unstable_features,
162        actually_rustdoc: true,
163        edition: options.edition,
164        target_triple: options.target.clone(),
165        crate_name: options.crate_name.clone(),
166        remap_path_prefix: options.remap_path_prefix.clone(),
167        unstable_opts: options.unstable_opts.clone(),
168        error_format: options.error_format.clone(),
169        target_modifiers: options.target_modifiers.clone(),
170        ..config::Options::default()
171    };
172
173    let mut cfgs = options.cfgs.clone();
174    cfgs.push("doc".to_owned());
175    cfgs.push("doctest".to_owned());
176    let config = interface::Config {
177        opts: sessopts,
178        crate_cfg: cfgs,
179        crate_check_cfg: options.check_cfgs.clone(),
180        input: input.clone(),
181        output_file: None,
182        output_dir: None,
183        file_loader: None,
184        locale_resources: rustc_driver::DEFAULT_LOCALE_RESOURCES.to_vec(),
185        lint_caps,
186        psess_created: None,
187        hash_untracked_state: None,
188        register_lints: Some(Box::new(crate::lint::register_lints)),
189        override_queries: None,
190        extra_symbols: Vec::new(),
191        make_codegen_backend: None,
192        registry: rustc_driver::diagnostics_registry(),
193        ice_file: None,
194        using_internal_features: &rustc_driver::USING_INTERNAL_FEATURES,
195    };
196
197    let externs = options.externs.clone();
198    let json_unused_externs = options.json_unused_externs;
199
200    let temp_dir = match get_doctest_dir()
201        .map_err(|error| format!("failed to create temporary directory: {error:?}"))
202    {
203        Ok(temp_dir) => temp_dir,
204        Err(error) => return crate::wrap_return(dcx, Err(error)),
205    };
206    let args_path = temp_dir.path().join("rustdoc-cfgs");
207    crate::wrap_return(dcx, generate_args_file(&args_path, &options));
208
209    let extract_doctests = options.output_format == OutputFormat::Doctest;
210    let result = interface::run_compiler(config, |compiler| {
211        let krate = rustc_interface::passes::parse(&compiler.sess);
212
213        let collector = rustc_interface::create_and_enter_global_ctxt(compiler, krate, |tcx| {
214            let crate_name = tcx.crate_name(LOCAL_CRATE).to_string();
215            let crate_attrs = tcx.hir_attrs(CRATE_HIR_ID);
216            let opts = scrape_test_config(crate_name, crate_attrs, args_path);
217
218            let hir_collector = HirCollector::new(
219                ErrorCodes::from(compiler.sess.opts.unstable_features.is_nightly_build()),
220                tcx,
221            );
222            let tests = hir_collector.collect_crate();
223            if extract_doctests {
224                let mut collector = extracted::ExtractedDocTests::new();
225                tests.into_iter().for_each(|t| collector.add_test(t, &opts, &options));
226
227                let stdout = std::io::stdout();
228                let mut stdout = stdout.lock();
229                if let Err(error) = serde_json::ser::to_writer(&mut stdout, &collector) {
230                    eprintln!();
231                    Err(format!("Failed to generate JSON output for doctests: {error:?}"))
232                } else {
233                    Ok(None)
234                }
235            } else {
236                let mut collector = CreateRunnableDocTests::new(options, opts);
237                tests.into_iter().for_each(|t| collector.add_test(t, Some(compiler.sess.dcx())));
238
239                Ok(Some(collector))
240            }
241        });
242        compiler.sess.dcx().abort_if_errors();
243
244        collector
245    });
246
247    let CreateRunnableDocTests {
248        standalone_tests,
249        mergeable_tests,
250        rustdoc_options,
251        opts,
252        unused_extern_reports,
253        compiling_test_count,
254        ..
255    } = match result {
256        Ok(Some(collector)) => collector,
257        Ok(None) => return,
258        Err(error) => {
259            eprintln!("{error}");
260            // Since some files in the temporary folder are still owned and alive, we need
261            // to manually remove the folder.
262            let _ = std::fs::remove_dir_all(temp_dir.path());
263            std::process::exit(1);
264        }
265    };
266
267    run_tests(
268        opts,
269        &rustdoc_options,
270        &unused_extern_reports,
271        standalone_tests,
272        mergeable_tests,
273        Some(temp_dir),
274    );
275
276    let compiling_test_count = compiling_test_count.load(Ordering::SeqCst);
277
278    // Collect and warn about unused externs, but only if we've gotten
279    // reports for each doctest
280    if json_unused_externs.is_enabled() {
281        let unused_extern_reports: Vec<_> =
282            std::mem::take(&mut unused_extern_reports.lock().unwrap());
283        if unused_extern_reports.len() == compiling_test_count {
284            let extern_names =
285                externs.iter().map(|(name, _)| name).collect::<FxIndexSet<&String>>();
286            let mut unused_extern_names = unused_extern_reports
287                .iter()
288                .map(|uexts| uexts.unused_extern_names.iter().collect::<FxIndexSet<&String>>())
289                .fold(extern_names, |uextsa, uextsb| {
290                    uextsa.intersection(&uextsb).copied().collect::<FxIndexSet<&String>>()
291                })
292                .iter()
293                .map(|v| (*v).clone())
294                .collect::<Vec<String>>();
295            unused_extern_names.sort();
296            // Take the most severe lint level
297            let lint_level = unused_extern_reports
298                .iter()
299                .map(|uexts| uexts.lint_level.as_str())
300                .max_by_key(|v| match *v {
301                    "warn" => 1,
302                    "deny" => 2,
303                    "forbid" => 3,
304                    // The allow lint level is not expected,
305                    // as if allow is specified, no message
306                    // is to be emitted.
307                    v => unreachable!("Invalid lint level '{v}'"),
308                })
309                .unwrap_or("warn")
310                .to_string();
311            let uext = UnusedExterns { lint_level, unused_extern_names };
312            let unused_extern_json = serde_json::to_string(&uext).unwrap();
313            eprintln!("{unused_extern_json}");
314        }
315    }
316}
317
318pub(crate) fn run_tests(
319    opts: GlobalTestOptions,
320    rustdoc_options: &Arc<RustdocOptions>,
321    unused_extern_reports: &Arc<Mutex<Vec<UnusedExterns>>>,
322    mut standalone_tests: Vec<test::TestDescAndFn>,
323    mergeable_tests: FxIndexMap<MergeableTestKey, Vec<(DocTestBuilder, ScrapedDocTest)>>,
324    // We pass this argument so we can drop it manually before using `exit`.
325    mut temp_dir: Option<TempDir>,
326) {
327    let mut test_args = Vec::with_capacity(rustdoc_options.test_args.len() + 1);
328    test_args.insert(0, "rustdoctest".to_string());
329    test_args.extend_from_slice(&rustdoc_options.test_args);
330    if rustdoc_options.no_capture {
331        test_args.push("--no-capture".to_string());
332    }
333
334    let mut nb_errors = 0;
335    let mut ran_edition_tests = 0;
336    let mut times = MergedDoctestTimes::new();
337    let target_str = rustdoc_options.target.to_string();
338
339    for (MergeableTestKey { edition, global_crate_attrs_hash }, mut doctests) in mergeable_tests {
340        if doctests.is_empty() {
341            continue;
342        }
343        doctests.sort_by(|(_, a), (_, b)| a.name.cmp(&b.name));
344
345        let mut tests_runner = runner::DocTestRunner::new();
346
347        let rustdoc_test_options = IndividualTestOptions::new(
348            rustdoc_options,
349            &Some(format!("merged_doctest_{edition}_{global_crate_attrs_hash}")),
350            PathBuf::from(format!("doctest_{edition}_{global_crate_attrs_hash}.rs")),
351        );
352
353        for (doctest, scraped_test) in &doctests {
354            tests_runner.add_test(doctest, scraped_test, &target_str);
355        }
356        let (duration, ret) = tests_runner.run_merged_tests(
357            rustdoc_test_options,
358            edition,
359            &opts,
360            &test_args,
361            rustdoc_options,
362        );
363        times.add_compilation_time(duration);
364        if let Ok(success) = ret {
365            ran_edition_tests += 1;
366            if !success {
367                nb_errors += 1;
368            }
369            continue;
370        }
371        // We failed to compile all compatible tests as one so we push them into the
372        // `standalone_tests` doctests.
373        debug!("Failed to compile compatible doctests for edition {} all at once", edition);
374        for (doctest, scraped_test) in doctests {
375            doctest.generate_unique_doctest(
376                &scraped_test.text,
377                scraped_test.langstr.test_harness,
378                &opts,
379                Some(&opts.crate_name),
380            );
381            standalone_tests.push(generate_test_desc_and_fn(
382                doctest,
383                scraped_test,
384                opts.clone(),
385                Arc::clone(rustdoc_options),
386                unused_extern_reports.clone(),
387            ));
388        }
389    }
390
391    // We need to call `test_main` even if there is no doctest to run to get the output
392    // `running 0 tests...`.
393    if ran_edition_tests == 0 || !standalone_tests.is_empty() {
394        standalone_tests.sort_by(|a, b| a.desc.name.as_slice().cmp(b.desc.name.as_slice()));
395        test::test_main_with_exit_callback(&test_args, standalone_tests, None, || {
396            let times = times.times_in_secs();
397            // We ensure temp dir destructor is called.
398            std::mem::drop(temp_dir.take());
399            if let Some((total_time, compilation_time)) = times {
400                test::print_merged_doctests_times(&test_args, total_time, compilation_time);
401            }
402        });
403    } else {
404        // If the first condition branch exited successfully, `test_main_with_exit_callback` will
405        // not exit the process. So to prevent displaying the times twice, we put it behind an
406        // `else` condition.
407        if let Some((total_time, compilation_time)) = times.times_in_secs() {
408            test::print_merged_doctests_times(&test_args, total_time, compilation_time);
409        }
410    }
411    // We ensure temp dir destructor is called.
412    std::mem::drop(temp_dir);
413    if nb_errors != 0 {
414        std::process::exit(test::ERROR_EXIT_CODE);
415    }
416}
417
418// Look for `#![doc(test(no_crate_inject))]`, used by crates in the std facade.
419fn scrape_test_config(
420    crate_name: String,
421    attrs: &[hir::Attribute],
422    args_file: PathBuf,
423) -> GlobalTestOptions {
424    let mut opts = GlobalTestOptions {
425        crate_name,
426        no_crate_inject: false,
427        insert_indent_space: false,
428        args_file,
429    };
430
431    let test_attrs: Vec<_> = attrs
432        .iter()
433        .filter(|a| a.has_name(sym::doc))
434        .flat_map(|a| a.meta_item_list().unwrap_or_default())
435        .filter(|a| a.has_name(sym::test))
436        .collect();
437    let attrs = test_attrs.iter().flat_map(|a| a.meta_item_list().unwrap_or(&[]));
438
439    for attr in attrs {
440        if attr.has_name(sym::no_crate_inject) {
441            opts.no_crate_inject = true;
442        }
443        // NOTE: `test(attr(..))` is handled when discovering the individual tests
444    }
445
446    opts
447}
448
449/// Documentation test failure modes.
450enum TestFailure {
451    /// The test failed to compile.
452    CompileError,
453    /// The test is marked `compile_fail` but compiled successfully.
454    UnexpectedCompilePass,
455    /// The test failed to compile (as expected) but the compiler output did not contain all
456    /// expected error codes.
457    MissingErrorCodes(Vec<String>),
458    /// The test binary was unable to be executed.
459    ExecutionError(io::Error),
460    /// The test binary exited with a non-zero exit code.
461    ///
462    /// This typically means an assertion in the test failed or another form of panic occurred.
463    ExecutionFailure(process::Output),
464    /// The test is marked `should_panic` but the test binary executed successfully.
465    UnexpectedRunPass,
466}
467
468enum DirState {
469    Temp(TempDir),
470    Perm(PathBuf),
471}
472
473impl DirState {
474    fn path(&self) -> &std::path::Path {
475        match self {
476            DirState::Temp(t) => t.path(),
477            DirState::Perm(p) => p.as_path(),
478        }
479    }
480}
481
482// NOTE: Keep this in sync with the equivalent structs in rustc
483// and cargo.
484// We could unify this struct the one in rustc but they have different
485// ownership semantics, so doing so would create wasteful allocations.
486#[derive(serde::Serialize, serde::Deserialize)]
487pub(crate) struct UnusedExterns {
488    /// Lint level of the unused_crate_dependencies lint
489    lint_level: String,
490    /// List of unused externs by their names.
491    unused_extern_names: Vec<String>,
492}
493
494fn add_exe_suffix(input: String, target: &TargetTuple) -> String {
495    let exe_suffix = match target {
496        TargetTuple::TargetTuple(_) => Target::expect_builtin(target).options.exe_suffix,
497        TargetTuple::TargetJson { contents, .. } => {
498            Target::from_json(contents).unwrap().0.options.exe_suffix
499        }
500    };
501    input + &exe_suffix
502}
503
504fn wrapped_rustc_command(rustc_wrappers: &[PathBuf], rustc_binary: &Path) -> Command {
505    let mut args = rustc_wrappers.iter().map(PathBuf::as_path).chain([rustc_binary]);
506
507    let exe = args.next().expect("unable to create rustc command");
508    let mut command = Command::new(exe);
509    for arg in args {
510        command.arg(arg);
511    }
512
513    command
514}
515
516/// Information needed for running a bundle of doctests.
517///
518/// This data structure contains the "full" test code, including the wrappers
519/// (if multiple doctests are merged), `main` function,
520/// and everything needed to calculate the compiler's command-line arguments.
521/// The `# ` prefix on boring lines has also been stripped.
522pub(crate) struct RunnableDocTest {
523    full_test_code: String,
524    full_test_line_offset: usize,
525    test_opts: IndividualTestOptions,
526    global_opts: GlobalTestOptions,
527    langstr: LangString,
528    line: usize,
529    edition: Edition,
530    no_run: bool,
531    merged_test_code: Option<String>,
532}
533
534impl RunnableDocTest {
535    fn path_for_merged_doctest_bundle(&self) -> PathBuf {
536        self.test_opts.outdir.path().join(format!("doctest_bundle_{}.rs", self.edition))
537    }
538    fn path_for_merged_doctest_runner(&self) -> PathBuf {
539        self.test_opts.outdir.path().join(format!("doctest_runner_{}.rs", self.edition))
540    }
541    fn is_multiple_tests(&self) -> bool {
542        self.merged_test_code.is_some()
543    }
544}
545
546/// Execute a `RunnableDoctest`.
547///
548/// This is the function that calculates the compiler command line, invokes the compiler, then
549/// invokes the test or tests in a separate executable (if applicable).
550///
551/// Returns a tuple containing the `Duration` of the compilation and the `Result` of the test.
552fn run_test(
553    doctest: RunnableDocTest,
554    rustdoc_options: &RustdocOptions,
555    supports_color: bool,
556    report_unused_externs: impl Fn(UnusedExterns),
557) -> (Duration, Result<(), TestFailure>) {
558    let langstr = &doctest.langstr;
559    // Make sure we emit well-formed executable names for our target.
560    let rust_out = add_exe_suffix("rust_out".to_owned(), &rustdoc_options.target);
561    let output_file = doctest.test_opts.outdir.path().join(rust_out);
562    let instant = Instant::now();
563
564    // Common arguments used for compiling the doctest runner.
565    // On merged doctests, the compiler is invoked twice: once for the test code itself,
566    // and once for the runner wrapper (which needs to use `#![feature]` on stable).
567    let mut compiler_args = vec![];
568
569    compiler_args.push(format!("@{}", doctest.global_opts.args_file.display()));
570
571    let sysroot = &rustdoc_options.sysroot;
572    if let Some(explicit_sysroot) = &sysroot.explicit {
573        compiler_args.push(format!("--sysroot={}", explicit_sysroot.display()));
574    }
575
576    compiler_args.extend_from_slice(&["--edition".to_owned(), doctest.edition.to_string()]);
577    if langstr.test_harness {
578        compiler_args.push("--test".to_owned());
579    }
580    if rustdoc_options.json_unused_externs.is_enabled() && !langstr.compile_fail {
581        compiler_args.push("--error-format=json".to_owned());
582        compiler_args.extend_from_slice(&["--json".to_owned(), "unused-externs".to_owned()]);
583        compiler_args.extend_from_slice(&["-W".to_owned(), "unused_crate_dependencies".to_owned()]);
584        compiler_args.extend_from_slice(&["-Z".to_owned(), "unstable-options".to_owned()]);
585    }
586
587    if doctest.no_run && !langstr.compile_fail && rustdoc_options.persist_doctests.is_none() {
588        // FIXME: why does this code check if it *shouldn't* persist doctests
589        //        -- shouldn't it be the negation?
590        compiler_args.push("--emit=metadata".to_owned());
591    }
592    compiler_args.extend_from_slice(&[
593        "--target".to_owned(),
594        match &rustdoc_options.target {
595            TargetTuple::TargetTuple(s) => s.clone(),
596            TargetTuple::TargetJson { path_for_rustdoc, .. } => {
597                path_for_rustdoc.to_str().expect("target path must be valid unicode").to_owned()
598            }
599        },
600    ]);
601    if let ErrorOutputType::HumanReadable { kind, color_config } = rustdoc_options.error_format {
602        let short = kind.short();
603        let unicode = kind == HumanReadableErrorType::AnnotateSnippet { unicode: true, short };
604
605        if short {
606            compiler_args.extend_from_slice(&["--error-format".to_owned(), "short".to_owned()]);
607        }
608        if unicode {
609            compiler_args
610                .extend_from_slice(&["--error-format".to_owned(), "human-unicode".to_owned()]);
611        }
612
613        match color_config {
614            ColorConfig::Never => {
615                compiler_args.extend_from_slice(&["--color".to_owned(), "never".to_owned()]);
616            }
617            ColorConfig::Always => {
618                compiler_args.extend_from_slice(&["--color".to_owned(), "always".to_owned()]);
619            }
620            ColorConfig::Auto => {
621                compiler_args.extend_from_slice(&[
622                    "--color".to_owned(),
623                    if supports_color { "always" } else { "never" }.to_owned(),
624                ]);
625            }
626        }
627    }
628
629    let rustc_binary = rustdoc_options
630        .test_builder
631        .as_deref()
632        .unwrap_or_else(|| rustc_interface::util::rustc_path(sysroot).expect("found rustc"));
633    let mut compiler = wrapped_rustc_command(&rustdoc_options.test_builder_wrappers, rustc_binary);
634
635    compiler.args(&compiler_args);
636
637    // If this is a merged doctest, we need to write it into a file instead of using stdin
638    // because if the size of the merged doctests is too big, it'll simply break stdin.
639    if doctest.is_multiple_tests() {
640        // It makes the compilation failure much faster if it is for a combined doctest.
641        compiler.arg("--error-format=short");
642        let input_file = doctest.path_for_merged_doctest_bundle();
643        if std::fs::write(&input_file, &doctest.full_test_code).is_err() {
644            // If we cannot write this file for any reason, we leave. All combined tests will be
645            // tested as standalone tests.
646            return (Duration::default(), Err(TestFailure::CompileError));
647        }
648        if !rustdoc_options.no_capture {
649            // If `no_capture` is disabled, then we don't display rustc's output when compiling
650            // the merged doctests.
651            compiler.stderr(Stdio::null());
652        }
653        // bundled tests are an rlib, loaded by a separate runner executable
654        compiler
655            .arg("--crate-type=lib")
656            .arg("--out-dir")
657            .arg(doctest.test_opts.outdir.path())
658            .arg(input_file);
659    } else {
660        compiler.arg("--crate-type=bin").arg("-o").arg(&output_file);
661        // Setting these environment variables is unneeded if this is a merged doctest.
662        compiler.env("UNSTABLE_RUSTDOC_TEST_PATH", &doctest.test_opts.path);
663        compiler.env(
664            "UNSTABLE_RUSTDOC_TEST_LINE",
665            format!("{}", doctest.line as isize - doctest.full_test_line_offset as isize),
666        );
667        compiler.arg("-");
668        compiler.stdin(Stdio::piped());
669        compiler.stderr(Stdio::piped());
670    }
671
672    debug!("compiler invocation for doctest: {compiler:?}");
673
674    let mut child = match compiler.spawn() {
675        Ok(child) => child,
676        Err(error) => {
677            eprintln!("Failed to spawn {:?}: {error:?}", compiler.get_program());
678            return (Duration::default(), Err(TestFailure::CompileError));
679        }
680    };
681    let output = if let Some(merged_test_code) = &doctest.merged_test_code {
682        // compile-fail tests never get merged, so this should always pass
683        let status = child.wait().expect("Failed to wait");
684
685        // the actual test runner is a separate component, built with nightly-only features;
686        // build it now
687        let runner_input_file = doctest.path_for_merged_doctest_runner();
688
689        let mut runner_compiler =
690            wrapped_rustc_command(&rustdoc_options.test_builder_wrappers, rustc_binary);
691        // the test runner does not contain any user-written code, so this doesn't allow
692        // the user to exploit nightly-only features on stable
693        runner_compiler.env("RUSTC_BOOTSTRAP", "1");
694        runner_compiler.args(compiler_args);
695        runner_compiler.args(["--crate-type=bin", "-o"]).arg(&output_file);
696        let mut extern_path = std::ffi::OsString::from(format!(
697            "--extern=doctest_bundle_{edition}=",
698            edition = doctest.edition
699        ));
700
701        // Deduplicate passed -L directory paths, since usually all dependencies will be in the
702        // same directory (e.g. target/debug/deps from Cargo).
703        let mut seen_search_dirs = FxHashSet::default();
704        for extern_str in &rustdoc_options.extern_strs {
705            if let Some((_cratename, path)) = extern_str.split_once('=') {
706                // Direct dependencies of the tests themselves are
707                // indirect dependencies of the test runner.
708                // They need to be in the library search path.
709                let dir = Path::new(path)
710                    .parent()
711                    .filter(|x| x.components().count() > 0)
712                    .unwrap_or(Path::new("."));
713                if seen_search_dirs.insert(dir) {
714                    runner_compiler.arg("-L").arg(dir);
715                }
716            }
717        }
718        let output_bundle_file = doctest
719            .test_opts
720            .outdir
721            .path()
722            .join(format!("libdoctest_bundle_{edition}.rlib", edition = doctest.edition));
723        extern_path.push(&output_bundle_file);
724        runner_compiler.arg(extern_path);
725        runner_compiler.arg(&runner_input_file);
726        if std::fs::write(&runner_input_file, merged_test_code).is_err() {
727            // If we cannot write this file for any reason, we leave. All combined tests will be
728            // tested as standalone tests.
729            return (instant.elapsed(), Err(TestFailure::CompileError));
730        }
731        if !rustdoc_options.no_capture {
732            // If `no_capture` is disabled, then we don't display rustc's output when compiling
733            // the merged doctests.
734            runner_compiler.stderr(Stdio::null());
735        }
736        runner_compiler.arg("--error-format=short");
737        debug!("compiler invocation for doctest runner: {runner_compiler:?}");
738
739        let status = if !status.success() {
740            status
741        } else {
742            let mut child_runner = match runner_compiler.spawn() {
743                Ok(child) => child,
744                Err(error) => {
745                    eprintln!("Failed to spawn {:?}: {error:?}", runner_compiler.get_program());
746                    return (Duration::default(), Err(TestFailure::CompileError));
747                }
748            };
749            child_runner.wait().expect("Failed to wait")
750        };
751
752        process::Output { status, stdout: Vec::new(), stderr: Vec::new() }
753    } else {
754        let stdin = child.stdin.as_mut().expect("Failed to open stdin");
755        stdin.write_all(doctest.full_test_code.as_bytes()).expect("could write out test sources");
756        child.wait_with_output().expect("Failed to read stdout")
757    };
758
759    struct Bomb<'a>(&'a str);
760    impl Drop for Bomb<'_> {
761        fn drop(&mut self) {
762            eprint!("{}", self.0);
763        }
764    }
765    let mut out = str::from_utf8(&output.stderr)
766        .unwrap()
767        .lines()
768        .filter(|l| {
769            if let Ok(uext) = serde_json::from_str::<UnusedExterns>(l) {
770                report_unused_externs(uext);
771                false
772            } else {
773                true
774            }
775        })
776        .intersperse_with(|| "\n")
777        .collect::<String>();
778
779    // Add a \n to the end to properly terminate the last line,
780    // but only if there was output to be printed
781    if !out.is_empty() {
782        out.push('\n');
783    }
784
785    let _bomb = Bomb(&out);
786    match (output.status.success(), langstr.compile_fail) {
787        (true, true) => {
788            return (instant.elapsed(), Err(TestFailure::UnexpectedCompilePass));
789        }
790        (true, false) => {}
791        (false, true) => {
792            if !langstr.error_codes.is_empty() {
793                // We used to check if the output contained "error[{}]: " but since we added the
794                // colored output, we can't anymore because of the color escape characters before
795                // the ":".
796                let missing_codes: Vec<String> = langstr
797                    .error_codes
798                    .iter()
799                    .filter(|err| !out.contains(&format!("error[{err}]")))
800                    .cloned()
801                    .collect();
802
803                if !missing_codes.is_empty() {
804                    return (instant.elapsed(), Err(TestFailure::MissingErrorCodes(missing_codes)));
805                }
806            }
807        }
808        (false, false) => {
809            return (instant.elapsed(), Err(TestFailure::CompileError));
810        }
811    }
812
813    let duration = instant.elapsed();
814    if doctest.no_run {
815        return (duration, Ok(()));
816    }
817
818    // Run the code!
819    let mut cmd;
820
821    let output_file = make_maybe_absolute_path(output_file);
822    if let Some(tool) = &rustdoc_options.test_runtool {
823        let tool = make_maybe_absolute_path(tool.into());
824        cmd = Command::new(tool);
825        cmd.args(&rustdoc_options.test_runtool_args);
826        cmd.arg(&output_file);
827    } else {
828        cmd = Command::new(&output_file);
829        if doctest.is_multiple_tests() {
830            cmd.env("RUSTDOC_DOCTEST_BIN_PATH", &output_file);
831        }
832    }
833    if let Some(run_directory) = &rustdoc_options.test_run_directory {
834        cmd.current_dir(run_directory);
835    }
836
837    let result = if doctest.is_multiple_tests() || rustdoc_options.no_capture {
838        cmd.status().map(|status| process::Output {
839            status,
840            stdout: Vec::new(),
841            stderr: Vec::new(),
842        })
843    } else {
844        cmd.output()
845    };
846    match result {
847        Err(e) => return (duration, Err(TestFailure::ExecutionError(e))),
848        Ok(out) => {
849            if langstr.should_panic && out.status.success() {
850                return (duration, Err(TestFailure::UnexpectedRunPass));
851            } else if !langstr.should_panic && !out.status.success() {
852                return (duration, Err(TestFailure::ExecutionFailure(out)));
853            }
854        }
855    }
856
857    (duration, Ok(()))
858}
859
860/// Converts a path intended to use as a command to absolute if it is
861/// relative, and not a single component.
862///
863/// This is needed to deal with relative paths interacting with
864/// `Command::current_dir` in a platform-specific way.
865fn make_maybe_absolute_path(path: PathBuf) -> PathBuf {
866    if path.components().count() == 1 {
867        // Look up process via PATH.
868        path
869    } else {
870        std::env::current_dir().map(|c| c.join(&path)).unwrap_or_else(|_| path)
871    }
872}
873struct IndividualTestOptions {
874    outdir: DirState,
875    path: PathBuf,
876}
877
878impl IndividualTestOptions {
879    fn new(options: &RustdocOptions, test_id: &Option<String>, test_path: PathBuf) -> Self {
880        let outdir = if let Some(ref path) = options.persist_doctests {
881            let mut path = path.clone();
882            path.push(test_id.as_deref().unwrap_or("<doctest>"));
883
884            if let Err(err) = std::fs::create_dir_all(&path) {
885                eprintln!("Couldn't create directory for doctest executables: {err}");
886                panic::resume_unwind(Box::new(()));
887            }
888
889            DirState::Perm(path)
890        } else {
891            DirState::Temp(get_doctest_dir().expect("rustdoc needs a tempdir"))
892        };
893
894        Self { outdir, path: test_path }
895    }
896}
897
898/// A doctest scraped from the code, ready to be turned into a runnable test.
899///
900/// The pipeline goes: [`clean`] AST -> `ScrapedDoctest` -> `RunnableDoctest`.
901/// [`run_merged_tests`] converts a bunch of scraped doctests to a single runnable doctest,
902/// while [`generate_unique_doctest`] does the standalones.
903///
904/// [`clean`]: crate::clean
905/// [`run_merged_tests`]: crate::doctest::runner::DocTestRunner::run_merged_tests
906/// [`generate_unique_doctest`]: crate::doctest::make::DocTestBuilder::generate_unique_doctest
907#[derive(Debug)]
908pub(crate) struct ScrapedDocTest {
909    filename: FileName,
910    line: usize,
911    langstr: LangString,
912    text: String,
913    name: String,
914    span: Span,
915    global_crate_attrs: Vec<String>,
916}
917
918impl ScrapedDocTest {
919    fn new(
920        filename: FileName,
921        line: usize,
922        logical_path: Vec<String>,
923        langstr: LangString,
924        text: String,
925        span: Span,
926        global_crate_attrs: Vec<String>,
927    ) -> Self {
928        let mut item_path = logical_path.join("::");
929        item_path.retain(|c| c != ' ');
930        if !item_path.is_empty() {
931            item_path.push(' ');
932        }
933        let name =
934            format!("{} - {item_path}(line {line})", filename.prefer_remapped_unconditionally());
935
936        Self { filename, line, langstr, text, name, span, global_crate_attrs }
937    }
938    fn edition(&self, opts: &RustdocOptions) -> Edition {
939        self.langstr.edition.unwrap_or(opts.edition)
940    }
941
942    fn no_run(&self, opts: &RustdocOptions) -> bool {
943        self.langstr.no_run || opts.no_run
944    }
945    fn path(&self) -> PathBuf {
946        match &self.filename {
947            FileName::Real(path) => {
948                if let Some(local_path) = path.local_path() {
949                    local_path.to_path_buf()
950                } else {
951                    // Somehow we got the filename from the metadata of another crate, should never happen
952                    unreachable!("doctest from a different crate");
953                }
954            }
955            _ => PathBuf::from(r"doctest.rs"),
956        }
957    }
958}
959
960pub(crate) trait DocTestVisitor {
961    fn visit_test(&mut self, test: String, config: LangString, rel_line: MdRelLine);
962    fn visit_header(&mut self, _name: &str, _level: u32) {}
963}
964
965#[derive(Clone, Debug, Hash, Eq, PartialEq)]
966pub(crate) struct MergeableTestKey {
967    edition: Edition,
968    global_crate_attrs_hash: u64,
969}
970
971struct CreateRunnableDocTests {
972    standalone_tests: Vec<test::TestDescAndFn>,
973    mergeable_tests: FxIndexMap<MergeableTestKey, Vec<(DocTestBuilder, ScrapedDocTest)>>,
974
975    rustdoc_options: Arc<RustdocOptions>,
976    opts: GlobalTestOptions,
977    visited_tests: FxHashMap<(String, usize), usize>,
978    unused_extern_reports: Arc<Mutex<Vec<UnusedExterns>>>,
979    compiling_test_count: AtomicUsize,
980    can_merge_doctests: bool,
981}
982
983impl CreateRunnableDocTests {
984    fn new(rustdoc_options: RustdocOptions, opts: GlobalTestOptions) -> CreateRunnableDocTests {
985        let can_merge_doctests = rustdoc_options.edition >= Edition::Edition2024;
986        CreateRunnableDocTests {
987            standalone_tests: Vec::new(),
988            mergeable_tests: FxIndexMap::default(),
989            rustdoc_options: Arc::new(rustdoc_options),
990            opts,
991            visited_tests: FxHashMap::default(),
992            unused_extern_reports: Default::default(),
993            compiling_test_count: AtomicUsize::new(0),
994            can_merge_doctests,
995        }
996    }
997
998    fn add_test(&mut self, scraped_test: ScrapedDocTest, dcx: Option<DiagCtxtHandle<'_>>) {
999        // For example `module/file.rs` would become `module_file_rs`
1000        let file = scraped_test
1001            .filename
1002            .prefer_local()
1003            .to_string_lossy()
1004            .chars()
1005            .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
1006            .collect::<String>();
1007        let test_id = format!(
1008            "{file}_{line}_{number}",
1009            file = file,
1010            line = scraped_test.line,
1011            number = {
1012                // Increases the current test number, if this file already
1013                // exists or it creates a new entry with a test number of 0.
1014                self.visited_tests
1015                    .entry((file.clone(), scraped_test.line))
1016                    .and_modify(|v| *v += 1)
1017                    .or_insert(0)
1018            },
1019        );
1020
1021        let edition = scraped_test.edition(&self.rustdoc_options);
1022        let doctest = BuildDocTestBuilder::new(&scraped_test.text)
1023            .crate_name(&self.opts.crate_name)
1024            .global_crate_attrs(scraped_test.global_crate_attrs.clone())
1025            .edition(edition)
1026            .can_merge_doctests(self.can_merge_doctests)
1027            .test_id(test_id)
1028            .lang_str(&scraped_test.langstr)
1029            .span(scraped_test.span)
1030            .build(dcx);
1031        let is_standalone = !doctest.can_be_merged
1032            || self.rustdoc_options.no_capture
1033            || self.rustdoc_options.test_args.iter().any(|arg| arg == "--show-output");
1034        if is_standalone {
1035            let test_desc = self.generate_test_desc_and_fn(doctest, scraped_test);
1036            self.standalone_tests.push(test_desc);
1037        } else {
1038            self.mergeable_tests
1039                .entry(MergeableTestKey {
1040                    edition,
1041                    global_crate_attrs_hash: {
1042                        let mut hasher = FxHasher::default();
1043                        scraped_test.global_crate_attrs.hash(&mut hasher);
1044                        hasher.finish()
1045                    },
1046                })
1047                .or_default()
1048                .push((doctest, scraped_test));
1049        }
1050    }
1051
1052    fn generate_test_desc_and_fn(
1053        &mut self,
1054        test: DocTestBuilder,
1055        scraped_test: ScrapedDocTest,
1056    ) -> test::TestDescAndFn {
1057        if !scraped_test.langstr.compile_fail {
1058            self.compiling_test_count.fetch_add(1, Ordering::SeqCst);
1059        }
1060
1061        generate_test_desc_and_fn(
1062            test,
1063            scraped_test,
1064            self.opts.clone(),
1065            Arc::clone(&self.rustdoc_options),
1066            self.unused_extern_reports.clone(),
1067        )
1068    }
1069}
1070
1071fn generate_test_desc_and_fn(
1072    test: DocTestBuilder,
1073    scraped_test: ScrapedDocTest,
1074    opts: GlobalTestOptions,
1075    rustdoc_options: Arc<RustdocOptions>,
1076    unused_externs: Arc<Mutex<Vec<UnusedExterns>>>,
1077) -> test::TestDescAndFn {
1078    let target_str = rustdoc_options.target.to_string();
1079    let rustdoc_test_options =
1080        IndividualTestOptions::new(&rustdoc_options, &test.test_id, scraped_test.path());
1081
1082    debug!("creating test {}: {}", scraped_test.name, scraped_test.text);
1083    test::TestDescAndFn {
1084        desc: test::TestDesc {
1085            name: test::DynTestName(scraped_test.name.clone()),
1086            ignore: match scraped_test.langstr.ignore {
1087                Ignore::All => true,
1088                Ignore::None => false,
1089                Ignore::Some(ref ignores) => ignores.iter().any(|s| target_str.contains(s)),
1090            },
1091            ignore_message: None,
1092            source_file: "",
1093            start_line: 0,
1094            start_col: 0,
1095            end_line: 0,
1096            end_col: 0,
1097            // compiler failures are test failures
1098            should_panic: test::ShouldPanic::No,
1099            compile_fail: scraped_test.langstr.compile_fail,
1100            no_run: scraped_test.no_run(&rustdoc_options),
1101            test_type: test::TestType::DocTest,
1102        },
1103        testfn: test::DynTestFn(Box::new(move || {
1104            doctest_run_fn(
1105                rustdoc_test_options,
1106                opts,
1107                test,
1108                scraped_test,
1109                rustdoc_options,
1110                unused_externs,
1111            )
1112        })),
1113    }
1114}
1115
1116fn doctest_run_fn(
1117    test_opts: IndividualTestOptions,
1118    global_opts: GlobalTestOptions,
1119    doctest: DocTestBuilder,
1120    scraped_test: ScrapedDocTest,
1121    rustdoc_options: Arc<RustdocOptions>,
1122    unused_externs: Arc<Mutex<Vec<UnusedExterns>>>,
1123) -> Result<(), String> {
1124    let report_unused_externs = |uext| {
1125        unused_externs.lock().unwrap().push(uext);
1126    };
1127    let (wrapped, full_test_line_offset) = doctest.generate_unique_doctest(
1128        &scraped_test.text,
1129        scraped_test.langstr.test_harness,
1130        &global_opts,
1131        Some(&global_opts.crate_name),
1132    );
1133    let runnable_test = RunnableDocTest {
1134        full_test_code: wrapped.to_string(),
1135        full_test_line_offset,
1136        test_opts,
1137        global_opts,
1138        langstr: scraped_test.langstr.clone(),
1139        line: scraped_test.line,
1140        edition: scraped_test.edition(&rustdoc_options),
1141        no_run: scraped_test.no_run(&rustdoc_options),
1142        merged_test_code: None,
1143    };
1144    let (_, res) =
1145        run_test(runnable_test, &rustdoc_options, doctest.supports_color, report_unused_externs);
1146
1147    if let Err(err) = res {
1148        match err {
1149            TestFailure::CompileError => {
1150                eprint!("Couldn't compile the test.");
1151            }
1152            TestFailure::UnexpectedCompilePass => {
1153                eprint!("Test compiled successfully, but it's marked `compile_fail`.");
1154            }
1155            TestFailure::UnexpectedRunPass => {
1156                eprint!("Test executable succeeded, but it's marked `should_panic`.");
1157            }
1158            TestFailure::MissingErrorCodes(codes) => {
1159                eprint!("Some expected error codes were not found: {codes:?}");
1160            }
1161            TestFailure::ExecutionError(err) => {
1162                eprint!("Couldn't run the test: {err}");
1163                if err.kind() == io::ErrorKind::PermissionDenied {
1164                    eprint!(" - maybe your tempdir is mounted with noexec?");
1165                }
1166            }
1167            TestFailure::ExecutionFailure(out) => {
1168                eprintln!("Test executable failed ({reason}).", reason = out.status);
1169
1170                // FIXME(#12309): An unfortunate side-effect of capturing the test
1171                // executable's output is that the relative ordering between the test's
1172                // stdout and stderr is lost. However, this is better than the
1173                // alternative: if the test executable inherited the parent's I/O
1174                // handles the output wouldn't be captured at all, even on success.
1175                //
1176                // The ordering could be preserved if the test process' stderr was
1177                // redirected to stdout, but that functionality does not exist in the
1178                // standard library, so it may not be portable enough.
1179                let stdout = str::from_utf8(&out.stdout).unwrap_or_default();
1180                let stderr = str::from_utf8(&out.stderr).unwrap_or_default();
1181
1182                if !stdout.is_empty() || !stderr.is_empty() {
1183                    eprintln!();
1184
1185                    if !stdout.is_empty() {
1186                        eprintln!("stdout:\n{stdout}");
1187                    }
1188
1189                    if !stderr.is_empty() {
1190                        eprintln!("stderr:\n{stderr}");
1191                    }
1192                }
1193            }
1194        }
1195
1196        panic::resume_unwind(Box::new(()));
1197    }
1198    Ok(())
1199}
1200
1201#[cfg(test)] // used in tests
1202impl DocTestVisitor for Vec<usize> {
1203    fn visit_test(&mut self, _test: String, _config: LangString, rel_line: MdRelLine) {
1204        self.push(1 + rel_line.offset());
1205    }
1206}
1207
1208#[cfg(test)]
1209mod tests;