1 #![allow(clippy::enum_variant_names, clippy::useless_format, clippy::too_many_arguments)]
3 use std::collections::VecDeque;
5 use std::path::{Path, PathBuf};
6 use std::process::{Command, ExitStatus};
7 use std::sync::atomic::{AtomicUsize, Ordering};
11 use comments::ErrorMatch;
13 use rustc_stderr::{Level, Message};
15 use crate::comments::{Comments, Condition};
24 /// Arguments passed to the binary that is executed.
25 pub args: Vec<String>,
26 /// `None` to run on the host, otherwise a target triple
27 pub target: Option<String>,
28 /// Filters applied to stderr output before processing it
29 pub stderr_filters: Filter,
30 /// Filters applied to stdout output before processing it
31 pub stdout_filters: Filter,
32 /// The folder in which to start searching for .rs files
33 pub root_dir: PathBuf,
36 pub output_conflict_handling: OutputConflictHandling,
37 /// Only run tests with one of these strings in their path/name
38 pub path_filter: Vec<String>,
42 pub enum OutputConflictHandling {
43 /// The default: emit a diff of the expected/actual output.
45 /// Ignore mismatches in the stderr/stdout files.
47 /// Instead of erroring if the stderr/stdout differs from the expected
48 /// automatically replace it with the found output (after applying filters).
52 pub type Filter = Vec<(Regex, &'static str)>;
54 pub fn run_tests(config: Config) {
55 eprintln!(" Compiler flags: {:?}", config.args);
57 // Get the triple with which to run the tests
58 let target = config.target.clone().unwrap_or_else(|| config.get_host());
60 // A channel for files to process
61 let (submit, receive) = crossbeam::channel::unbounded();
63 // Some statistics and failure reports.
64 let failures = Mutex::new(vec![]);
65 let succeeded = AtomicUsize::default();
66 let ignored = AtomicUsize::default();
67 let filtered = AtomicUsize::default();
69 crossbeam::scope(|s| {
70 // Create a thread that is in charge of walking the directory and submitting jobs.
71 // It closes the channel when it is done.
73 let mut todo = VecDeque::new();
74 todo.push_back(config.root_dir.clone());
75 while let Some(path) = todo.pop_front() {
77 // Enqueue everything inside this directory.
78 // We want it sorted, to have some control over scheduling of slow tests.
80 std::fs::read_dir(path).unwrap().collect::<Result<Vec<_>, _>>().unwrap();
81 entries.sort_by_key(|e| e.file_name());
82 for entry in entries {
83 todo.push_back(entry.path());
85 } else if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
86 // Forward .rs files to the test workers.
87 submit.send(path).unwrap();
90 // There will be no more jobs. This signals the workers to quit.
91 // (This also ensures `submit` is moved into this closure.)
95 // Create N worker threads that receive files to test.
96 for _ in 0..std::thread::available_parallelism().unwrap().get() {
98 for path in &receive {
99 if !config.path_filter.is_empty() {
100 let path_display = path.display().to_string();
101 if !config.path_filter.iter().any(|filter| path_display.contains(filter)) {
102 filtered.fetch_add(1, Ordering::Relaxed);
106 let comments = Comments::parse_file(&path);
107 // Ignore file if only/ignore rules do (not) apply
108 if !test_file_conditions(&comments, &target) {
109 ignored.fetch_add(1, Ordering::Relaxed);
113 "ignored (in-test comment)".yellow()
117 // Run the test for all revisions
119 comments.revisions.clone().unwrap_or_else(|| vec![String::new()])
121 let (m, errors, stderr) =
122 run_test(&path, &config, &target, &revision, &comments);
124 // Using a single `eprintln!` to prevent messages from threads from getting intermingled.
125 let mut msg = format!("{} ", path.display());
126 if !revision.is_empty() {
127 write!(msg, "(revision `{revision}`) ").unwrap();
129 write!(msg, "... ").unwrap();
130 if errors.is_empty() {
131 eprintln!("{msg}{}", "ok".green());
132 succeeded.fetch_add(1, Ordering::Relaxed);
134 eprintln!("{msg}{}", "FAILED".red().bold());
135 failures.lock().unwrap().push((
150 // Print all errors in a single thread to show reliable output
151 let failures = failures.into_inner().unwrap();
152 let succeeded = succeeded.load(Ordering::Relaxed);
153 let ignored = ignored.load(Ordering::Relaxed);
154 let filtered = filtered.load(Ordering::Relaxed);
155 if !failures.is_empty() {
156 for (path, miri, revision, errors, stderr) in &failures {
158 eprint!("{}", path.display().to_string().underline());
159 if !revision.is_empty() {
160 eprint!(" (revision `{}`)", revision);
162 eprint!(" {}", "FAILED".red());
164 eprintln!("command: {:?}", miri);
166 let mut dump_stderr = true;
167 for error in errors {
169 Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
170 Error::PatternNotFound { pattern, definition_line } => {
171 eprintln!("`{pattern}` {} in stderr output", "not found".red());
173 "expected because of pattern here: {}:{definition_line}",
174 path.display().to_string().bold()
177 Error::NoPatternsFound => {
178 eprintln!("{}", "no error patterns found in failure test".red());
180 Error::PatternFoundInPassTest =>
181 eprintln!("{}", "error pattern found in success test".red()),
182 Error::OutputDiffers { path, actual, expected } => {
183 if path.extension().unwrap() == "stderr" {
186 eprintln!("actual output differed from expected {}", path.display());
187 eprintln!("{}", pretty_assertions::StrComparison::new(expected, actual));
190 Error::ErrorsWithoutPattern { path: None, msgs } => {
192 "There were {} unmatched diagnostics that occurred outside the testfile and had not pattern",
195 for Message { level, message } in msgs {
196 eprintln!(" {level:?}: {message}")
199 Error::ErrorsWithoutPattern { path: Some((path, line)), msgs } => {
201 "There were {} unmatched diagnostics at {}:{line}",
205 for Message { level, message } in msgs {
206 eprintln!(" {level:?}: {message}")
209 Error::ErrorPatternWithoutErrorAnnotation(path, line) => {
211 "Annotation at {}:{line} matched an error diagnostic but did not have `ERROR` before its message",
218 // Unless we already dumped the stderr via an OutputDiffers diff, let's dump it here.
220 eprintln!("actual stderr:");
221 eprintln!("{}", stderr);
225 eprintln!("{}", "failures:".red().underline());
226 for (path, _miri, _revision, _errors, _stderr) in &failures {
227 eprintln!(" {}", path.display());
231 "test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
233 failures.len().to_string().red().bold(),
234 succeeded.to_string().green(),
235 ignored.to_string().yellow(),
236 filtered.to_string().yellow(),
238 std::process::exit(1);
242 "test result: {}. {} tests passed, {} ignored, {} filtered out",
244 succeeded.to_string().green(),
245 ignored.to_string().yellow(),
246 filtered.to_string().yellow(),
253 /// Got an invalid exit status for the given mode.
254 ExitStatus(Mode, ExitStatus),
257 definition_line: usize,
259 /// A ui test checking for failure does not have any failure patterns
261 /// A ui test checking for success has failure patterns
262 PatternFoundInPassTest,
263 /// Stderr/Stdout differed from the `.stderr`/`.stdout` file present.
269 ErrorsWithoutPattern {
271 path: Option<(PathBuf, usize)>,
273 ErrorPatternWithoutErrorAnnotation(PathBuf, usize),
276 type Errors = Vec<Error>;
284 ) -> (Command, Errors, String) {
286 let mut miri = Command::new(&config.program);
287 miri.args(config.args.iter());
289 if !revision.is_empty() {
290 miri.arg(format!("--cfg={revision}"));
292 miri.arg("--error-format=json");
293 for arg in &comments.compile_flags {
296 for (k, v) in &comments.env_vars {
299 let output = miri.output().expect("could not execute miri");
300 let mut errors = config.mode.ok(output.status);
301 let stderr = check_test_result(
311 (miri, errors, stderr)
314 fn check_test_result(
324 // Always remove annotation comments from stderr.
325 let diagnostics = rustc_stderr::process(path, stderr);
326 let stdout = std::str::from_utf8(stdout).unwrap();
327 // Check output files (if any)
328 let revised = |extension: &str| {
329 if revision.is_empty() {
330 extension.to_string()
332 format!("{}.{}", revision, extension)
335 // Check output files against actual output
337 &diagnostics.rendered,
342 &config.stderr_filters,
352 &config.stdout_filters,
356 // Check error annotations in the source against output
358 diagnostics.messages,
359 diagnostics.messages_from_unknown_file_or_line,
369 fn check_annotations(
370 mut messages: Vec<Vec<Message>>,
371 mut messages_from_unknown_file_or_line: Vec<Message>,
378 if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
379 // first check the diagnostics messages outside of our file. We check this first, so that
380 // you can mix in-file annotations with // error-pattern annotations, even if there is overlap
382 if let Some(i) = messages_from_unknown_file_or_line
384 .position(|msg| msg.message.contains(error_pattern))
386 messages_from_unknown_file_or_line.remove(i);
388 errors.push(Error::PatternNotFound {
389 pattern: error_pattern.to_string(),
395 // The order on `Level` is such that `Error` is the highest level.
396 // We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
398 let mut lowest_annotation_level = Level::Error;
399 for &ErrorMatch { ref matched, revision: ref rev, definition_line, line, level } in
400 &comments.error_matches
402 if let Some(rev) = rev {
407 if let Some(level) = level {
408 // If we found a diagnostic with a level annotation, make sure that all
409 // diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
411 lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
414 if let Some(msgs) = messages.get_mut(line) {
415 let found = msgs.iter().position(|msg| {
416 msg.message.contains(matched)
417 // in case there is no level on the annotation, match any level.
418 && level.map_or(true, |level| {
422 if let Some(found) = found {
423 let msg = msgs.remove(found);
424 if msg.level == Level::Error && level.is_none() {
426 .push(Error::ErrorPatternWithoutErrorAnnotation(path.to_path_buf(), line));
432 errors.push(Error::PatternNotFound { pattern: matched.to_string(), definition_line });
435 let filter = |msgs: Vec<Message>| -> Vec<_> {
436 msgs.into_iter().filter(|msg| msg.level >= lowest_annotation_level).collect()
439 let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
440 if !messages_from_unknown_file_or_line.is_empty() {
441 errors.push(Error::ErrorsWithoutPattern {
443 msgs: messages_from_unknown_file_or_line,
447 for (line, msgs) in messages.into_iter().enumerate() {
448 let msgs = filter(msgs);
449 if !msgs.is_empty() {
451 .push(Error::ErrorsWithoutPattern { path: Some((path.to_path_buf(), line)), msgs });
455 match (config.mode, comments.error_pattern.is_some() || !comments.error_matches.is_empty()) {
456 (Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
457 (Mode::Fail, false) => errors.push(Error::NoPatternsFound),
472 let output = normalize(path, output, filters, comments);
473 let path = output_path(path, comments, kind, target);
474 match config.output_conflict_handling {
475 OutputConflictHandling::Bless =>
476 if output.is_empty() {
477 let _ = std::fs::remove_file(path);
479 std::fs::write(path, &output).unwrap();
481 OutputConflictHandling::Error => {
482 let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
483 if output != expected_output {
484 errors.push(Error::OutputDiffers {
487 expected: expected_output,
491 OutputConflictHandling::Ignore => {}
495 fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
496 if comments.stderr_per_bitwidth {
497 return path.with_extension(format!("{}bit.{kind}", get_pointer_width(target)));
499 path.with_extension(kind)
502 fn test_condition(condition: &Condition, target: &str) -> bool {
504 Condition::Bitwidth(bits) => get_pointer_width(target) == *bits,
505 Condition::Target(t) => target.contains(t),
509 /// Returns whether according to the in-file conditions, this file should be run.
510 fn test_file_conditions(comments: &Comments, target: &str) -> bool {
511 if comments.ignore.iter().any(|c| test_condition(c, target)) {
514 comments.only.iter().all(|c| test_condition(c, target))
517 // Taken 1:1 from compiletest-rs
518 fn get_pointer_width(triple: &str) -> u8 {
519 if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
520 || triple.starts_with("s390x")
523 } else if triple.starts_with("avr") {
530 fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
532 let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
533 if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
534 text = text.replace(lib_path, "RUSTLIB");
537 for (regex, replacement) in filters.iter() {
538 text = regex.replace_all(&text, *replacement).to_string();
541 for (from, to) in &comments.normalize_stderr {
542 text = from.replace_all(&text, to).to_string();
548 fn get_host(&self) -> String {
549 rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
550 .expect("failed to parse rustc version info")
555 #[derive(Copy, Clone, Debug)]
557 // The test passes a full execution of the rustc driver
559 // The rustc driver panicked
561 // The rustc driver emitted an error
566 fn ok(self, status: ExitStatus) -> Errors {
567 match (status.code().unwrap(), self) {
568 (1, Mode::Fail) | (101, Mode::Panic) | (0, Mode::Pass) => vec![],
569 _ => vec![Error::ExitStatus(self, status)],