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