2 use std::path::{Path, PathBuf};
3 use std::process::{Command, ExitStatus};
4 use std::sync::atomic::{AtomicUsize, Ordering};
8 use comments::ErrorMatch;
9 use crossbeam::queue::SegQueue;
11 use rustc_stderr::{Level, Message};
13 use crate::comments::Comments;
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 queue for files or folders to process
59 let todo = SegQueue::new();
60 todo.push(config.root_dir.clone());
62 // Some statistics and failure reports.
63 let failures = Mutex::new(vec![]);
64 let succeeded = AtomicUsize::default();
65 let ignored = AtomicUsize::default();
66 let filtered = AtomicUsize::default();
68 crossbeam::scope(|s| {
69 for _ in 0..std::thread::available_parallelism().unwrap().get() {
71 while let Some(path) = todo.pop() {
72 // Collect everything inside directories
74 for entry in std::fs::read_dir(path).unwrap() {
75 todo.push(entry.unwrap().path());
79 // Only look at .rs files
80 if !path.extension().map(|ext| ext == "rs").unwrap_or(false) {
83 if !config.path_filter.is_empty() {
84 let path_display = path.display().to_string();
85 if !config.path_filter.iter().any(|filter| path_display.contains(filter)) {
86 filtered.fetch_add(1, Ordering::Relaxed);
90 let comments = Comments::parse_file(&path);
91 // Ignore file if only/ignore rules do (not) apply
92 if ignore_file(&comments, &target) {
93 ignored.fetch_add(1, Ordering::Relaxed);
97 "ignored (in-test comment)".yellow()
101 // Run the test for all revisions
103 comments.revisions.clone().unwrap_or_else(|| vec![String::new()])
105 let (m, errors, stderr) =
106 run_test(&path, &config, &target, &revision, &comments);
108 // Using a single `eprintln!` to prevent messages from threads from getting intermingled.
109 let mut msg = format!("{} ", path.display());
110 if !revision.is_empty() {
111 write!(msg, "(revision `{revision}`) ").unwrap();
113 write!(msg, "... ").unwrap();
114 if errors.is_empty() {
115 eprintln!("{msg}{}", "ok".green());
116 succeeded.fetch_add(1, Ordering::Relaxed);
118 eprintln!("{msg}{}", "FAILED".red().bold());
119 failures.lock().unwrap().push((
134 // Print all errors in a single thread to show reliable output
135 let failures = failures.into_inner().unwrap();
136 let succeeded = succeeded.load(Ordering::Relaxed);
137 let ignored = ignored.load(Ordering::Relaxed);
138 let filtered = filtered.load(Ordering::Relaxed);
139 if !failures.is_empty() {
140 for (path, miri, revision, errors, stderr) in &failures {
142 eprint!("{}", path.display().to_string().underline());
143 if !revision.is_empty() {
144 eprint!(" (revision `{}`)", revision);
146 eprint!(" {}", "FAILED".red());
148 eprintln!("command: {:?}", miri);
150 // `None` means never dump, as we already dumped it for an `OutputDiffers`
151 // `Some(false)` means there's no reason to dump, as all errors are independent of the stderr
152 // `Some(true)` means that there was a pattern in the .rs file that was not found in the output.
153 let mut dump_stderr = Some(false);
154 for error in errors {
156 Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
157 Error::PatternNotFound { pattern, definition_line } => {
158 eprintln!("`{pattern}` {} in stderr output", "not found".red());
160 "expected because of pattern here: {}:{definition_line}",
161 path.display().to_string().bold()
163 dump_stderr = dump_stderr.map(|_| true);
165 Error::NoPatternsFound => {
166 eprintln!("{}", "no error patterns found in failure test".red());
168 Error::PatternFoundInPassTest =>
169 eprintln!("{}", "error pattern found in success test".red()),
170 Error::OutputDiffers { path, actual, expected } => {
171 if path.extension().unwrap() == "stderr" {
174 eprintln!("actual output differed from expected {}", path.display());
175 eprintln!("{}", pretty_assertions::StrComparison::new(expected, actual));
178 Error::ErrorsWithoutPattern { path: None, msgs } => {
180 "There were {} unmatched diagnostics that occurred outside the testfile and had not pattern",
183 for Message { level, message } in msgs {
184 eprintln!(" {level:?}: {message}")
187 Error::ErrorsWithoutPattern { path: Some((path, line)), msgs } => {
189 "There were {} unmatched diagnostics at {}:{line}",
193 for Message { level, message } in msgs {
194 eprintln!(" {level:?}: {message}")
197 Error::ErrorPatternWithoutErrorAnnotation(path, line) => {
199 "Annotation at {}:{line} matched an error diagnostic but did not have `ERROR` before its message",
206 if let Some(true) = dump_stderr {
207 eprintln!("actual stderr:");
208 eprintln!("{}", stderr);
212 eprintln!("{}", "failures:".red().underline());
213 for (path, _miri, _revision, _errors, _stderr) in &failures {
214 eprintln!(" {}", path.display());
218 "test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
220 failures.len().to_string().red().bold(),
221 succeeded.to_string().green(),
222 ignored.to_string().yellow(),
223 filtered.to_string().yellow(),
225 std::process::exit(1);
229 "test result: {}. {} tests passed, {} ignored, {} filtered out",
231 succeeded.to_string().green(),
232 ignored.to_string().yellow(),
233 filtered.to_string().yellow(),
240 /// Got an invalid exit status for the given mode.
241 ExitStatus(Mode, ExitStatus),
244 definition_line: usize,
246 /// A ui test checking for failure does not have any failure patterns
248 /// A ui test checking for success has failure patterns
249 PatternFoundInPassTest,
250 /// Stderr/Stdout differed from the `.stderr`/`.stdout` file present.
256 ErrorsWithoutPattern {
258 path: Option<(PathBuf, usize)>,
260 ErrorPatternWithoutErrorAnnotation(PathBuf, usize),
263 type Errors = Vec<Error>;
271 ) -> (Command, Errors, String) {
273 let mut miri = Command::new(&config.program);
274 miri.args(config.args.iter());
276 if !revision.is_empty() {
277 miri.arg(format!("--cfg={revision}"));
279 miri.arg("--error-format=json");
280 for arg in &comments.compile_flags {
283 for (k, v) in &comments.env_vars {
286 let output = miri.output().expect("could not execute miri");
287 let mut errors = config.mode.ok(output.status);
288 let stderr = check_test_result(
298 (miri, errors, stderr)
301 fn check_test_result(
311 // Always remove annotation comments from stderr.
312 let diagnostics = rustc_stderr::process(path, stderr);
313 let stdout = std::str::from_utf8(stdout).unwrap();
314 // Check output files (if any)
315 let revised = |extension: &str| {
316 if revision.is_empty() {
317 extension.to_string()
319 format!("{}.{}", revision, extension)
322 // Check output files against actual output
324 &diagnostics.rendered,
329 &config.stderr_filters,
339 &config.stdout_filters,
343 // Check error annotations in the source against output
345 diagnostics.messages,
346 diagnostics.messages_from_unknown_file_or_line,
356 fn check_annotations(
357 mut messages: Vec<Vec<Message>>,
358 mut messages_from_unknown_file_or_line: Vec<Message>,
365 if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
366 let mut found = false;
368 // first check the diagnostics messages outside of our file. We check this first, so that
369 // you can mix in-file annotations with // error-pattern annotations, even if there is overlap
371 if let Some(i) = messages_from_unknown_file_or_line
373 .position(|msg| msg.message.contains(error_pattern))
375 messages_from_unknown_file_or_line.remove(i);
379 // if nothing was found, check the ones inside our file. We permit this because some tests may have
380 // flaky line numbers for their messages.
382 for line in &mut messages {
383 if let Some(i) = line.iter().position(|msg| msg.message.contains(error_pattern)) {
392 errors.push(Error::PatternNotFound {
393 pattern: error_pattern.to_string(),
399 // The order on `Level` is such that `Error` is the highest level.
400 // We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
402 let mut lowest_annotation_level = Level::Error;
403 for &ErrorMatch { ref matched, revision: ref rev, definition_line, line, level } in
404 &comments.error_matches
406 if let Some(rev) = rev {
411 if let Some(level) = level {
412 // If we found a diagnostic with a level annotation, make sure that all
413 // diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
415 lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
418 if let Some(msgs) = messages.get_mut(line) {
419 let found = msgs.iter().position(|msg| {
420 msg.message.contains(matched)
421 // in case there is no level on the annotation, match any level.
422 && level.map_or(true, |level| {
426 if let Some(found) = found {
427 let msg = msgs.remove(found);
428 if msg.level == Level::Error && level.is_none() {
430 .push(Error::ErrorPatternWithoutErrorAnnotation(path.to_path_buf(), line));
436 errors.push(Error::PatternNotFound { pattern: matched.to_string(), definition_line });
439 let filter = |msgs: Vec<Message>| -> Vec<_> {
440 msgs.into_iter().filter(|msg| msg.level >= lowest_annotation_level).collect()
443 let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
444 if !messages_from_unknown_file_or_line.is_empty() {
445 errors.push(Error::ErrorsWithoutPattern {
447 msgs: messages_from_unknown_file_or_line,
451 for (line, msgs) in messages.into_iter().enumerate() {
452 let msgs = filter(msgs);
453 if !msgs.is_empty() {
455 .push(Error::ErrorsWithoutPattern { path: Some((path.to_path_buf(), line)), msgs });
459 match (config.mode, comments.error_pattern.is_some() || !comments.error_matches.is_empty()) {
460 (Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
461 (Mode::Fail, false) => errors.push(Error::NoPatternsFound),
476 let output = normalize(path, output, filters, comments);
477 let path = output_path(path, comments, kind, target);
478 match config.output_conflict_handling {
479 OutputConflictHandling::Bless =>
480 if output.is_empty() {
481 let _ = std::fs::remove_file(path);
483 std::fs::write(path, &output).unwrap();
485 OutputConflictHandling::Error => {
486 let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
487 if output != expected_output {
488 errors.push(Error::OutputDiffers {
491 expected: expected_output,
495 OutputConflictHandling::Ignore => {}
499 fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
500 if comments.stderr_per_bitwidth {
501 return path.with_extension(format!("{}.{kind}", get_pointer_width(target)));
503 path.with_extension(kind)
506 fn ignore_file(comments: &Comments, target: &str) -> bool {
507 for s in &comments.ignore {
508 if target.contains(s) {
511 if get_pointer_width(target) == s {
515 for s in &comments.only {
516 if !target.contains(s) {
519 /* FIXME(https://github.com/rust-lang/miri/issues/2206)
520 if get_pointer_width(target) != s {
527 // Taken 1:1 from compiletest-rs
528 fn get_pointer_width(triple: &str) -> &'static str {
529 if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
530 || triple.starts_with("s390x")
533 } else if triple.starts_with("avr") {
540 fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
542 let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
543 if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
544 text = text.replace(lib_path, "RUSTLIB");
547 for (regex, replacement) in filters.iter() {
548 text = regex.replace_all(&text, *replacement).to_string();
551 for (from, to) in &comments.normalize_stderr {
552 text = from.replace_all(&text, to).to_string();
558 fn get_host(&self) -> String {
559 rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
560 .expect("failed to parse rustc version info")
565 #[derive(Copy, Clone, Debug)]
567 // The test passes a full execution of the rustc driver
569 // The rustc driver panicked
571 // The rustc driver emitted an error
576 fn ok(self, status: ExitStatus) -> Errors {
577 match (status.code().unwrap(), self) {
578 (1, Mode::Fail) | (101, Mode::Panic) | (0, Mode::Pass) => vec![],
579 _ => vec![Error::ExitStatus(self, status)],