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
24pub(crate) fn discover_tests(config: &Arc<Config>) -> Vec<CollectedTest> {
26 debug!(?config, "run_tests");
27
28 let ignore_tests = config.mode == TestMode::DebugInfo && config.target.contains("emscripten");
30
31 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
43struct TestCollectorCx {
45 config: Arc<Config>,
46 cache: DirectivesCache,
47 common_inputs_stamp: Stamp,
48 modified_tests: Vec<Utf8PathBuf>,
49}
50
51struct 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
70fn 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
106fn 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 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 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 stamp.add_dir(&src_root.join("src/tools/compiletest"));
152
153 stamp
154}
155
156fn modified_tests(config: &Config, dir: &Utf8Path) -> Result<Vec<Utf8PathBuf>, String> {
161 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 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
191fn collect_tests_from_dir(
194 cx: &TestCollectorCx,
195 dir: &Utf8Path,
196 relative_dir_path: &Utf8Path,
197) -> io::Result<TestCollector> {
198 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 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 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 return Ok(collector);
231 }
232 }
233
234 let build_dir = output_relative_path(&cx.config, relative_dir_path);
241 fs::create_dir_all(&build_dir).unwrap();
242
243 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 debug!(%file_path, "found test file");
260
261 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 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
290pub(crate) fn is_test(file_name: &str) -> bool {
292 if !file_name.ends_with(".rs") {
293 return false;
294 }
295
296 let invalid_prefixes = &[".", "#", "~"];
298 !invalid_prefixes.iter().any(|p| file_name.starts_with(p))
299}
300
301fn make_test(cx: &TestCollectorCx, collector: &mut TestCollector, testpaths: &TestPaths) {
304 let test_path = if cx.config.mode == TestMode::RunMake {
308 testpaths.file.join("rmake.rs")
309 } else {
310 testpaths.file.clone()
311 };
312
313 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 panic!("directives check failed:\n{message}");
322 }
323 let early_props = EarlyProps::from_file_directives(&cx.config, &file_directives);
324
325 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 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 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 let (test_name, filterable_path) =
354 make_test_name_and_filterable_path(&cx.config, testpaths, &variant);
355
356 let mut aux_props = AuxProps::default();
359
360 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 !desc.is_ignored()
378 && !cx.config.force_rerun
379 && is_up_to_date(cx, testpaths, &aux_props, &variant)
380 {
381 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
395pub(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
405fn 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 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 let path = testpaths.file.parent().unwrap().join("auxiliary").join(aux);
435 related.push(path);
436 }
437
438 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 related.push(config.src_root.join("tests").join("auxiliary").join("minicore.rs"));
447
448 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
467fn 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 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 Err(_) => return false,
485 };
486 let expected_hash = runtest::compute_stamp_hash(&cx.config, variant);
487 if contents != expected_hash {
488 return false;
491 }
492
493 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 inputs_stamp < Stamp::from_path(&stamp_file_path)
503}
504
505#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
507struct Stamp {
508 time: SystemTime,
509}
510
511impl Stamp {
512 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 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 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
547fn make_test_name_and_filterable_path(
549 config: &Config,
550 testpaths: &TestPaths,
551 variant: &TestVariant,
552) -> (String, Utf8PathBuf) {
553 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 let mut filterable_path = path.strip_prefix("tests").unwrap().to_owned();
577 filterable_path = filterable_path.components().skip(1).collect();
579
580 (name, filterable_path)
581}
582
583fn 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}