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