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
47fn 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 .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 let cdb = matches.opt_str("cdb").map(Utf8PathBuf::from);
269 let cdb_version = cdb.as_deref().and_then(debuggers::query_cdb_version);
270 let gdb = matches.opt_str("gdb").map(Utf8PathBuf::from);
272 let gdb_version = gdb.as_deref().and_then(debuggers::query_gdb_version);
273 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 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 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 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 path.parent().unwrap().to_string()
321 } else {
322 f.to_string()
323 }
324 })
325 .collect::<Vec<_>>()
326 } else {
327 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 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
487fn run_tests(config: Arc<Config>) {
489 debug!(?config, "run_tests");
490
491 panic_hook::install_panic_hook();
492
493 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 unsafe {
510 raise_fd_limit::raise_fd_limit();
511 }
512 unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") };
517
518 let mut configs = Vec::new();
519 if let TestMode::DebugInfo = config.mode {
520 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 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 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 let ok = executor::run_tests(&config, tests);
554
555 if !ok {
557 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
585struct TestCollectorCx {
587 config: Arc<Config>,
588 cache: DirectivesCache,
589 common_inputs_stamp: Stamp,
590 modified_tests: Vec<Utf8PathBuf>,
591}
592
593struct 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
612fn 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
648fn 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 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 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 stamp.add_dir(&src_root.join("src/tools/compiletest"));
694
695 stamp
696}
697
698fn modified_tests(config: &Config, dir: &Utf8Path) -> Result<Vec<Utf8PathBuf>, String> {
703 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 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
733fn collect_tests_from_dir(
736 cx: &TestCollectorCx,
737 dir: &Utf8Path,
738 relative_dir_path: &Utf8Path,
739) -> io::Result<TestCollector> {
740 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 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 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 return Ok(collector);
773 }
774 }
775
776 let build_dir = output_relative_path(&cx.config, relative_dir_path);
783 fs::create_dir_all(&build_dir).unwrap();
784
785 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 debug!(%file_path, "found test file");
802
803 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 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
832fn is_test(file_name: &str) -> bool {
834 if !file_name.ends_with(".rs") {
835 return false;
836 }
837
838 let invalid_prefixes = &[".", "#", "~"];
840 !invalid_prefixes.iter().any(|p| file_name.starts_with(p))
841}
842
843fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &TestPaths) {
846 let test_path = if cx.config.mode == TestMode::RunMake {
850 testpaths.file.join("rmake.rs")
851 } else {
852 testpaths.file.clone()
853 };
854
855 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 panic!("directives check failed:\n{message}");
864 }
865 let early_props = EarlyProps::from_file_directives(&cx.config, &file_directives);
866
867 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 collector.tests.extend(revisions.into_iter().map(|revision| {
882 let (test_name, filterable_path) =
884 make_test_name_and_filterable_path(&cx.config, testpaths, revision);
885
886 let mut aux_props = AuxProps::default();
889
890 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 !desc.ignore
908 && !cx.config.force_rerun
909 && is_up_to_date(cx, testpaths, &aux_props, revision)
910 {
911 desc.ignore = true;
912 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
926fn stamp_file_path(config: &Config, testpaths: &TestPaths, revision: Option<&str>) -> Utf8PathBuf {
929 output_base_dir(config, testpaths, revision).join("stamp")
930}
931
932fn 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 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 let path = testpaths.file.parent().unwrap().join("auxiliary").join(aux);
962 related.push(path);
963 }
964
965 for extension in UI_EXTENSIONS {
967 let path = expected_output_path(testpaths, revision, &config.compare_mode, extension);
968 related.push(path);
969 }
970
971 related.push(config.src_root.join("tests").join("auxiliary").join("minicore.rs"));
973
974 related
975}
976
977fn 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 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 Err(_) => return false,
995 };
996 let expected_hash = runtest::compute_stamp_hash(&cx.config);
997 if contents != expected_hash {
998 return false;
1001 }
1002
1003 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 inputs_stamp < Stamp::from_path(&stamp_file_path)
1013}
1014
1015#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1017struct Stamp {
1018 time: SystemTime,
1019}
1020
1021impl Stamp {
1022 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 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 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
1057fn make_test_name_and_filterable_path(
1059 config: &Config,
1060 testpaths: &TestPaths,
1061 revision: Option<&str>,
1062) -> (String, Utf8PathBuf) {
1063 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 let mut filterable_path = path.strip_prefix("tests").unwrap().to_owned();
1087 filterable_path = filterable_path.components().skip(1).collect();
1089
1090 (name, filterable_path)
1091}
1092
1093fn 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 if env::var("RUST_TEST_NOCAPTURE").is_ok() {
1141 warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead");
1142 }
1143}