Skip to main content

compiletest/
discovery.rs

1use core::panic;
2use std::collections::HashSet;
3use std::io::{self, ErrorKind};
4use std::sync::Arc;
5use std::time::SystemTime;
6use std::{fs, vec};
7
8use build_helper::git::{get_git_modified_files, get_git_untracked_files};
9use camino::{Utf8Component, Utf8Path, Utf8PathBuf};
10use rayon::iter::{ParallelBridge, ParallelIterator};
11use tracing::debug;
12use walkdir::WalkDir;
13
14use crate::common::{
15    CodegenBackend, Config, Debugger, TestMode, TestPaths, UI_EXTENSIONS, expected_output_path,
16    output_base_dir, output_relative_path,
17};
18use crate::directives::{
19    self, AuxProps, DirectivesCache, EarlyProps, FileDirectives, make_test_description,
20};
21use crate::executor::{CollectedTest, TestVariant};
22use crate::{fatal, runtest, warning};
23
24/// Called by `main` after the config has been parsed.
25pub(crate) fn discover_tests(config: &Arc<Config>) -> Vec<CollectedTest> {
26    debug!(?config, "run_tests");
27
28    // Debugging emscripten code doesn't make sense today
29    let ignore_tests = config.mode == TestMode::DebugInfo && config.target.contains("emscripten");
30
31    // Discover all of the tests in the test suite directory, and build a `CollectedTest`
32    // structure for each test (or each revision of a multi-revision test).
33    let mut tests = Vec::new();
34    if !ignore_tests {
35        tests.extend(collect_and_make_tests(config.clone()));
36    }
37
38    tests.sort_by(|a, b| Ord::cmp(&a.desc.name, &b.desc.name));
39
40    tests
41}
42
43/// Read-only context data used during test collection.
44struct TestCollectorCx {
45    config: Arc<Config>,
46    cache: DirectivesCache,
47    common_inputs_stamp: Stamp,
48    modified_tests: Vec<Utf8PathBuf>,
49}
50
51/// Mutable state used during test collection.
52struct TestCollector {
53    tests: Vec<CollectedTest>,
54    found_path_stems: HashSet<Utf8PathBuf>,
55    poisoned: bool,
56}
57
58impl TestCollector {
59    fn new() -> Self {
60        TestCollector { tests: vec![], found_path_stems: HashSet::new(), poisoned: false }
61    }
62
63    fn merge(&mut self, mut other: Self) {
64        self.tests.append(&mut other.tests);
65        self.found_path_stems.extend(other.found_path_stems);
66        self.poisoned |= other.poisoned;
67    }
68}
69
70/// Creates test structures for every test/revision in the test suite directory.
71///
72/// This always inspects _all_ test files in the suite (e.g. all 17k+ ui tests),
73/// regardless of whether any filters/tests were specified on the command-line,
74/// because filtering is handled later by code that was copied from libtest.
75///
76/// FIXME(Zalathar): Now that we no longer rely on libtest, try to overhaul
77/// test discovery to take into account the filters/tests specified on the
78/// command-line, instead of having to enumerate everything.
79fn collect_and_make_tests(config: Arc<Config>) -> Vec<CollectedTest> {
80    debug!("making tests from {}", config.src_test_suite_root);
81    let common_inputs_stamp = common_inputs_stamp(&config);
82    let modified_tests =
83        modified_tests(&config, &config.src_test_suite_root).unwrap_or_else(|err| {
84            fatal!("modified_tests: {}: {err}", config.src_test_suite_root);
85        });
86    let cache = DirectivesCache::load(&config);
87
88    let cx = TestCollectorCx { config, cache, common_inputs_stamp, modified_tests };
89    let collector = collect_tests_from_dir(&cx, &cx.config.src_test_suite_root, Utf8Path::new(""))
90        .unwrap_or_else(|reason| {
91            panic!("Could not read tests from {}: {reason}", cx.config.src_test_suite_root)
92        });
93
94    let TestCollector { tests, found_path_stems, poisoned } = collector;
95
96    if poisoned {
97        eprintln!();
98        panic!("there are errors in tests");
99    }
100
101    check_for_overlapping_test_paths(&found_path_stems);
102
103    tests
104}
105
106/// Returns the most recent last-modified timestamp from among the input files
107/// that are considered relevant to all tests (e.g. the compiler, std, and
108/// compiletest itself).
109///
110/// (Some of these inputs aren't actually relevant to _all_ tests, but they are
111/// common to some subset of tests, and are hopefully unlikely to be modified
112/// while working on other tests.)
113fn common_inputs_stamp(config: &Config) -> Stamp {
114    let src_root = &config.src_root;
115
116    let mut stamp = Stamp::from_path(&config.rustc_path);
117
118    // Relevant pretty printer files
119    let pretty_printer_files = [
120        "src/etc/rust_types.py",
121        "src/etc/gdb_load_rust_pretty_printers.py",
122        "src/etc/gdb_lookup.py",
123        "src/etc/gdb_providers.py",
124        "src/etc/lldb_lookup.py",
125        "src/etc/lldb_providers.py",
126    ];
127    for file in &pretty_printer_files {
128        let path = src_root.join(file);
129        stamp.add_path(&path);
130    }
131
132    stamp.add_dir(&src_root.join("src/etc/debugger_tester"));
133    stamp.add_dir(&src_root.join("src/etc/natvis"));
134
135    stamp.add_dir(&config.target_run_lib_path);
136
137    if let Some(ref rustdoc_path) = config.rustdoc_path {
138        stamp.add_path(&rustdoc_path);
139        stamp.add_path(&src_root.join("src/etc/htmldocck.py"));
140    }
141
142    // Re-run coverage tests if the `coverage-dump` tool was modified,
143    // because its output format might have changed.
144    if let Some(coverage_dump_path) = &config.coverage_dump_path {
145        stamp.add_path(coverage_dump_path)
146    }
147
148    stamp.add_dir(&src_root.join("src/tools/run-make-support"));
149
150    // Compiletest itself.
151    stamp.add_dir(&src_root.join("src/tools/compiletest"));
152
153    stamp
154}
155
156/// Returns a list of modified/untracked test files that should be run when
157/// the `--only-modified` flag is in use.
158///
159/// (Might be inaccurate in some cases.)
160fn modified_tests(config: &Config, dir: &Utf8Path) -> Result<Vec<Utf8PathBuf>, String> {
161    // If `--only-modified` wasn't passed, the list of modified tests won't be
162    // used for anything, so avoid some work and just return an empty list.
163    if !config.only_modified {
164        return Ok(vec![]);
165    }
166
167    let files = get_git_modified_files(
168        &config.git_config(),
169        Some(dir.as_std_path()),
170        &vec!["rs", "stderr", "fixed"],
171    )?;
172    // Add new test cases to the list, it will be convenient in daily development.
173    let untracked_files = get_git_untracked_files(Some(dir.as_std_path()))?.unwrap_or(vec![]);
174
175    let all_paths = [&files[..], &untracked_files[..]].concat();
176    let full_paths = {
177        let mut full_paths: Vec<Utf8PathBuf> = all_paths
178            .into_iter()
179            .map(|f| Utf8PathBuf::from(f).with_extension("").with_extension("rs"))
180            .filter_map(
181                |f| if Utf8Path::new(&f).exists() { f.canonicalize_utf8().ok() } else { None },
182            )
183            .collect();
184        full_paths.dedup();
185        full_paths.sort_unstable();
186        full_paths
187    };
188    Ok(full_paths)
189}
190
191/// Recursively scans a directory to find test files and create test structures
192/// that will be handed over to the executor.
193fn collect_tests_from_dir(
194    cx: &TestCollectorCx,
195    dir: &Utf8Path,
196    relative_dir_path: &Utf8Path,
197) -> io::Result<TestCollector> {
198    // Ignore directories that contain a file named `compiletest-ignore-dir`.
199    if dir.join("compiletest-ignore-dir").exists() {
200        return Ok(TestCollector::new());
201    }
202
203    let mut components = dir.components().rev();
204    if let Some(Utf8Component::Normal(last)) = components.next()
205        && let Some(("assembly" | "codegen", backend)) = last.split_once('-')
206        && let Some(Utf8Component::Normal(parent)) = components.next()
207        && parent == "tests"
208        && let Ok(backend) = backend.parse::<CodegenBackend>()
209        && backend != cx.config.default_codegen_backend
210    {
211        // We ignore asm tests which don't match the current codegen backend.
212        warning!(
213            "Ignoring tests in `{dir}` because they don't match the configured codegen \
214             backend (`{}`)",
215            cx.config.default_codegen_backend.as_str(),
216        );
217        return Ok(TestCollector::new());
218    }
219
220    // For run-make tests, a "test file" is actually a directory that contains an `rmake.rs`.
221    if cx.config.mode == TestMode::RunMake {
222        let mut collector = TestCollector::new();
223        if dir.join("rmake.rs").exists() {
224            let paths = TestPaths {
225                file: dir.to_path_buf(),
226                relative_dir: relative_dir_path.parent().unwrap().to_path_buf(),
227            };
228            make_test(cx, &mut collector, &paths);
229            // This directory is a test, so don't try to find other tests inside it.
230            return Ok(collector);
231        }
232    }
233
234    // If we find a test foo/bar.rs, we have to build the
235    // output directory `$build/foo` so we can write
236    // `$build/foo/bar` into it. We do this *now* in this
237    // sequential loop because otherwise, if we do it in the
238    // tests themselves, they race for the privilege of
239    // creating the directories and sometimes fail randomly.
240    let build_dir = output_relative_path(&cx.config, relative_dir_path);
241    fs::create_dir_all(&build_dir).unwrap();
242
243    // Add each `.rs` file as a test, and recurse further on any
244    // subdirectories we find, except for `auxiliary` directories.
245    // FIXME: this walks full tests tree, even if we have something to ignore
246    // use walkdir/ignore like in tidy?
247    fs::read_dir(dir.as_std_path())?
248        .par_bridge()
249        .map(|file| {
250            let mut collector = TestCollector::new();
251            let file = file?;
252            let file_path = Utf8PathBuf::try_from(file.path()).unwrap();
253            let file_name = file_path.file_name().unwrap();
254
255            if is_test(file_name)
256                && (!cx.config.only_modified || cx.modified_tests.contains(&file_path))
257            {
258                // We found a test file, so create the corresponding test structures.
259                debug!(%file_path, "found test file");
260
261                // Record the stem of the test file, to check for overlaps later.
262                let rel_test_path = relative_dir_path.join(file_path.file_stem().unwrap());
263                collector.found_path_stems.insert(rel_test_path);
264
265                let paths =
266                    TestPaths { file: file_path, relative_dir: relative_dir_path.to_path_buf() };
267                make_test(cx, &mut collector, &paths);
268            } else if file_path.is_dir() {
269                // Recurse to find more tests in a subdirectory.
270                let relative_file_path = relative_dir_path.join(file_name);
271                if file_name != "auxiliary" {
272                    debug!(%file_path, "found directory");
273                    collector.merge(collect_tests_from_dir(cx, &file_path, &relative_file_path)?);
274                }
275            } else {
276                debug!(%file_path, "found other file/directory");
277            }
278            Ok(collector)
279        })
280        .reduce(
281            || Ok(TestCollector::new()),
282            |a, b| {
283                let mut a = a?;
284                a.merge(b?);
285                Ok(a)
286            },
287        )
288}
289
290/// Returns true if `file_name` looks like a proper test file name.
291pub(crate) fn is_test(file_name: &str) -> bool {
292    if !file_name.ends_with(".rs") {
293        return false;
294    }
295
296    // `.`, `#`, and `~` are common temp-file prefixes.
297    let invalid_prefixes = &[".", "#", "~"];
298    !invalid_prefixes.iter().any(|p| file_name.starts_with(p))
299}
300
301/// For a single test file, creates one or more test structures (one per revision) that can be
302/// handed over to the executor to run, possibly in parallel.
303fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &TestPaths) {
304    // For run-make tests, each "test file" is actually a _directory_ containing an `rmake.rs`. But
305    // for the purposes of directive parsing, we want to look at that recipe file, not the directory
306    // itself.
307    let test_path = if cx.config.mode == TestMode::RunMake {
308        testpaths.file.join("rmake.rs")
309    } else {
310        testpaths.file.clone()
311    };
312
313    // Scan the test file to discover its revisions, if any.
314    let file_contents =
315        fs::read_to_string(&test_path).expect("reading test file for directives should succeed");
316    let file_directives = FileDirectives::from_file_contents(&test_path, &file_contents);
317
318    if let Err(message) = directives::do_early_directives_check(cx.config.mode, &file_directives) {
319        // FIXME(Zalathar): Overhaul compiletest error handling so that we
320        // don't have to resort to ad-hoc panics everywhere.
321        panic!("directives check failed:\n{message}");
322    }
323    let early_props = EarlyProps::from_file_directives(&cx.config, &file_directives);
324
325    // Normally we create one structure per revision, with two exceptions:
326    // - If a test doesn't use revisions, create a dummy revision (None) so that
327    //   the test can still run.
328    // - Incremental tests inherently can't run their revisions in parallel, so
329    //   we treat them like non-revisioned tests here. Incremental revisions are
330    //   handled internally by `runtest::run` instead.
331    let revisions = if early_props.revisions.is_empty() || cx.config.mode == TestMode::Incremental {
332        vec![None]
333    } else {
334        early_props.revisions.iter().map(|r| Some(r.as_str())).collect()
335    };
336
337    // For debuginfo tests, we have to run them once for each debugger.
338    // We thus create a cartesian product of each revision and each supported debugger here.
339    let debuggers = if cx.config.mode == TestMode::DebugInfo {
340        vec![Some(Debugger::Cdb), Some(Debugger::Gdb), Some(Debugger::Lldb)]
341    } else {
342        vec![None]
343    };
344
345    // For each revision (or the sole dummy revision) and each debugger, create and append a
346    // `CollectedTest` that can be handed over to the test executor.
347    for debugger in debuggers {
348        collector.tests.extend(revisions.iter().map(|&revision| {
349            let revision = revision.map(str::to_owned);
350            let variant = TestVariant { revision, debugger };
351
352            // Create a test name and description to hand over to the executor.
353            let (test_name, filterable_path) =
354                make_test_name_and_filterable_path(&cx.config, testpaths, &variant);
355
356            // While scanning for ignore/only/needs directives, also collect aux
357            // paths for up-to-date checking.
358            let mut aux_props = AuxProps::default();
359
360            // Create a description struct for the test/revision.
361            // This is where `ignore-*`/`only-*`/`needs-*` directives are handled,
362            // because they historically needed to set the libtest ignored flag.
363            let mut desc = make_test_description(
364                &cx.config,
365                &cx.cache,
366                test_name,
367                &test_path,
368                &filterable_path,
369                &file_directives,
370                &variant,
371                &mut collector.poisoned,
372                &mut aux_props,
373            );
374
375            // If a test's inputs haven't changed since the last time it ran,
376            // mark it as ignored so that the executor will skip it.
377            if !desc.is_ignored()
378                && !cx.config.force_rerun
379                && is_up_to_date(cx, testpaths, &aux_props, &variant)
380            {
381                // Keep this in sync with the "up-to-date" message detected by bootstrap.
382                // FIXME(Zalathar): Now that we are no longer tied to libtest, we could
383                // find a less fragile way to communicate this status to bootstrap.
384                desc.ignore_message = Some("up-to-date".into());
385            }
386
387            let config = Arc::clone(&cx.config);
388            let testpaths = testpaths.clone();
389
390            CollectedTest { desc, config, testpaths, variant }
391        }));
392    }
393}
394
395/// The path of the `stamp` file that gets created or updated whenever a
396/// particular test completes successfully.
397pub(crate) fn stamp_file_path(
398    config: &Config,
399    testpaths: &TestPaths,
400    variant: &TestVariant,
401) -> Utf8PathBuf {
402    output_base_dir(config, testpaths, variant).join("stamp")
403}
404
405/// Returns a list of files that, if modified, would cause this test to no
406/// longer be up-to-date.
407///
408/// (Might be inaccurate in some cases.)
409fn files_related_to_test(
410    config: &Config,
411    testpaths: &TestPaths,
412    aux_props: &AuxProps,
413    variant: &TestVariant,
414) -> Vec<Utf8PathBuf> {
415    let mut related = vec![];
416
417    if testpaths.file.is_dir() {
418        // run-make tests use their individual directory
419        for entry in WalkDir::new(&testpaths.file) {
420            let path = entry.unwrap().into_path();
421            if path.is_file() {
422                related.push(Utf8PathBuf::try_from(path).unwrap());
423            }
424        }
425    } else {
426        related.push(testpaths.file.clone());
427    }
428
429    for aux in aux_props.all_aux_path_strings() {
430        // FIXME(Zalathar): Perform all `auxiliary` path resolution in one place.
431        // FIXME(Zalathar): This only finds auxiliary files used _directly_ by
432        // the test file; if a transitive auxiliary is modified, the test might
433        // be treated as "up-to-date" even though it should run.
434        let path = testpaths.file.parent().unwrap().join("auxiliary").join(aux);
435        related.push(path);
436    }
437
438    // UI test files.
439    for extension in UI_EXTENSIONS {
440        let path =
441            expected_output_path(testpaths, variant.revision(), &config.compare_mode, extension);
442        related.push(path);
443    }
444
445    // `minicore.rs` test auxiliary: we need to make sure tests get rerun if this changes.
446    related.push(config.src_root.join("tests").join("auxiliary").join("minicore.rs"));
447
448    // `tests/debuginfo` blessed files
449    match variant.debugger {
450        Some(debugger @ Debugger::Lldb | debugger @ Debugger::Gdb) => {
451            let bless_path: Utf8PathBuf =
452                testpaths.file.parent().unwrap().join(format!("{}_input", debugger.to_str()));
453            if bless_path.is_dir() {
454                related.extend(
455                    WalkDir::new(bless_path)
456                        .into_iter()
457                        .map(|entry| Utf8PathBuf::from(entry.unwrap().path().to_str().unwrap())),
458                );
459            }
460        }
461        Some(Debugger::Cdb) | None => {}
462    }
463
464    related
465}
466
467/// Checks whether a particular test/revision is "up-to-date", meaning that no
468/// relevant files/settings have changed since the last time the test succeeded.
469///
470/// (This is not very reliable in some circumstances, so the `--force-rerun`
471/// flag can be used to ignore up-to-date checking and always re-run tests.)
472fn is_up_to_date(
473    cx: &TestCollectorCx,
474    testpaths: &TestPaths,
475    aux_props: &AuxProps,
476    variant: &TestVariant,
477) -> bool {
478    let stamp_file_path = stamp_file_path(&cx.config, testpaths, variant);
479    // Check the config hash inside the stamp file.
480    let contents = match fs::read_to_string(&stamp_file_path) {
481        Ok(f) => f,
482        Err(ref e) if e.kind() == ErrorKind::InvalidData => panic!("Can't read stamp contents"),
483        // The test hasn't succeeded yet, so it is not up-to-date.
484        Err(_) => return false,
485    };
486    let expected_hash = runtest::compute_stamp_hash(&cx.config, variant);
487    if contents != expected_hash {
488        // Some part of compiletest configuration has changed since the test
489        // last succeeded, so it is not up-to-date.
490        return false;
491    }
492
493    // Check the timestamp of the stamp file against the last modified time
494    // of all files known to be relevant to the test.
495    let mut inputs_stamp = cx.common_inputs_stamp.clone();
496    for path in files_related_to_test(&cx.config, testpaths, aux_props, variant) {
497        inputs_stamp.add_path(&path);
498    }
499
500    // If no relevant files have been modified since the stamp file was last
501    // written, the test is up-to-date.
502    inputs_stamp < Stamp::from_path(&stamp_file_path)
503}
504
505/// The maximum of a set of file-modified timestamps.
506#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
507struct Stamp {
508    time: SystemTime,
509}
510
511impl Stamp {
512    /// Creates a timestamp holding the last-modified time of the specified file.
513    fn from_path(path: &Utf8Path) -> Self {
514        let mut stamp = Stamp { time: SystemTime::UNIX_EPOCH };
515        stamp.add_path(path);
516        stamp
517    }
518
519    /// Updates this timestamp to the last-modified time of the specified file,
520    /// if it is later than the currently-stored timestamp.
521    fn add_path(&mut self, path: &Utf8Path) {
522        let modified = fs::metadata(path.as_std_path())
523            .and_then(|metadata| metadata.modified())
524            .unwrap_or(SystemTime::UNIX_EPOCH);
525        self.time = self.time.max(modified);
526    }
527
528    /// Updates this timestamp to the most recent last-modified time of all files
529    /// recursively contained in the given directory, if it is later than the
530    /// currently-stored timestamp.
531    fn add_dir(&mut self, path: &Utf8Path) {
532        let path = path.as_std_path();
533        for entry in WalkDir::new(path) {
534            let entry = entry.unwrap();
535            if entry.file_type().is_file() {
536                let modified = entry
537                    .metadata()
538                    .ok()
539                    .and_then(|metadata| metadata.modified().ok())
540                    .unwrap_or(SystemTime::UNIX_EPOCH);
541                self.time = self.time.max(modified);
542            }
543        }
544    }
545}
546
547/// Creates a name for this test/revision that can be handed over to the executor.
548fn make_test_name_and_filterable_path(
549    config: &Config,
550    testpaths: &TestPaths,
551    variant: &TestVariant,
552) -> (String, Utf8PathBuf) {
553    // Print the name of the file, relative to the sources root.
554    let path = testpaths.file.strip_prefix(&config.src_root).unwrap();
555    let debugger = match variant.debugger.as_ref() {
556        Some(d) => format!("-{d}"),
557        None => String::new(),
558    };
559    let mode_suffix = match config.compare_mode {
560        Some(ref mode) => format!(" ({})", mode.to_str()),
561        None => String::new(),
562    };
563
564    let name = format!(
565        "[{}{}{}] {}{}",
566        config.mode,
567        debugger,
568        mode_suffix,
569        path,
570        variant.revision().map_or("".to_string(), |rev| format!("#{}", rev))
571    );
572
573    // `path` is the full path from the repo root like, `tests/ui/foo/bar.rs`.
574    // Filtering is applied without the `tests/ui/` part, so strip that off.
575    // First strip off "tests" to make sure we don't have some unexpected path.
576    let mut filterable_path = path.strip_prefix("tests").unwrap().to_owned();
577    // Now strip off e.g. "ui" or "run-make" component.
578    filterable_path = filterable_path.components().skip(1).collect();
579
580    (name, filterable_path)
581}
582
583/// Checks that test discovery didn't find any tests whose name stem is a prefix
584/// of some other tests's name.
585///
586/// For example, suppose the test suite contains these two test files:
587/// - `tests/rustdoc-html/primitive.rs`
588/// - `tests/rustdoc-html/primitive/no_std.rs`
589///
590/// The test runner might put the output from those tests in these directories:
591/// - `$build/test/rustdoc/primitive/`
592/// - `$build/test/rustdoc/primitive/no_std/`
593///
594/// Because one output path is a subdirectory of the other, the two tests might
595/// interfere with each other in unwanted ways, especially if the test runner
596/// decides to delete test output directories to clean them between runs.
597/// To avoid problems, we forbid test names from overlapping in this way.
598///
599/// See <https://github.com/rust-lang/rust/pull/109509> for more context.
600fn check_for_overlapping_test_paths(found_path_stems: &HashSet<Utf8PathBuf>) {
601    let mut collisions = Vec::new();
602    for path in found_path_stems {
603        for ancestor in path.ancestors().skip(1) {
604            if found_path_stems.contains(ancestor) {
605                collisions.push((path, ancestor));
606            }
607        }
608    }
609    if !collisions.is_empty() {
610        collisions.sort();
611        let collisions: String = collisions
612            .into_iter()
613            .map(|(path, check_parent)| format!("test {path} clashes with {check_parent}\n"))
614            .collect();
615        panic!(
616            "{collisions}\n\
617            Tests cannot have overlapping names. Make sure they use unique prefixes."
618        );
619    }
620}