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 let mut dump_stderr = true;
151 for error in errors {
153 Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
154 Error::PatternNotFound { pattern, definition_line } => {
155 eprintln!("`{pattern}` {} in stderr output", "not found".red());
157 "expected because of pattern here: {}:{definition_line}",
158 path.display().to_string().bold()
161 Error::NoPatternsFound => {
162 eprintln!("{}", "no error patterns found in failure test".red());
164 Error::PatternFoundInPassTest =>
165 eprintln!("{}", "error pattern found in success test".red()),
166 Error::OutputDiffers { path, actual, expected } => {
167 if path.extension().unwrap() == "stderr" {
170 eprintln!("actual output differed from expected {}", path.display());
171 eprintln!("{}", pretty_assertions::StrComparison::new(expected, actual));
174 Error::ErrorsWithoutPattern { path: None, msgs } => {
176 "There were {} unmatched diagnostics that occurred outside the testfile and had not pattern",
179 for Message { level, message } in msgs {
180 eprintln!(" {level:?}: {message}")
183 Error::ErrorsWithoutPattern { path: Some((path, line)), msgs } => {
185 "There were {} unmatched diagnostics at {}:{line}",
189 for Message { level, message } in msgs {
190 eprintln!(" {level:?}: {message}")
193 Error::ErrorPatternWithoutErrorAnnotation(path, line) => {
195 "Annotation at {}:{line} matched an error diagnostic but did not have `ERROR` before its message",
202 // Unless we already dumped the stderr via an OutputDiffers diff, let's dump it here.
204 eprintln!("actual stderr:");
205 eprintln!("{}", stderr);
209 eprintln!("{}", "failures:".red().underline());
210 for (path, _miri, _revision, _errors, _stderr) in &failures {
211 eprintln!(" {}", path.display());
215 "test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
217 failures.len().to_string().red().bold(),
218 succeeded.to_string().green(),
219 ignored.to_string().yellow(),
220 filtered.to_string().yellow(),
222 std::process::exit(1);
226 "test result: {}. {} tests passed, {} ignored, {} filtered out",
228 succeeded.to_string().green(),
229 ignored.to_string().yellow(),
230 filtered.to_string().yellow(),
237 /// Got an invalid exit status for the given mode.
238 ExitStatus(Mode, ExitStatus),
241 definition_line: usize,
243 /// A ui test checking for failure does not have any failure patterns
245 /// A ui test checking for success has failure patterns
246 PatternFoundInPassTest,
247 /// Stderr/Stdout differed from the `.stderr`/`.stdout` file present.
253 ErrorsWithoutPattern {
255 path: Option<(PathBuf, usize)>,
257 ErrorPatternWithoutErrorAnnotation(PathBuf, usize),
260 type Errors = Vec<Error>;
268 ) -> (Command, Errors, String) {
270 let mut miri = Command::new(&config.program);
271 miri.args(config.args.iter());
273 if !revision.is_empty() {
274 miri.arg(format!("--cfg={revision}"));
276 miri.arg("--error-format=json");
277 for arg in &comments.compile_flags {
280 for (k, v) in &comments.env_vars {
283 let output = miri.output().expect("could not execute miri");
284 let mut errors = config.mode.ok(output.status);
285 let stderr = check_test_result(
295 (miri, errors, stderr)
298 fn check_test_result(
308 // Always remove annotation comments from stderr.
309 let diagnostics = rustc_stderr::process(path, stderr);
310 let stdout = std::str::from_utf8(stdout).unwrap();
311 // Check output files (if any)
312 let revised = |extension: &str| {
313 if revision.is_empty() {
314 extension.to_string()
316 format!("{}.{}", revision, extension)
319 // Check output files against actual output
321 &diagnostics.rendered,
326 &config.stderr_filters,
336 &config.stdout_filters,
340 // Check error annotations in the source against output
342 diagnostics.messages,
343 diagnostics.messages_from_unknown_file_or_line,
353 fn check_annotations(
354 mut messages: Vec<Vec<Message>>,
355 mut messages_from_unknown_file_or_line: Vec<Message>,
362 if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
363 let mut found = false;
365 // first check the diagnostics messages outside of our file. We check this first, so that
366 // you can mix in-file annotations with // error-pattern annotations, even if there is overlap
368 if let Some(i) = messages_from_unknown_file_or_line
370 .position(|msg| msg.message.contains(error_pattern))
372 messages_from_unknown_file_or_line.remove(i);
376 // if nothing was found, check the ones inside our file. We permit this because some tests may have
377 // flaky line numbers for their messages.
379 for line in &mut messages {
380 if let Some(i) = line.iter().position(|msg| msg.message.contains(error_pattern)) {
389 errors.push(Error::PatternNotFound {
390 pattern: error_pattern.to_string(),
396 // The order on `Level` is such that `Error` is the highest level.
397 // We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
399 let mut lowest_annotation_level = Level::Error;
400 for &ErrorMatch { ref matched, revision: ref rev, definition_line, line, level } in
401 &comments.error_matches
403 if let Some(rev) = rev {
408 if let Some(level) = level {
409 // If we found a diagnostic with a level annotation, make sure that all
410 // diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
412 lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
415 if let Some(msgs) = messages.get_mut(line) {
416 let found = msgs.iter().position(|msg| {
417 msg.message.contains(matched)
418 // in case there is no level on the annotation, match any level.
419 && level.map_or(true, |level| {
423 if let Some(found) = found {
424 let msg = msgs.remove(found);
425 if msg.level == Level::Error && level.is_none() {
427 .push(Error::ErrorPatternWithoutErrorAnnotation(path.to_path_buf(), line));
433 errors.push(Error::PatternNotFound { pattern: matched.to_string(), definition_line });
436 let filter = |msgs: Vec<Message>| -> Vec<_> {
437 msgs.into_iter().filter(|msg| msg.level >= lowest_annotation_level).collect()
440 let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
441 if !messages_from_unknown_file_or_line.is_empty() {
442 errors.push(Error::ErrorsWithoutPattern {
444 msgs: messages_from_unknown_file_or_line,
448 for (line, msgs) in messages.into_iter().enumerate() {
449 let msgs = filter(msgs);
450 if !msgs.is_empty() {
452 .push(Error::ErrorsWithoutPattern { path: Some((path.to_path_buf(), line)), msgs });
456 match (config.mode, comments.error_pattern.is_some() || !comments.error_matches.is_empty()) {
457 (Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
458 (Mode::Fail, false) => errors.push(Error::NoPatternsFound),
473 let output = normalize(path, output, filters, comments);
474 let path = output_path(path, comments, kind, target);
475 match config.output_conflict_handling {
476 OutputConflictHandling::Bless =>
477 if output.is_empty() {
478 let _ = std::fs::remove_file(path);
480 std::fs::write(path, &output).unwrap();
482 OutputConflictHandling::Error => {
483 let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
484 if output != expected_output {
485 errors.push(Error::OutputDiffers {
488 expected: expected_output,
492 OutputConflictHandling::Ignore => {}
496 fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
497 if comments.stderr_per_bitwidth {
498 return path.with_extension(format!("{}.{kind}", get_pointer_width(target)));
500 path.with_extension(kind)
503 fn ignore_file(comments: &Comments, target: &str) -> bool {
504 for s in &comments.ignore {
505 if target.contains(s) {
508 if get_pointer_width(target) == s {
512 for s in &comments.only {
513 if !target.contains(s) {
516 /* FIXME(https://github.com/rust-lang/miri/issues/2206)
517 if get_pointer_width(target) != s {
524 // Taken 1:1 from compiletest-rs
525 fn get_pointer_width(triple: &str) -> &'static str {
526 if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
527 || triple.starts_with("s390x")
530 } else if triple.starts_with("avr") {
537 fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
539 let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
540 if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
541 text = text.replace(lib_path, "RUSTLIB");
544 for (regex, replacement) in filters.iter() {
545 text = regex.replace_all(&text, *replacement).to_string();
548 for (from, to) in &comments.normalize_stderr {
549 text = from.replace_all(&text, to).to_string();
555 fn get_host(&self) -> String {
556 rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
557 .expect("failed to parse rustc version info")
562 #[derive(Copy, Clone, Debug)]
564 // The test passes a full execution of the rustc driver
566 // The rustc driver panicked
568 // The rustc driver emitted an error
573 fn ok(self, status: ExitStatus) -> Errors {
574 match (status.code().unwrap(), self) {
575 (1, Mode::Fail) | (101, Mode::Panic) | (0, Mode::Pass) => vec![],
576 _ => vec![Error::ExitStatus(self, status)],