compiletest/
lib.rs

1#![crate_name = "compiletest"]
2
3#[cfg(test)]
4mod tests;
5
6pub mod cli;
7mod common;
8mod debuggers;
9mod diagnostics;
10mod directives;
11mod edition;
12mod errors;
13mod executor;
14mod json;
15mod output_capture;
16mod panic_hook;
17mod raise_fd_limit;
18mod read2;
19mod runtest;
20pub mod rustdoc_gui_test;
21mod util;
22
23use core::panic;
24use std::collections::HashSet;
25use std::fmt::Write;
26use std::io::{self, ErrorKind};
27use std::sync::{Arc, OnceLock};
28use std::time::SystemTime;
29use std::{env, fs, vec};
30
31use build_helper::git::{get_git_modified_files, get_git_untracked_files};
32use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
33use getopts::Options;
34use rayon::iter::{ParallelBridge, ParallelIterator};
35use tracing::debug;
36use walkdir::WalkDir;
37
38use self::directives::{EarlyProps, make_test_description};
39use crate::common::{
40    CodegenBackend, CompareMode, Config, Debugger, PassMode, TestMode, TestPaths, UI_EXTENSIONS,
41    expected_output_path, output_base_dir, output_relative_path,
42};
43use crate::directives::{AuxProps, DirectivesCache, FileDirectives};
44use crate::edition::parse_edition;
45use crate::executor::CollectedTest;
46
47/// Creates the `Config` instance for this invocation of compiletest.
48///
49/// The config mostly reflects command-line arguments, but there might also be
50/// some code here that inspects environment variables or even runs executables
51/// (e.g. when discovering debugger versions).
52fn parse_config(args: Vec<String>) -> Config {
53    let mut opts = Options::new();
54    opts.reqopt("", "compile-lib-path", "path to host shared libraries", "PATH")
55        .reqopt("", "run-lib-path", "path to target shared libraries", "PATH")
56        .reqopt("", "rustc-path", "path to rustc to use for compiling", "PATH")
57        .optopt("", "cargo-path", "path to cargo to use for compiling", "PATH")
58        .optopt(
59            "",
60            "stage0-rustc-path",
61            "path to rustc to use for compiling run-make recipes",
62            "PATH",
63        )
64        .optopt(
65            "",
66            "query-rustc-path",
67            "path to rustc to use for querying target information (defaults to `--rustc-path`)",
68            "PATH",
69        )
70        .optopt("", "rustdoc-path", "path to rustdoc to use for compiling", "PATH")
71        .optopt("", "coverage-dump-path", "path to coverage-dump to use in tests", "PATH")
72        .reqopt("", "python", "path to python to use for doc tests", "PATH")
73        .optopt("", "jsondocck-path", "path to jsondocck to use for doc tests", "PATH")
74        .optopt("", "jsondoclint-path", "path to jsondoclint to use for doc tests", "PATH")
75        .optopt("", "run-clang-based-tests-with", "path to Clang executable", "PATH")
76        .optopt("", "llvm-filecheck", "path to LLVM's FileCheck binary", "DIR")
77        .reqopt("", "src-root", "directory containing sources", "PATH")
78        .reqopt("", "src-test-suite-root", "directory containing test suite sources", "PATH")
79        .reqopt("", "build-root", "path to root build directory", "PATH")
80        .reqopt("", "build-test-suite-root", "path to test suite specific build directory", "PATH")
81        .reqopt("", "sysroot-base", "directory containing the compiler sysroot", "PATH")
82        .reqopt("", "stage", "stage number under test", "N")
83        .reqopt("", "stage-id", "the target-stage identifier", "stageN-TARGET")
84        .reqopt(
85            "",
86            "mode",
87            "which sort of compile tests to run",
88            "pretty | debug-info | codegen | rustdoc-html \
89            | rustdoc-json | codegen-units | incremental | run-make | ui \
90            | rustdoc-js | mir-opt | assembly | crashes",
91        )
92        .reqopt(
93            "",
94            "suite",
95            "which suite of compile tests to run. used for nicer error reporting.",
96            "SUITE",
97        )
98        .optopt(
99            "",
100            "pass",
101            "force {check,build,run}-pass tests to this mode.",
102            "check | build | run",
103        )
104        .optopt("", "run", "whether to execute run-* tests", "auto | always | never")
105        .optflag("", "ignored", "run tests marked as ignored")
106        .optflag("", "has-enzyme", "run tests that require enzyme")
107        .optflag("", "has-offload", "run tests that require offload")
108        .optflag("", "with-rustc-debug-assertions", "whether rustc was built with debug assertions")
109        .optflag("", "with-std-debug-assertions", "whether std was built with debug assertions")
110        .optflag("", "with-std-remap-debuginfo", "whether std was built with remapping")
111        .optmulti(
112            "",
113            "skip",
114            "skip tests matching SUBSTRING. Can be passed multiple times",
115            "SUBSTRING",
116        )
117        .optflag("", "exact", "filters match exactly")
118        .optopt(
119            "",
120            "runner",
121            "supervisor program to run tests under \
122             (eg. emulator, valgrind)",
123            "PROGRAM",
124        )
125        .optmulti("", "host-rustcflags", "flags to pass to rustc for host", "FLAGS")
126        .optmulti("", "target-rustcflags", "flags to pass to rustc for target", "FLAGS")
127        .optflag(
128            "",
129            "rust-randomized-layout",
130            "set this when rustc/stdlib were compiled with randomized layouts",
131        )
132        .optflag("", "optimize-tests", "run tests with optimizations enabled")
133        .optflag("", "verbose", "run tests verbosely, showing all output")
134        .optflag(
135            "",
136            "bless",
137            "overwrite stderr/stdout files instead of complaining about a mismatch",
138        )
139        .optflag("", "fail-fast", "stop as soon as possible after any test fails")
140        .optopt("", "target", "the target to build for", "TARGET")
141        .optopt("", "host", "the host to build for", "HOST")
142        .optopt("", "cdb", "path to CDB to use for CDB debuginfo tests", "PATH")
143        .optopt("", "gdb", "path to GDB to use for GDB debuginfo tests", "PATH")
144        .optopt("", "lldb", "path to LLDB to use for LLDB debuginfo tests", "PATH")
145        .optopt("", "lldb-version", "the version of LLDB used", "VERSION STRING")
146        .optopt("", "llvm-version", "the version of LLVM used", "VERSION STRING")
147        .optflag("", "system-llvm", "is LLVM the system LLVM")
148        .optopt("", "android-cross-path", "Android NDK standalone path", "PATH")
149        .optopt("", "adb-path", "path to the android debugger", "PATH")
150        .optopt("", "adb-test-dir", "path to tests for the android debugger", "PATH")
151        .reqopt("", "cc", "path to a C compiler", "PATH")
152        .reqopt("", "cxx", "path to a C++ compiler", "PATH")
153        .reqopt("", "cflags", "flags for the C compiler", "FLAGS")
154        .reqopt("", "cxxflags", "flags for the CXX compiler", "FLAGS")
155        .optopt("", "ar", "path to an archiver", "PATH")
156        .optopt("", "target-linker", "path to a linker for the target", "PATH")
157        .optopt("", "host-linker", "path to a linker for the host", "PATH")
158        .reqopt("", "llvm-components", "list of LLVM components built in", "LIST")
159        .optopt("", "llvm-bin-dir", "Path to LLVM's `bin` directory", "PATH")
160        .optopt("", "nodejs", "the name of nodejs", "PATH")
161        .optopt("", "npm", "the name of npm", "PATH")
162        .optopt("", "remote-test-client", "path to the remote test client", "PATH")
163        .optopt(
164            "",
165            "compare-mode",
166            "mode describing what file the actual ui output will be compared to",
167            "COMPARE MODE",
168        )
169        .optflag(
170            "",
171            "rustfix-coverage",
172            "enable this to generate a Rustfix coverage file, which is saved in \
173            `./<build_test_suite_root>/rustfix_missing_coverage.txt`",
174        )
175        .optflag("", "force-rerun", "rerun tests even if the inputs are unchanged")
176        .optflag("", "only-modified", "only run tests that result been modified")
177        // FIXME: Temporarily retained so we can point users to `--no-capture`
178        .optflag("", "nocapture", "")
179        .optflag("", "no-capture", "don't capture stdout/stderr of tests")
180        .optflag("", "profiler-runtime", "is the profiler runtime enabled for this target")
181        .optflag("h", "help", "show this message")
182        .reqopt("", "channel", "current Rust channel", "CHANNEL")
183        .optflag(
184            "",
185            "git-hash",
186            "run tests which rely on commit version being compiled into the binaries",
187        )
188        .optopt("", "edition", "default Rust edition", "EDITION")
189        .reqopt("", "nightly-branch", "name of the git branch for nightly", "BRANCH")
190        .reqopt(
191            "",
192            "git-merge-commit-email",
193            "email address used for finding merge commits",
194            "EMAIL",
195        )
196        .optopt(
197            "",
198            "compiletest-diff-tool",
199            "What custom diff tool to use for displaying compiletest tests.",
200            "COMMAND",
201        )
202        .reqopt("", "minicore-path", "path to minicore aux library", "PATH")
203        .optopt(
204            "",
205            "debugger",
206            "only test a specific debugger in debuginfo tests",
207            "gdb | lldb | cdb",
208        )
209        .optopt(
210            "",
211            "default-codegen-backend",
212            "the codegen backend currently used",
213            "CODEGEN BACKEND NAME",
214        )
215        .optopt(
216            "",
217            "override-codegen-backend",
218            "the codegen backend to use instead of the default one",
219            "CODEGEN BACKEND [NAME | PATH]",
220        )
221        .optflag("", "bypass-ignore-backends", "ignore `//@ ignore-backends` directives");
222
223    let (argv0, args_) = args.split_first().unwrap();
224    if args.len() == 1 || args[1] == "-h" || args[1] == "--help" {
225        let message = format!("Usage: {} [OPTIONS] [TESTNAME...]", argv0);
226        println!("{}", opts.usage(&message));
227        println!();
228        panic!()
229    }
230
231    let matches = &match opts.parse(args_) {
232        Ok(m) => m,
233        Err(f) => panic!("{:?}", f),
234    };
235
236    if matches.opt_present("h") || matches.opt_present("help") {
237        let message = format!("Usage: {} [OPTIONS]  [TESTNAME...]", argv0);
238        println!("{}", opts.usage(&message));
239        println!();
240        panic!()
241    }
242
243    fn make_absolute(path: Utf8PathBuf) -> Utf8PathBuf {
244        if path.is_relative() {
245            Utf8PathBuf::try_from(env::current_dir().unwrap()).unwrap().join(path)
246        } else {
247            path
248        }
249    }
250
251    fn opt_path(m: &getopts::Matches, nm: &str) -> Utf8PathBuf {
252        match m.opt_str(nm) {
253            Some(s) => Utf8PathBuf::from(&s),
254            None => panic!("no option (=path) found for {}", nm),
255        }
256    }
257
258    let host = matches.opt_str("host").expect("`--host` must be unconditionally specified");
259    let target = matches.opt_str("target").expect("`--target` must be unconditionally specified");
260
261    let android_cross_path = matches.opt_str("android-cross-path").map(Utf8PathBuf::from);
262
263    let adb_path = matches.opt_str("adb-path").map(Utf8PathBuf::from);
264    let adb_test_dir = matches.opt_str("adb-test-dir").map(Utf8PathBuf::from);
265    let adb_device_status = target.contains("android") && adb_test_dir.is_some();
266
267    // FIXME: `cdb_version` is *derived* from cdb, but it's *not* technically a config!
268    let cdb = matches.opt_str("cdb").map(Utf8PathBuf::from);
269    let cdb_version = cdb.as_deref().and_then(debuggers::query_cdb_version);
270    // FIXME: `gdb_version` is *derived* from gdb, but it's *not* technically a config!
271    let gdb = matches.opt_str("gdb").map(Utf8PathBuf::from);
272    let gdb_version = gdb.as_deref().and_then(debuggers::query_gdb_version);
273    // FIXME: `lldb_version` is *derived* from lldb, but it's *not* technically a config!
274    let lldb = matches.opt_str("lldb").map(Utf8PathBuf::from);
275    let lldb_version =
276        matches.opt_str("lldb-version").as_deref().and_then(debuggers::extract_lldb_version);
277    // FIXME: this is very questionable, we really should be obtaining LLVM version info from
278    // `bootstrap`, and not trying to be figuring out that in `compiletest` by running the
279    // `FileCheck` binary.
280    let llvm_version =
281        matches.opt_str("llvm-version").as_deref().map(directives::extract_llvm_version).or_else(
282            || directives::extract_llvm_version_from_binary(&matches.opt_str("llvm-filecheck")?),
283        );
284
285    let default_codegen_backend = match matches.opt_str("default-codegen-backend").as_deref() {
286        Some(backend) => match CodegenBackend::try_from(backend) {
287            Ok(backend) => backend,
288            Err(error) => {
289                panic!("invalid value `{backend}` for `--defalt-codegen-backend`: {error}")
290            }
291        },
292        // By default, it's always llvm.
293        None => CodegenBackend::Llvm,
294    };
295    let override_codegen_backend = matches.opt_str("override-codegen-backend");
296
297    let run_ignored = matches.opt_present("ignored");
298    let with_rustc_debug_assertions = matches.opt_present("with-rustc-debug-assertions");
299    let with_std_debug_assertions = matches.opt_present("with-std-debug-assertions");
300    let with_std_remap_debuginfo = matches.opt_present("with-std-remap-debuginfo");
301    let mode = matches.opt_str("mode").unwrap().parse().expect("invalid mode");
302    let has_enzyme = matches.opt_present("has-enzyme");
303    let has_offload = matches.opt_present("has-offload");
304    let filters = if mode == TestMode::RunMake {
305        matches
306            .free
307            .iter()
308            .map(|f| {
309                // Here `f` is relative to `./tests/run-make`. So if you run
310                //
311                //   ./x test tests/run-make/crate-loading
312                //
313                //  then `f` is "crate-loading".
314                let path = Utf8Path::new(f);
315                let mut iter = path.iter().skip(1);
316
317                if iter.next().is_some_and(|s| s == "rmake.rs") && iter.next().is_none() {
318                    // Strip the "rmake.rs" suffix. For example, if `f` is
319                    // "crate-loading/rmake.rs" then this gives us "crate-loading".
320                    path.parent().unwrap().to_string()
321                } else {
322                    f.to_string()
323                }
324            })
325            .collect::<Vec<_>>()
326    } else {
327        // Note that the filters are relative to the root dir of the different test
328        // suites. For example, with:
329        //
330        //   ./x test tests/ui/lint/unused
331        //
332        // the filter is "lint/unused".
333        matches.free.clone()
334    };
335    let compare_mode = matches.opt_str("compare-mode").map(|s| {
336        s.parse().unwrap_or_else(|_| {
337            let variants: Vec<_> = CompareMode::STR_VARIANTS.iter().copied().collect();
338            panic!(
339                "`{s}` is not a valid value for `--compare-mode`, it should be one of: {}",
340                variants.join(", ")
341            );
342        })
343    });
344    if matches.opt_present("nocapture") {
345        panic!("`--nocapture` is deprecated; please use `--no-capture`");
346    }
347
348    let stage = match matches.opt_str("stage") {
349        Some(stage) => stage.parse::<u32>().expect("expected `--stage` to be an unsigned integer"),
350        None => panic!("`--stage` is required"),
351    };
352
353    let src_root = opt_path(matches, "src-root");
354    let src_test_suite_root = opt_path(matches, "src-test-suite-root");
355    assert!(
356        src_test_suite_root.starts_with(&src_root),
357        "`src-root` must be a parent of `src-test-suite-root`: `src-root`=`{}`, `src-test-suite-root` = `{}`",
358        src_root,
359        src_test_suite_root
360    );
361
362    let build_root = opt_path(matches, "build-root");
363    let build_test_suite_root = opt_path(matches, "build-test-suite-root");
364    assert!(build_test_suite_root.starts_with(&build_root));
365
366    Config {
367        bless: matches.opt_present("bless"),
368        fail_fast: matches.opt_present("fail-fast")
369            || env::var_os("RUSTC_TEST_FAIL_FAST").is_some(),
370
371        host_compile_lib_path: make_absolute(opt_path(matches, "compile-lib-path")),
372        target_run_lib_path: make_absolute(opt_path(matches, "run-lib-path")),
373        rustc_path: opt_path(matches, "rustc-path"),
374        cargo_path: matches.opt_str("cargo-path").map(Utf8PathBuf::from),
375        stage0_rustc_path: matches.opt_str("stage0-rustc-path").map(Utf8PathBuf::from),
376        query_rustc_path: matches.opt_str("query-rustc-path").map(Utf8PathBuf::from),
377        rustdoc_path: matches.opt_str("rustdoc-path").map(Utf8PathBuf::from),
378        coverage_dump_path: matches.opt_str("coverage-dump-path").map(Utf8PathBuf::from),
379        python: matches.opt_str("python").unwrap(),
380        jsondocck_path: matches.opt_str("jsondocck-path").map(Utf8PathBuf::from),
381        jsondoclint_path: matches.opt_str("jsondoclint-path").map(Utf8PathBuf::from),
382        run_clang_based_tests_with: matches
383            .opt_str("run-clang-based-tests-with")
384            .map(Utf8PathBuf::from),
385        llvm_filecheck: matches.opt_str("llvm-filecheck").map(Utf8PathBuf::from),
386        llvm_bin_dir: matches.opt_str("llvm-bin-dir").map(Utf8PathBuf::from),
387
388        src_root,
389        src_test_suite_root,
390
391        build_root,
392        build_test_suite_root,
393
394        sysroot_base: opt_path(matches, "sysroot-base"),
395
396        stage,
397        stage_id: matches.opt_str("stage-id").unwrap(),
398
399        mode,
400        suite: matches.opt_str("suite").unwrap().parse().expect("invalid suite"),
401        debugger: matches.opt_str("debugger").map(|debugger| {
402            debugger
403                .parse::<Debugger>()
404                .unwrap_or_else(|_| panic!("unknown `--debugger` option `{debugger}` given"))
405        }),
406        run_ignored,
407        with_rustc_debug_assertions,
408        with_std_debug_assertions,
409        with_std_remap_debuginfo,
410        filters,
411        skip: matches.opt_strs("skip"),
412        filter_exact: matches.opt_present("exact"),
413        force_pass_mode: matches.opt_str("pass").map(|mode| {
414            mode.parse::<PassMode>()
415                .unwrap_or_else(|_| panic!("unknown `--pass` option `{}` given", mode))
416        }),
417        // FIXME: this run scheme is... confusing.
418        run: matches.opt_str("run").and_then(|mode| match mode.as_str() {
419            "auto" => None,
420            "always" => Some(true),
421            "never" => Some(false),
422            _ => panic!("unknown `--run` option `{}` given", mode),
423        }),
424        runner: matches.opt_str("runner"),
425        host_rustcflags: matches.opt_strs("host-rustcflags"),
426        target_rustcflags: matches.opt_strs("target-rustcflags"),
427        optimize_tests: matches.opt_present("optimize-tests"),
428        rust_randomized_layout: matches.opt_present("rust-randomized-layout"),
429        target,
430        host,
431        cdb,
432        cdb_version,
433        gdb,
434        gdb_version,
435        lldb,
436        lldb_version,
437        llvm_version,
438        system_llvm: matches.opt_present("system-llvm"),
439        android_cross_path,
440        adb_path,
441        adb_test_dir,
442        adb_device_status,
443        verbose: matches.opt_present("verbose"),
444        only_modified: matches.opt_present("only-modified"),
445        remote_test_client: matches.opt_str("remote-test-client").map(Utf8PathBuf::from),
446        compare_mode,
447        rustfix_coverage: matches.opt_present("rustfix-coverage"),
448        has_enzyme,
449        has_offload,
450        channel: matches.opt_str("channel").unwrap(),
451        git_hash: matches.opt_present("git-hash"),
452        edition: matches.opt_str("edition").as_deref().map(parse_edition),
453
454        cc: matches.opt_str("cc").unwrap(),
455        cxx: matches.opt_str("cxx").unwrap(),
456        cflags: matches.opt_str("cflags").unwrap(),
457        cxxflags: matches.opt_str("cxxflags").unwrap(),
458        ar: matches.opt_str("ar").unwrap_or_else(|| String::from("ar")),
459        target_linker: matches.opt_str("target-linker"),
460        host_linker: matches.opt_str("host-linker"),
461        llvm_components: matches.opt_str("llvm-components").unwrap(),
462        nodejs: matches.opt_str("nodejs").map(Utf8PathBuf::from),
463
464        force_rerun: matches.opt_present("force-rerun"),
465
466        target_cfgs: OnceLock::new(),
467        builtin_cfg_names: OnceLock::new(),
468        supported_crate_types: OnceLock::new(),
469
470        capture: !matches.opt_present("no-capture"),
471
472        nightly_branch: matches.opt_str("nightly-branch").unwrap(),
473        git_merge_commit_email: matches.opt_str("git-merge-commit-email").unwrap(),
474
475        profiler_runtime: matches.opt_present("profiler-runtime"),
476
477        diff_command: matches.opt_str("compiletest-diff-tool"),
478
479        minicore_path: opt_path(matches, "minicore-path"),
480
481        default_codegen_backend,
482        override_codegen_backend,
483        bypass_ignore_backends: matches.opt_present("bypass-ignore-backends"),
484    }
485}
486
487/// Called by `main` after the config has been parsed.
488fn run_tests(config: Arc<Config>) {
489    debug!(?config, "run_tests");
490
491    panic_hook::install_panic_hook();
492
493    // If we want to collect rustfix coverage information,
494    // we first make sure that the coverage file does not exist.
495    // It will be created later on.
496    if config.rustfix_coverage {
497        let mut coverage_file_path = config.build_test_suite_root.clone();
498        coverage_file_path.push("rustfix_missing_coverage.txt");
499        if coverage_file_path.exists() {
500            if let Err(e) = fs::remove_file(&coverage_file_path) {
501                panic!("Could not delete {} due to {}", coverage_file_path, e)
502            }
503        }
504    }
505
506    // sadly osx needs some file descriptor limits raised for running tests in
507    // parallel (especially when we have lots and lots of child processes).
508    // For context, see #8904
509    unsafe {
510        raise_fd_limit::raise_fd_limit();
511    }
512    // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows
513    // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary
514    //
515    // SAFETY: at this point we're still single-threaded.
516    unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") };
517
518    let mut configs = Vec::new();
519    if let TestMode::DebugInfo = config.mode {
520        // Debugging emscripten code doesn't make sense today
521        if !config.target.contains("emscripten") {
522            match config.debugger {
523                Some(Debugger::Cdb) => configs.extend(debuggers::configure_cdb(&config)),
524                Some(Debugger::Gdb) => configs.extend(debuggers::configure_gdb(&config)),
525                Some(Debugger::Lldb) => configs.extend(debuggers::configure_lldb(&config)),
526                // FIXME: the *implicit* debugger discovery makes it really difficult to control
527                // which {`cdb`, `gdb`, `lldb`} are used. These should **not** be implicitly
528                // discovered by `compiletest`; these should be explicit `bootstrap` configuration
529                // options that are passed to `compiletest`!
530                None => {
531                    configs.extend(debuggers::configure_cdb(&config));
532                    configs.extend(debuggers::configure_gdb(&config));
533                    configs.extend(debuggers::configure_lldb(&config));
534                }
535            }
536        }
537    } else {
538        configs.push(config.clone());
539    };
540
541    // Discover all of the tests in the test suite directory, and build a `CollectedTest`
542    // structure for each test (or each revision of a multi-revision test).
543    let mut tests = Vec::new();
544    for c in configs {
545        tests.extend(collect_and_make_tests(c));
546    }
547
548    tests.sort_by(|a, b| Ord::cmp(&a.desc.name, &b.desc.name));
549
550    // Delegate to the executor to filter and run the big list of test structures
551    // created during test discovery. When the executor decides to run a test,
552    // it will return control to the rest of compiletest by calling `runtest::run`.
553    let ok = executor::run_tests(&config, tests);
554
555    // Check the outcome reported by the executor.
556    if !ok {
557        // We want to report that the tests failed, but we also want to give
558        // some indication of just what tests we were running. Especially on
559        // CI, where there can be cross-compiled tests for a lot of
560        // architectures, without this critical information it can be quite
561        // easy to miss which tests failed, and as such fail to reproduce
562        // the failure locally.
563
564        let mut msg = String::from("Some tests failed in compiletest");
565        write!(msg, " suite={}", config.suite).unwrap();
566
567        if let Some(compare_mode) = config.compare_mode.as_ref() {
568            write!(msg, " compare_mode={}", compare_mode).unwrap();
569        }
570
571        if let Some(pass_mode) = config.force_pass_mode.as_ref() {
572            write!(msg, " pass_mode={}", pass_mode).unwrap();
573        }
574
575        write!(msg, " mode={}", config.mode).unwrap();
576        write!(msg, " host={}", config.host).unwrap();
577        write!(msg, " target={}", config.target).unwrap();
578
579        println!("{msg}");
580
581        std::process::exit(1);
582    }
583}
584
585/// Read-only context data used during test collection.
586struct TestCollectorCx {
587    config: Arc<Config>,
588    cache: DirectivesCache,
589    common_inputs_stamp: Stamp,
590    modified_tests: Vec<Utf8PathBuf>,
591}
592
593/// Mutable state used during test collection.
594struct TestCollector {
595    tests: Vec<CollectedTest>,
596    found_path_stems: HashSet<Utf8PathBuf>,
597    poisoned: bool,
598}
599
600impl TestCollector {
601    fn new() -> Self {
602        TestCollector { tests: vec![], found_path_stems: HashSet::new(), poisoned: false }
603    }
604
605    fn merge(&mut self, mut other: Self) {
606        self.tests.append(&mut other.tests);
607        self.found_path_stems.extend(other.found_path_stems);
608        self.poisoned |= other.poisoned;
609    }
610}
611
612/// Creates test structures for every test/revision in the test suite directory.
613///
614/// This always inspects _all_ test files in the suite (e.g. all 17k+ ui tests),
615/// regardless of whether any filters/tests were specified on the command-line,
616/// because filtering is handled later by code that was copied from libtest.
617///
618/// FIXME(Zalathar): Now that we no longer rely on libtest, try to overhaul
619/// test discovery to take into account the filters/tests specified on the
620/// command-line, instead of having to enumerate everything.
621fn collect_and_make_tests(config: Arc<Config>) -> Vec<CollectedTest> {
622    debug!("making tests from {}", config.src_test_suite_root);
623    let common_inputs_stamp = common_inputs_stamp(&config);
624    let modified_tests =
625        modified_tests(&config, &config.src_test_suite_root).unwrap_or_else(|err| {
626            fatal!("modified_tests: {}: {err}", config.src_test_suite_root);
627        });
628    let cache = DirectivesCache::load(&config);
629
630    let cx = TestCollectorCx { config, cache, common_inputs_stamp, modified_tests };
631    let collector = collect_tests_from_dir(&cx, &cx.config.src_test_suite_root, Utf8Path::new(""))
632        .unwrap_or_else(|reason| {
633            panic!("Could not read tests from {}: {reason}", cx.config.src_test_suite_root)
634        });
635
636    let TestCollector { tests, found_path_stems, poisoned } = collector;
637
638    if poisoned {
639        eprintln!();
640        panic!("there are errors in tests");
641    }
642
643    check_for_overlapping_test_paths(&found_path_stems);
644
645    tests
646}
647
648/// Returns the most recent last-modified timestamp from among the input files
649/// that are considered relevant to all tests (e.g. the compiler, std, and
650/// compiletest itself).
651///
652/// (Some of these inputs aren't actually relevant to _all_ tests, but they are
653/// common to some subset of tests, and are hopefully unlikely to be modified
654/// while working on other tests.)
655fn common_inputs_stamp(config: &Config) -> Stamp {
656    let src_root = &config.src_root;
657
658    let mut stamp = Stamp::from_path(&config.rustc_path);
659
660    // Relevant pretty printer files
661    let pretty_printer_files = [
662        "src/etc/rust_types.py",
663        "src/etc/gdb_load_rust_pretty_printers.py",
664        "src/etc/gdb_lookup.py",
665        "src/etc/gdb_providers.py",
666        "src/etc/lldb_batchmode.py",
667        "src/etc/lldb_lookup.py",
668        "src/etc/lldb_providers.py",
669    ];
670    for file in &pretty_printer_files {
671        let path = src_root.join(file);
672        stamp.add_path(&path);
673    }
674
675    stamp.add_dir(&src_root.join("src/etc/natvis"));
676
677    stamp.add_dir(&config.target_run_lib_path);
678
679    if let Some(ref rustdoc_path) = config.rustdoc_path {
680        stamp.add_path(&rustdoc_path);
681        stamp.add_path(&src_root.join("src/etc/htmldocck.py"));
682    }
683
684    // Re-run coverage tests if the `coverage-dump` tool was modified,
685    // because its output format might have changed.
686    if let Some(coverage_dump_path) = &config.coverage_dump_path {
687        stamp.add_path(coverage_dump_path)
688    }
689
690    stamp.add_dir(&src_root.join("src/tools/run-make-support"));
691
692    // Compiletest itself.
693    stamp.add_dir(&src_root.join("src/tools/compiletest"));
694
695    stamp
696}
697
698/// Returns a list of modified/untracked test files that should be run when
699/// the `--only-modified` flag is in use.
700///
701/// (Might be inaccurate in some cases.)
702fn modified_tests(config: &Config, dir: &Utf8Path) -> Result<Vec<Utf8PathBuf>, String> {
703    // If `--only-modified` wasn't passed, the list of modified tests won't be
704    // used for anything, so avoid some work and just return an empty list.
705    if !config.only_modified {
706        return Ok(vec![]);
707    }
708
709    let files = get_git_modified_files(
710        &config.git_config(),
711        Some(dir.as_std_path()),
712        &vec!["rs", "stderr", "fixed"],
713    )?;
714    // Add new test cases to the list, it will be convenient in daily development.
715    let untracked_files = get_git_untracked_files(Some(dir.as_std_path()))?.unwrap_or(vec![]);
716
717    let all_paths = [&files[..], &untracked_files[..]].concat();
718    let full_paths = {
719        let mut full_paths: Vec<Utf8PathBuf> = all_paths
720            .into_iter()
721            .map(|f| Utf8PathBuf::from(f).with_extension("").with_extension("rs"))
722            .filter_map(
723                |f| if Utf8Path::new(&f).exists() { f.canonicalize_utf8().ok() } else { None },
724            )
725            .collect();
726        full_paths.dedup();
727        full_paths.sort_unstable();
728        full_paths
729    };
730    Ok(full_paths)
731}
732
733/// Recursively scans a directory to find test files and create test structures
734/// that will be handed over to the executor.
735fn collect_tests_from_dir(
736    cx: &TestCollectorCx,
737    dir: &Utf8Path,
738    relative_dir_path: &Utf8Path,
739) -> io::Result<TestCollector> {
740    // Ignore directories that contain a file named `compiletest-ignore-dir`.
741    if dir.join("compiletest-ignore-dir").exists() {
742        return Ok(TestCollector::new());
743    }
744
745    let mut components = dir.components().rev();
746    if let Some(Utf8Component::Normal(last)) = components.next()
747        && let Some(("assembly" | "codegen", backend)) = last.split_once('-')
748        && let Some(Utf8Component::Normal(parent)) = components.next()
749        && parent == "tests"
750        && let Ok(backend) = CodegenBackend::try_from(backend)
751        && backend != cx.config.default_codegen_backend
752    {
753        // We ignore asm tests which don't match the current codegen backend.
754        warning!(
755            "Ignoring tests in `{dir}` because they don't match the configured codegen \
756             backend (`{}`)",
757            cx.config.default_codegen_backend.as_str(),
758        );
759        return Ok(TestCollector::new());
760    }
761
762    // For run-make tests, a "test file" is actually a directory that contains an `rmake.rs`.
763    if cx.config.mode == TestMode::RunMake {
764        let mut collector = TestCollector::new();
765        if dir.join("rmake.rs").exists() {
766            let paths = TestPaths {
767                file: dir.to_path_buf(),
768                relative_dir: relative_dir_path.parent().unwrap().to_path_buf(),
769            };
770            make_test(cx, &mut collector, &paths);
771            // This directory is a test, so don't try to find other tests inside it.
772            return Ok(collector);
773        }
774    }
775
776    // If we find a test foo/bar.rs, we have to build the
777    // output directory `$build/foo` so we can write
778    // `$build/foo/bar` into it. We do this *now* in this
779    // sequential loop because otherwise, if we do it in the
780    // tests themselves, they race for the privilege of
781    // creating the directories and sometimes fail randomly.
782    let build_dir = output_relative_path(&cx.config, relative_dir_path);
783    fs::create_dir_all(&build_dir).unwrap();
784
785    // Add each `.rs` file as a test, and recurse further on any
786    // subdirectories we find, except for `auxiliary` directories.
787    // FIXME: this walks full tests tree, even if we have something to ignore
788    // use walkdir/ignore like in tidy?
789    fs::read_dir(dir.as_std_path())?
790        .par_bridge()
791        .map(|file| {
792            let mut collector = TestCollector::new();
793            let file = file?;
794            let file_path = Utf8PathBuf::try_from(file.path()).unwrap();
795            let file_name = file_path.file_name().unwrap();
796
797            if is_test(file_name)
798                && (!cx.config.only_modified || cx.modified_tests.contains(&file_path))
799            {
800                // We found a test file, so create the corresponding test structures.
801                debug!(%file_path, "found test file");
802
803                // Record the stem of the test file, to check for overlaps later.
804                let rel_test_path = relative_dir_path.join(file_path.file_stem().unwrap());
805                collector.found_path_stems.insert(rel_test_path);
806
807                let paths =
808                    TestPaths { file: file_path, relative_dir: relative_dir_path.to_path_buf() };
809                make_test(cx, &mut collector, &paths);
810            } else if file_path.is_dir() {
811                // Recurse to find more tests in a subdirectory.
812                let relative_file_path = relative_dir_path.join(file_name);
813                if file_name != "auxiliary" {
814                    debug!(%file_path, "found directory");
815                    collector.merge(collect_tests_from_dir(cx, &file_path, &relative_file_path)?);
816                }
817            } else {
818                debug!(%file_path, "found other file/directory");
819            }
820            Ok(collector)
821        })
822        .reduce(
823            || Ok(TestCollector::new()),
824            |a, b| {
825                let mut a = a?;
826                a.merge(b?);
827                Ok(a)
828            },
829        )
830}
831
832/// Returns true if `file_name` looks like a proper test file name.
833fn is_test(file_name: &str) -> bool {
834    if !file_name.ends_with(".rs") {
835        return false;
836    }
837
838    // `.`, `#`, and `~` are common temp-file prefixes.
839    let invalid_prefixes = &[".", "#", "~"];
840    !invalid_prefixes.iter().any(|p| file_name.starts_with(p))
841}
842
843/// For a single test file, creates one or more test structures (one per revision) that can be
844/// handed over to the executor to run, possibly in parallel.
845fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &TestPaths) {
846    // For run-make tests, each "test file" is actually a _directory_ containing an `rmake.rs`. But
847    // for the purposes of directive parsing, we want to look at that recipe file, not the directory
848    // itself.
849    let test_path = if cx.config.mode == TestMode::RunMake {
850        testpaths.file.join("rmake.rs")
851    } else {
852        testpaths.file.clone()
853    };
854
855    // Scan the test file to discover its revisions, if any.
856    let file_contents =
857        fs::read_to_string(&test_path).expect("reading test file for directives should succeed");
858    let file_directives = FileDirectives::from_file_contents(&test_path, &file_contents);
859
860    if let Err(message) = directives::do_early_directives_check(cx.config.mode, &file_directives) {
861        // FIXME(Zalathar): Overhaul compiletest error handling so that we
862        // don't have to resort to ad-hoc panics everywhere.
863        panic!("directives check failed:\n{message}");
864    }
865    let early_props = EarlyProps::from_file_directives(&cx.config, &file_directives);
866
867    // Normally we create one structure per revision, with two exceptions:
868    // - If a test doesn't use revisions, create a dummy revision (None) so that
869    //   the test can still run.
870    // - Incremental tests inherently can't run their revisions in parallel, so
871    //   we treat them like non-revisioned tests here. Incremental revisions are
872    //   handled internally by `runtest::run` instead.
873    let revisions = if early_props.revisions.is_empty() || cx.config.mode == TestMode::Incremental {
874        vec![None]
875    } else {
876        early_props.revisions.iter().map(|r| Some(r.as_str())).collect()
877    };
878
879    // For each revision (or the sole dummy revision), create and append a
880    // `CollectedTest` that can be handed over to the test executor.
881    collector.tests.extend(revisions.into_iter().map(|revision| {
882        // Create a test name and description to hand over to the executor.
883        let (test_name, filterable_path) =
884            make_test_name_and_filterable_path(&cx.config, testpaths, revision);
885
886        // While scanning for ignore/only/needs directives, also collect aux
887        // paths for up-to-date checking.
888        let mut aux_props = AuxProps::default();
889
890        // Create a description struct for the test/revision.
891        // This is where `ignore-*`/`only-*`/`needs-*` directives are handled,
892        // because they historically needed to set the libtest ignored flag.
893        let mut desc = make_test_description(
894            &cx.config,
895            &cx.cache,
896            test_name,
897            &test_path,
898            &filterable_path,
899            &file_directives,
900            revision,
901            &mut collector.poisoned,
902            &mut aux_props,
903        );
904
905        // If a test's inputs haven't changed since the last time it ran,
906        // mark it as ignored so that the executor will skip it.
907        if !desc.ignore
908            && !cx.config.force_rerun
909            && is_up_to_date(cx, testpaths, &aux_props, revision)
910        {
911            desc.ignore = true;
912            // Keep this in sync with the "up-to-date" message detected by bootstrap.
913            // FIXME(Zalathar): Now that we are no longer tied to libtest, we could
914            // find a less fragile way to communicate this status to bootstrap.
915            desc.ignore_message = Some("up-to-date".into());
916        }
917
918        let config = Arc::clone(&cx.config);
919        let testpaths = testpaths.clone();
920        let revision = revision.map(str::to_owned);
921
922        CollectedTest { desc, config, testpaths, revision }
923    }));
924}
925
926/// The path of the `stamp` file that gets created or updated whenever a
927/// particular test completes successfully.
928fn stamp_file_path(config: &Config, testpaths: &TestPaths, revision: Option<&str>) -> Utf8PathBuf {
929    output_base_dir(config, testpaths, revision).join("stamp")
930}
931
932/// Returns a list of files that, if modified, would cause this test to no
933/// longer be up-to-date.
934///
935/// (Might be inaccurate in some cases.)
936fn files_related_to_test(
937    config: &Config,
938    testpaths: &TestPaths,
939    aux_props: &AuxProps,
940    revision: Option<&str>,
941) -> Vec<Utf8PathBuf> {
942    let mut related = vec![];
943
944    if testpaths.file.is_dir() {
945        // run-make tests use their individual directory
946        for entry in WalkDir::new(&testpaths.file) {
947            let path = entry.unwrap().into_path();
948            if path.is_file() {
949                related.push(Utf8PathBuf::try_from(path).unwrap());
950            }
951        }
952    } else {
953        related.push(testpaths.file.clone());
954    }
955
956    for aux in aux_props.all_aux_path_strings() {
957        // FIXME(Zalathar): Perform all `auxiliary` path resolution in one place.
958        // FIXME(Zalathar): This only finds auxiliary files used _directly_ by
959        // the test file; if a transitive auxiliary is modified, the test might
960        // be treated as "up-to-date" even though it should run.
961        let path = testpaths.file.parent().unwrap().join("auxiliary").join(aux);
962        related.push(path);
963    }
964
965    // UI test files.
966    for extension in UI_EXTENSIONS {
967        let path = expected_output_path(testpaths, revision, &config.compare_mode, extension);
968        related.push(path);
969    }
970
971    // `minicore.rs` test auxiliary: we need to make sure tests get rerun if this changes.
972    related.push(config.src_root.join("tests").join("auxiliary").join("minicore.rs"));
973
974    related
975}
976
977/// Checks whether a particular test/revision is "up-to-date", meaning that no
978/// relevant files/settings have changed since the last time the test succeeded.
979///
980/// (This is not very reliable in some circumstances, so the `--force-rerun`
981/// flag can be used to ignore up-to-date checking and always re-run tests.)
982fn is_up_to_date(
983    cx: &TestCollectorCx,
984    testpaths: &TestPaths,
985    aux_props: &AuxProps,
986    revision: Option<&str>,
987) -> bool {
988    let stamp_file_path = stamp_file_path(&cx.config, testpaths, revision);
989    // Check the config hash inside the stamp file.
990    let contents = match fs::read_to_string(&stamp_file_path) {
991        Ok(f) => f,
992        Err(ref e) if e.kind() == ErrorKind::InvalidData => panic!("Can't read stamp contents"),
993        // The test hasn't succeeded yet, so it is not up-to-date.
994        Err(_) => return false,
995    };
996    let expected_hash = runtest::compute_stamp_hash(&cx.config);
997    if contents != expected_hash {
998        // Some part of compiletest configuration has changed since the test
999        // last succeeded, so it is not up-to-date.
1000        return false;
1001    }
1002
1003    // Check the timestamp of the stamp file against the last modified time
1004    // of all files known to be relevant to the test.
1005    let mut inputs_stamp = cx.common_inputs_stamp.clone();
1006    for path in files_related_to_test(&cx.config, testpaths, aux_props, revision) {
1007        inputs_stamp.add_path(&path);
1008    }
1009
1010    // If no relevant files have been modified since the stamp file was last
1011    // written, the test is up-to-date.
1012    inputs_stamp < Stamp::from_path(&stamp_file_path)
1013}
1014
1015/// The maximum of a set of file-modified timestamps.
1016#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1017struct Stamp {
1018    time: SystemTime,
1019}
1020
1021impl Stamp {
1022    /// Creates a timestamp holding the last-modified time of the specified file.
1023    fn from_path(path: &Utf8Path) -> Self {
1024        let mut stamp = Stamp { time: SystemTime::UNIX_EPOCH };
1025        stamp.add_path(path);
1026        stamp
1027    }
1028
1029    /// Updates this timestamp to the last-modified time of the specified file,
1030    /// if it is later than the currently-stored timestamp.
1031    fn add_path(&mut self, path: &Utf8Path) {
1032        let modified = fs::metadata(path.as_std_path())
1033            .and_then(|metadata| metadata.modified())
1034            .unwrap_or(SystemTime::UNIX_EPOCH);
1035        self.time = self.time.max(modified);
1036    }
1037
1038    /// Updates this timestamp to the most recent last-modified time of all files
1039    /// recursively contained in the given directory, if it is later than the
1040    /// currently-stored timestamp.
1041    fn add_dir(&mut self, path: &Utf8Path) {
1042        let path = path.as_std_path();
1043        for entry in WalkDir::new(path) {
1044            let entry = entry.unwrap();
1045            if entry.file_type().is_file() {
1046                let modified = entry
1047                    .metadata()
1048                    .ok()
1049                    .and_then(|metadata| metadata.modified().ok())
1050                    .unwrap_or(SystemTime::UNIX_EPOCH);
1051                self.time = self.time.max(modified);
1052            }
1053        }
1054    }
1055}
1056
1057/// Creates a name for this test/revision that can be handed over to the executor.
1058fn make_test_name_and_filterable_path(
1059    config: &Config,
1060    testpaths: &TestPaths,
1061    revision: Option<&str>,
1062) -> (String, Utf8PathBuf) {
1063    // Print the name of the file, relative to the sources root.
1064    let path = testpaths.file.strip_prefix(&config.src_root).unwrap();
1065    let debugger = match config.debugger {
1066        Some(d) => format!("-{}", d),
1067        None => String::new(),
1068    };
1069    let mode_suffix = match config.compare_mode {
1070        Some(ref mode) => format!(" ({})", mode.to_str()),
1071        None => String::new(),
1072    };
1073
1074    let name = format!(
1075        "[{}{}{}] {}{}",
1076        config.mode,
1077        debugger,
1078        mode_suffix,
1079        path,
1080        revision.map_or("".to_string(), |rev| format!("#{}", rev))
1081    );
1082
1083    // `path` is the full path from the repo root like, `tests/ui/foo/bar.rs`.
1084    // Filtering is applied without the `tests/ui/` part, so strip that off.
1085    // First strip off "tests" to make sure we don't have some unexpected path.
1086    let mut filterable_path = path.strip_prefix("tests").unwrap().to_owned();
1087    // Now strip off e.g. "ui" or "run-make" component.
1088    filterable_path = filterable_path.components().skip(1).collect();
1089
1090    (name, filterable_path)
1091}
1092
1093/// Checks that test discovery didn't find any tests whose name stem is a prefix
1094/// of some other tests's name.
1095///
1096/// For example, suppose the test suite contains these two test files:
1097/// - `tests/rustdoc-html/primitive.rs`
1098/// - `tests/rustdoc-html/primitive/no_std.rs`
1099///
1100/// The test runner might put the output from those tests in these directories:
1101/// - `$build/test/rustdoc/primitive/`
1102/// - `$build/test/rustdoc/primitive/no_std/`
1103///
1104/// Because one output path is a subdirectory of the other, the two tests might
1105/// interfere with each other in unwanted ways, especially if the test runner
1106/// decides to delete test output directories to clean them between runs.
1107/// To avoid problems, we forbid test names from overlapping in this way.
1108///
1109/// See <https://github.com/rust-lang/rust/pull/109509> for more context.
1110fn check_for_overlapping_test_paths(found_path_stems: &HashSet<Utf8PathBuf>) {
1111    let mut collisions = Vec::new();
1112    for path in found_path_stems {
1113        for ancestor in path.ancestors().skip(1) {
1114            if found_path_stems.contains(ancestor) {
1115                collisions.push((path, ancestor));
1116            }
1117        }
1118    }
1119    if !collisions.is_empty() {
1120        collisions.sort();
1121        let collisions: String = collisions
1122            .into_iter()
1123            .map(|(path, check_parent)| format!("test {path} clashes with {check_parent}\n"))
1124            .collect();
1125        panic!(
1126            "{collisions}\n\
1127            Tests cannot have overlapping names. Make sure they use unique prefixes."
1128        );
1129    }
1130}
1131
1132fn early_config_check(config: &Config) {
1133    if !config.profiler_runtime && config.mode == TestMode::CoverageRun {
1134        let actioned = if config.bless { "blessed" } else { "checked" };
1135        warning!("profiler runtime is not available, so `.coverage` files won't be {actioned}");
1136        help!("try setting `profiler = true` in the `[build]` section of `bootstrap.toml`");
1137    }
1138
1139    // `RUST_TEST_NOCAPTURE` is a libtest env var, but we don't callout to libtest.
1140    if env::var("RUST_TEST_NOCAPTURE").is_ok() {
1141        warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead");
1142    }
1143}