Skip to main content

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