1 use std::collections::VecDeque;
3 use std::path::{Path, PathBuf};
4 use std::process::{Command, ExitStatus};
5 use std::sync::atomic::{AtomicUsize, Ordering};
9 use comments::ErrorMatch;
11 use rustc_stderr::{Level, Message};
13 use crate::comments::{Comments, Condition};
22 /// Arguments passed to the binary that is executed.
23 pub args: Vec<String>,
24 /// `None` to run on the host, otherwise a target triple
25 pub target: Option<String>,
26 /// Filters applied to stderr output before processing it
27 pub stderr_filters: Filter,
28 /// Filters applied to stdout output before processing it
29 pub stdout_filters: Filter,
30 /// The folder in which to start searching for .rs files
31 pub root_dir: PathBuf,
34 pub output_conflict_handling: OutputConflictHandling,
35 /// Only run tests with one of these strings in their path/name
36 pub path_filter: Vec<String>,
40 pub enum OutputConflictHandling {
41 /// The default: emit a diff of the expected/actual output.
43 /// Ignore mismatches in the stderr/stdout files.
45 /// Instead of erroring if the stderr/stdout differs from the expected
46 /// automatically replace it with the found output (after applying filters).
50 pub type Filter = Vec<(Regex, &'static str)>;
52 pub fn run_tests(config: Config) {
53 eprintln!(" Compiler flags: {:?}", config.args);
55 // Get the triple with which to run the tests
56 let target = config.target.clone().unwrap_or_else(|| config.get_host());
58 // A channel for files to process
59 let (submit, receive) = crossbeam::channel::unbounded();
61 // Some statistics and failure reports.
62 let failures = Mutex::new(vec![]);
63 let succeeded = AtomicUsize::default();
64 let ignored = AtomicUsize::default();
65 let filtered = AtomicUsize::default();
67 crossbeam::scope(|s| {
68 // Create a thread that is in charge of walking the directory and submitting jobs.
69 // It closes the channel when it is done.
71 let mut todo = VecDeque::new();
72 todo.push_back(config.root_dir.clone());
73 while let Some(path) = todo.pop_front() {
75 // Enqueue everything inside this directory.
76 // We want it sorted, to have some control over scheduling of slow tests.
78 std::fs::read_dir(path).unwrap().collect::<Result<Vec<_>, _>>().unwrap();
79 entries.sort_by_key(|e| e.file_name());
80 for entry in entries {
81 todo.push_back(entry.path());
83 } else if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
84 // Forward .rs files to the test workers.
85 submit.send(path).unwrap();
88 // There will be no more jobs. This signals the workers to quit.
89 // (This also ensures `submit` is moved into this closure.)
93 // Create N worker threads that receive files to test.
94 for _ in 0..std::thread::available_parallelism().unwrap().get() {
96 for path in &receive {
97 if !config.path_filter.is_empty() {
98 let path_display = path.display().to_string();
99 if !config.path_filter.iter().any(|filter| path_display.contains(filter)) {
100 filtered.fetch_add(1, Ordering::Relaxed);
104 let comments = Comments::parse_file(&path);
105 // Ignore file if only/ignore rules do (not) apply
106 if !test_file_conditions(&comments, &target) {
107 ignored.fetch_add(1, Ordering::Relaxed);
111 "ignored (in-test comment)".yellow()
115 // Run the test for all revisions
117 comments.revisions.clone().unwrap_or_else(|| vec![String::new()])
119 let (m, errors, stderr) =
120 run_test(&path, &config, &target, &revision, &comments);
122 // Using a single `eprintln!` to prevent messages from threads from getting intermingled.
123 let mut msg = format!("{} ", path.display());
124 if !revision.is_empty() {
125 write!(msg, "(revision `{revision}`) ").unwrap();
127 write!(msg, "... ").unwrap();
128 if errors.is_empty() {
129 eprintln!("{msg}{}", "ok".green());
130 succeeded.fetch_add(1, Ordering::Relaxed);
132 eprintln!("{msg}{}", "FAILED".red().bold());
133 failures.lock().unwrap().push((
148 // Print all errors in a single thread to show reliable output
149 let failures = failures.into_inner().unwrap();
150 let succeeded = succeeded.load(Ordering::Relaxed);
151 let ignored = ignored.load(Ordering::Relaxed);
152 let filtered = filtered.load(Ordering::Relaxed);
153 if !failures.is_empty() {
154 for (path, miri, revision, errors, stderr) in &failures {
156 eprint!("{}", path.display().to_string().underline());
157 if !revision.is_empty() {
158 eprint!(" (revision `{}`)", revision);
160 eprint!(" {}", "FAILED".red());
162 eprintln!("command: {:?}", miri);
164 let mut dump_stderr = true;
165 for error in errors {
167 Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
168 Error::PatternNotFound { pattern, definition_line } => {
169 eprintln!("`{pattern}` {} in stderr output", "not found".red());
171 "expected because of pattern here: {}:{definition_line}",
172 path.display().to_string().bold()
175 Error::NoPatternsFound => {
176 eprintln!("{}", "no error patterns found in failure test".red());
178 Error::PatternFoundInPassTest =>
179 eprintln!("{}", "error pattern found in success test".red()),
180 Error::OutputDiffers { path, actual, expected } => {
181 if path.extension().unwrap() == "stderr" {
184 eprintln!("actual output differed from expected {}", path.display());
185 eprintln!("{}", pretty_assertions::StrComparison::new(expected, actual));
188 Error::ErrorsWithoutPattern { path: None, msgs } => {
190 "There were {} unmatched diagnostics that occurred outside the testfile and had not pattern",
193 for Message { level, message } in msgs {
194 eprintln!(" {level:?}: {message}")
197 Error::ErrorsWithoutPattern { path: Some((path, line)), msgs } => {
199 "There were {} unmatched diagnostics at {}:{line}",
203 for Message { level, message } in msgs {
204 eprintln!(" {level:?}: {message}")
207 Error::ErrorPatternWithoutErrorAnnotation(path, line) => {
209 "Annotation at {}:{line} matched an error diagnostic but did not have `ERROR` before its message",
216 // Unless we already dumped the stderr via an OutputDiffers diff, let's dump it here.
218 eprintln!("actual stderr:");
219 eprintln!("{}", stderr);
223 eprintln!("{}", "failures:".red().underline());
224 for (path, _miri, _revision, _errors, _stderr) in &failures {
225 eprintln!(" {}", path.display());
229 "test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
231 failures.len().to_string().red().bold(),
232 succeeded.to_string().green(),
233 ignored.to_string().yellow(),
234 filtered.to_string().yellow(),
236 std::process::exit(1);
240 "test result: {}. {} tests passed, {} ignored, {} filtered out",
242 succeeded.to_string().green(),
243 ignored.to_string().yellow(),
244 filtered.to_string().yellow(),
251 /// Got an invalid exit status for the given mode.
252 ExitStatus(Mode, ExitStatus),
255 definition_line: usize,
257 /// A ui test checking for failure does not have any failure patterns
259 /// A ui test checking for success has failure patterns
260 PatternFoundInPassTest,
261 /// Stderr/Stdout differed from the `.stderr`/`.stdout` file present.
267 ErrorsWithoutPattern {
269 path: Option<(PathBuf, usize)>,
271 ErrorPatternWithoutErrorAnnotation(PathBuf, usize),
274 type Errors = Vec<Error>;
282 ) -> (Command, Errors, String) {
284 let mut miri = Command::new(&config.program);
285 miri.args(config.args.iter());
287 if !revision.is_empty() {
288 miri.arg(format!("--cfg={revision}"));
290 miri.arg("--error-format=json");
291 for arg in &comments.compile_flags {
294 for (k, v) in &comments.env_vars {
297 let output = miri.output().expect("could not execute miri");
298 let mut errors = config.mode.ok(output.status);
299 let stderr = check_test_result(
309 (miri, errors, stderr)
312 fn check_test_result(
322 // Always remove annotation comments from stderr.
323 let diagnostics = rustc_stderr::process(path, stderr);
324 let stdout = std::str::from_utf8(stdout).unwrap();
325 // Check output files (if any)
326 let revised = |extension: &str| {
327 if revision.is_empty() {
328 extension.to_string()
330 format!("{}.{}", revision, extension)
333 // Check output files against actual output
335 &diagnostics.rendered,
340 &config.stderr_filters,
350 &config.stdout_filters,
354 // Check error annotations in the source against output
356 diagnostics.messages,
357 diagnostics.messages_from_unknown_file_or_line,
367 fn check_annotations(
368 mut messages: Vec<Vec<Message>>,
369 mut messages_from_unknown_file_or_line: Vec<Message>,
376 if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
377 let mut found = false;
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);
390 // if nothing was found, check the ones inside our file. We permit this because some tests may have
391 // flaky line numbers for their messages.
393 for line in &mut messages {
394 if let Some(i) = line.iter().position(|msg| msg.message.contains(error_pattern)) {
403 errors.push(Error::PatternNotFound {
404 pattern: error_pattern.to_string(),
410 // The order on `Level` is such that `Error` is the highest level.
411 // We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
413 let mut lowest_annotation_level = Level::Error;
414 for &ErrorMatch { ref matched, revision: ref rev, definition_line, line, level } in
415 &comments.error_matches
417 if let Some(rev) = rev {
422 if let Some(level) = level {
423 // If we found a diagnostic with a level annotation, make sure that all
424 // diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
426 lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
429 if let Some(msgs) = messages.get_mut(line) {
430 let found = msgs.iter().position(|msg| {
431 msg.message.contains(matched)
432 // in case there is no level on the annotation, match any level.
433 && level.map_or(true, |level| {
437 if let Some(found) = found {
438 let msg = msgs.remove(found);
439 if msg.level == Level::Error && level.is_none() {
441 .push(Error::ErrorPatternWithoutErrorAnnotation(path.to_path_buf(), line));
447 errors.push(Error::PatternNotFound { pattern: matched.to_string(), definition_line });
450 let filter = |msgs: Vec<Message>| -> Vec<_> {
451 msgs.into_iter().filter(|msg| msg.level >= lowest_annotation_level).collect()
454 let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
455 if !messages_from_unknown_file_or_line.is_empty() {
456 errors.push(Error::ErrorsWithoutPattern {
458 msgs: messages_from_unknown_file_or_line,
462 for (line, msgs) in messages.into_iter().enumerate() {
463 let msgs = filter(msgs);
464 if !msgs.is_empty() {
466 .push(Error::ErrorsWithoutPattern { path: Some((path.to_path_buf(), line)), msgs });
470 match (config.mode, comments.error_pattern.is_some() || !comments.error_matches.is_empty()) {
471 (Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
472 (Mode::Fail, false) => errors.push(Error::NoPatternsFound),
487 let output = normalize(path, output, filters, comments);
488 let path = output_path(path, comments, kind, target);
489 match config.output_conflict_handling {
490 OutputConflictHandling::Bless =>
491 if output.is_empty() {
492 let _ = std::fs::remove_file(path);
494 std::fs::write(path, &output).unwrap();
496 OutputConflictHandling::Error => {
497 let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
498 if output != expected_output {
499 errors.push(Error::OutputDiffers {
502 expected: expected_output,
506 OutputConflictHandling::Ignore => {}
510 fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
511 if comments.stderr_per_bitwidth {
512 return path.with_extension(format!("{}bit.{kind}", get_pointer_width(target)));
514 path.with_extension(kind)
517 fn test_condition(condition: &Condition, target: &str) -> bool {
519 Condition::Bitwidth(bits) => get_pointer_width(target) == *bits,
520 Condition::Target(t) => target.contains(t),
524 /// Returns whether according to the in-file conditions, this file should be run.
525 fn test_file_conditions(comments: &Comments, target: &str) -> bool {
526 if comments.ignore.iter().any(|c| test_condition(c, target)) {
529 comments.only.iter().all(|c| test_condition(c, target))
532 // Taken 1:1 from compiletest-rs
533 fn get_pointer_width(triple: &str) -> u8 {
534 if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
535 || triple.starts_with("s390x")
538 } else if triple.starts_with("avr") {
545 fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
547 let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
548 if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
549 text = text.replace(lib_path, "RUSTLIB");
552 for (regex, replacement) in filters.iter() {
553 text = regex.replace_all(&text, *replacement).to_string();
556 for (from, to) in &comments.normalize_stderr {
557 text = from.replace_all(&text, to).to_string();
563 fn get_host(&self) -> String {
564 rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
565 .expect("failed to parse rustc version info")
570 #[derive(Copy, Clone, Debug)]
572 // The test passes a full execution of the rustc driver
574 // The rustc driver panicked
576 // The rustc driver emitted an error
581 fn ok(self, status: ExitStatus) -> Errors {
582 match (status.code().unwrap(), self) {
583 (1, Mode::Fail) | (101, Mode::Panic) | (0, Mode::Pass) => vec![],
584 _ => vec![Error::ExitStatus(self, status)],