1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
#![allow(
clippy::enum_variant_names,
clippy::useless_format,
clippy::too_many_arguments,
rustc::internal
)]
use std::collections::VecDeque;
use std::ffi::OsString;
use std::fmt::Write;
use std::num::NonZeroUsize;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Mutex;
pub use color_eyre;
use color_eyre::eyre::Result;
use colored::*;
use parser::{ErrorMatch, Pattern};
use regex::Regex;
use rustc_stderr::{Level, Message};
use crate::dependencies::build_dependencies;
use crate::parser::{Comments, Condition};
mod dependencies;
mod diff;
mod parser;
mod rustc_stderr;
#[cfg(test)]
mod tests;
#[derive(Debug)]
pub struct Config {
pub args: Vec<OsString>,
pub target: Option<String>,
pub stderr_filters: Filter,
pub stdout_filters: Filter,
pub root_dir: PathBuf,
pub mode: Mode,
pub program: PathBuf,
pub output_conflict_handling: OutputConflictHandling,
pub path_filter: Vec<String>,
pub dependencies_crate_manifest_path: Option<PathBuf>,
pub dependency_builder: DependencyBuilder,
pub quiet: bool,
pub num_test_threads: NonZeroUsize,
}
impl Default for Config {
fn default() -> Self {
Self {
args: vec!["--error-format=json".into()],
target: None,
stderr_filters: vec![],
stdout_filters: vec![],
root_dir: PathBuf::new(),
mode: Mode::Fail {
require_patterns: true,
},
program: PathBuf::from("rustc"),
output_conflict_handling: OutputConflictHandling::Error,
path_filter: vec![],
dependencies_crate_manifest_path: None,
dependency_builder: DependencyBuilder::default(),
quiet: true,
num_test_threads: std::thread::available_parallelism().unwrap(),
}
}
}
impl Config {
pub fn stderr_filter(&mut self, pattern: &str, replacement: &'static str) {
self.stderr_filters
.push((Regex::new(pattern).unwrap(), replacement));
}
}
#[derive(Debug)]
pub struct DependencyBuilder {
pub program: PathBuf,
pub args: Vec<String>,
pub envs: Vec<(String, OsString)>,
}
impl Default for DependencyBuilder {
fn default() -> Self {
Self {
program: PathBuf::from(std::env::var_os("CARGO").unwrap_or_else(|| "cargo".into())),
args: vec!["build".into()],
envs: vec![],
}
}
}
#[derive(Debug)]
pub enum OutputConflictHandling {
Error,
Ignore,
Bless,
}
pub type Filter = Vec<(Regex, &'static str)>;
pub fn run_tests(mut config: Config) -> Result<()> {
eprintln!(" Compiler flags: {:?}", config.args);
let dependencies = build_dependencies(&config)?;
for (name, dependency) in dependencies.dependencies {
config.args.push("--extern".into());
let mut dep = OsString::from(name);
dep.push("=");
dep.push(dependency);
config.args.push(dep);
}
for import_path in dependencies.import_paths {
config.args.push("-L".into());
config.args.push(import_path.into());
}
run_tests_generic(config, |path| {
path.extension().map(|ext| ext == "rs").unwrap_or(false)
})
}
pub fn run_tests_generic(config: Config, file_filter: impl Fn(&Path) -> bool + Sync) -> Result<()> {
let target = config.target.clone().unwrap_or_else(|| config.get_host());
let (submit, receive) = crossbeam::channel::unbounded();
let failures = Mutex::new(vec![]);
let succeeded = AtomicUsize::default();
let ignored = AtomicUsize::default();
let filtered = AtomicUsize::default();
crossbeam::scope(|s| -> Result<()> {
s.spawn(|_| {
let mut todo = VecDeque::new();
todo.push_back(config.root_dir.clone());
while let Some(path) = todo.pop_front() {
if path.is_dir() {
let mut entries = std::fs::read_dir(path)
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
entries.sort_by_key(|e| e.file_name());
for entry in entries {
todo.push_back(entry.path());
}
} else if file_filter(&path) {
submit.send(path).unwrap();
}
}
drop(submit);
});
let (finished_files_sender, finished_files_recv) = crossbeam::channel::unbounded();
enum TestResult {
Ok,
Failed,
Ignored,
}
s.spawn(|_| {
if config.quiet {
for (i, (_, result)) in finished_files_recv.into_iter().enumerate() {
let i = i + 1;
match result {
TestResult::Ok => eprint!("{}", ".".green()),
TestResult::Failed => eprint!("{}", "F".red().bold()),
TestResult::Ignored => eprint!("{}", "i".yellow()),
}
if i % 100 == 0 {
eprintln!(" {i}");
}
}
} else {
for (msg, result) in finished_files_recv {
eprint!("{msg} ... ");
eprintln!(
"{}",
match result {
TestResult::Ok => "ok".green(),
TestResult::Failed => "FAILED".red().bold(),
TestResult::Ignored => "ignored (in-test comment)".yellow(),
}
);
}
}
});
let mut threads = vec![];
for _ in 0..config.num_test_threads.get() {
let finished_files_sender = finished_files_sender.clone();
threads.push(s.spawn(|_| -> Result<()> {
let finished_files_sender = finished_files_sender;
for path in &receive {
if !config.path_filter.is_empty() {
let path_display = path.display().to_string();
if !config
.path_filter
.iter()
.any(|filter| path_display.contains(filter))
{
filtered.fetch_add(1, Ordering::Relaxed);
continue;
}
}
let comments = Comments::parse_file(&path)?;
if !test_file_conditions(&comments, &target, &config) {
ignored.fetch_add(1, Ordering::Relaxed);
finished_files_sender
.send((path.display().to_string(), TestResult::Ignored))?;
continue;
}
for revision in comments
.revisions
.clone()
.unwrap_or_else(|| vec![String::new()])
{
let (m, errors, stderr) =
run_test(&path, &config, &target, &revision, &comments);
let mut msg = format!("{}", path.display());
if !revision.is_empty() {
write!(msg, " (revision `{revision}`) ").unwrap();
}
if errors.is_empty() {
finished_files_sender.send((msg, TestResult::Ok))?;
succeeded.fetch_add(1, Ordering::Relaxed);
} else {
finished_files_sender.send((msg, TestResult::Failed))?;
failures.lock().unwrap().push((
path.clone(),
m,
revision,
errors,
stderr,
));
}
}
}
Ok(())
}));
}
for thread in threads {
thread.join().unwrap()?;
}
Ok(())
})
.unwrap()?;
let failures = failures.into_inner().unwrap();
let succeeded = succeeded.load(Ordering::Relaxed);
let ignored = ignored.load(Ordering::Relaxed);
let filtered = filtered.load(Ordering::Relaxed);
if !failures.is_empty() {
for (path, miri, revision, errors, stderr) in &failures {
eprintln!();
eprint!("{}", path.display().to_string().underline().bold());
if !revision.is_empty() {
eprint!(" (revision `{}`)", revision);
}
eprint!(" {}", "FAILED:".red().bold());
eprintln!();
eprintln!("command: {:?}", miri);
eprintln!();
for error in errors {
match error {
Error::ExitStatus(mode, exit_status) => eprintln!("{mode:?} got {exit_status}"),
Error::PatternNotFound {
pattern,
definition_line,
} => {
match pattern {
Pattern::SubString(s) => {
eprintln!("substring `{s}` {} in stderr output", "not found".red())
}
Pattern::Regex(r) => {
eprintln!("`/{r}/` does {} stderr output", "not match".red())
}
}
eprintln!(
"expected because of pattern here: {}:{definition_line}",
path.display().to_string().bold()
);
}
Error::NoPatternsFound => {
eprintln!("{}", "no error patterns found in failure test".red());
}
Error::PatternFoundInPassTest => {
eprintln!("{}", "error pattern found in success test".red())
}
Error::OutputDiffers {
path,
actual,
expected,
} => {
eprintln!("{}", "actual output differed from expected".underline());
eprintln!("{}", format!("--- {}", path.display()).red());
eprintln!("{}", "+++ <stderr output>".green());
diff::print_diff(expected, actual);
}
Error::ErrorsWithoutPattern { path: None, msgs } => {
eprintln!(
"There were {} unmatched diagnostics that occurred outside the testfile and had no pattern",
msgs.len(),
);
for Message { level, message } in msgs {
eprintln!(" {level:?}: {message}")
}
}
Error::ErrorsWithoutPattern {
path: Some((path, line)),
msgs,
} => {
eprintln!(
"There were {} unmatched diagnostics at {}:{line}",
msgs.len(),
path.display()
);
for Message { level, message } in msgs {
eprintln!(" {level:?}: {message}")
}
}
}
eprintln!();
}
eprintln!("full stderr:");
eprintln!("{}", stderr);
eprintln!();
}
eprintln!("{}", "FAILURES:".red().underline().bold());
for (path, _miri, _revision, _errors, _stderr) in &failures {
eprintln!(" {}", path.display());
}
eprintln!();
eprintln!(
"test result: {}. {} tests failed, {} tests passed, {} ignored, {} filtered out",
"FAIL".red(),
failures.len().to_string().red().bold(),
succeeded.to_string().green(),
ignored.to_string().yellow(),
filtered.to_string().yellow(),
);
std::process::exit(1);
}
eprintln!();
eprintln!(
"test result: {}. {} tests passed, {} ignored, {} filtered out",
"ok".green(),
succeeded.to_string().green(),
ignored.to_string().yellow(),
filtered.to_string().yellow(),
);
eprintln!();
Ok(())
}
#[derive(Debug)]
enum Error {
ExitStatus(Mode, ExitStatus),
PatternNotFound {
pattern: Pattern,
definition_line: usize,
},
NoPatternsFound,
PatternFoundInPassTest,
OutputDiffers {
path: PathBuf,
actual: String,
expected: String,
},
ErrorsWithoutPattern {
msgs: Vec<Message>,
path: Option<(PathBuf, usize)>,
},
}
type Errors = Vec<Error>;
fn run_test(
path: &Path,
config: &Config,
target: &str,
revision: &str,
comments: &Comments,
) -> (Command, Errors, String) {
let mut miri = Command::new(&config.program);
miri.args(config.args.iter());
miri.arg(path);
if !revision.is_empty() {
miri.arg(format!("--cfg={revision}"));
}
for arg in &comments.compile_flags {
miri.arg(arg);
}
miri.envs(comments.env_vars.iter().map(|(k, v)| (k, v)));
let output = miri.output().expect("could not execute miri");
let mut errors = config.mode.ok(output.status);
let stderr = check_test_result(
path,
config,
target,
revision,
comments,
&mut errors,
&output.stdout,
&output.stderr,
);
(miri, errors, stderr)
}
fn check_test_result(
path: &Path,
config: &Config,
target: &str,
revision: &str,
comments: &Comments,
errors: &mut Errors,
stdout: &[u8],
stderr: &[u8],
) -> String {
let diagnostics = rustc_stderr::process(path, stderr);
let stdout = std::str::from_utf8(stdout).unwrap();
let revised = |extension: &str| {
if revision.is_empty() {
extension.to_string()
} else {
format!("{}.{}", revision, extension)
}
};
check_output(
&diagnostics.rendered,
path,
errors,
revised("stderr"),
target,
&config.stderr_filters,
config,
comments,
);
check_output(
stdout,
path,
errors,
revised("stdout"),
target,
&config.stdout_filters,
config,
comments,
);
check_annotations(
diagnostics.messages,
diagnostics.messages_from_unknown_file_or_line,
path,
errors,
config,
revision,
comments,
);
diagnostics.rendered
}
fn check_annotations(
mut messages: Vec<Vec<Message>>,
mut messages_from_unknown_file_or_line: Vec<Message>,
path: &Path,
errors: &mut Errors,
config: &Config,
revision: &str,
comments: &Comments,
) {
if let Some((ref error_pattern, definition_line)) = comments.error_pattern {
if let Some(i) = messages_from_unknown_file_or_line
.iter()
.position(|msg| error_pattern.matches(&msg.message))
{
messages_from_unknown_file_or_line.remove(i);
} else {
errors.push(Error::PatternNotFound {
pattern: error_pattern.clone(),
definition_line,
});
}
}
let mut lowest_annotation_level = Level::Error;
for &ErrorMatch {
ref pattern,
revision: ref rev,
definition_line,
line,
level,
} in &comments.error_matches
{
if let Some(rev) = rev {
if rev != revision {
continue;
}
}
lowest_annotation_level = std::cmp::min(lowest_annotation_level, level);
if let Some(msgs) = messages.get_mut(line) {
let found = msgs
.iter()
.position(|msg| pattern.matches(&msg.message) && msg.level == level);
if let Some(found) = found {
msgs.remove(found);
continue;
}
}
errors.push(Error::PatternNotFound {
pattern: pattern.clone(),
definition_line,
});
}
let filter = |msgs: Vec<Message>| -> Vec<_> {
msgs.into_iter()
.filter(|msg| {
msg.level
>= comments
.require_annotations_for_level
.unwrap_or(lowest_annotation_level)
})
.collect()
};
let messages_from_unknown_file_or_line = filter(messages_from_unknown_file_or_line);
if !messages_from_unknown_file_or_line.is_empty() {
errors.push(Error::ErrorsWithoutPattern {
path: None,
msgs: messages_from_unknown_file_or_line,
});
}
for (line, msgs) in messages.into_iter().enumerate() {
let msgs = filter(msgs);
if !msgs.is_empty() {
errors.push(Error::ErrorsWithoutPattern {
path: Some((path.to_path_buf(), line)),
msgs,
});
}
}
match (
config.mode,
comments.error_pattern.is_some() || !comments.error_matches.is_empty(),
) {
(Mode::Pass, true) | (Mode::Panic, true) => errors.push(Error::PatternFoundInPassTest),
(
Mode::Fail {
require_patterns: true,
},
false,
) => errors.push(Error::NoPatternsFound),
_ => {}
}
}
fn check_output(
output: &str,
path: &Path,
errors: &mut Errors,
kind: String,
target: &str,
filters: &Filter,
config: &Config,
comments: &Comments,
) {
let output = normalize(path, output, filters, comments);
let path = output_path(path, comments, kind, target);
match config.output_conflict_handling {
OutputConflictHandling::Bless => {
if output.is_empty() {
let _ = std::fs::remove_file(path);
} else {
std::fs::write(path, &output).unwrap();
}
}
OutputConflictHandling::Error => {
let expected_output = std::fs::read_to_string(&path).unwrap_or_default();
if output != expected_output {
errors.push(Error::OutputDiffers {
path,
actual: output,
expected: expected_output,
});
}
}
OutputConflictHandling::Ignore => {}
}
}
fn output_path(path: &Path, comments: &Comments, kind: String, target: &str) -> PathBuf {
if comments.stderr_per_bitwidth {
return path.with_extension(format!("{}bit.{kind}", get_pointer_width(target)));
}
path.with_extension(kind)
}
fn test_condition(condition: &Condition, target: &str, config: &Config) -> bool {
match condition {
Condition::Bitwidth(bits) => get_pointer_width(target) == *bits,
Condition::Target(t) => target.contains(t),
Condition::OnHost => config.target.is_none(),
}
}
fn test_file_conditions(comments: &Comments, target: &str, config: &Config) -> bool {
if comments
.ignore
.iter()
.any(|c| test_condition(c, target, config))
{
return false;
}
comments
.only
.iter()
.all(|c| test_condition(c, target, config))
}
fn get_pointer_width(triple: &str) -> u8 {
if (triple.contains("64") && !triple.ends_with("gnux32") && !triple.ends_with("gnu_ilp32"))
|| triple.starts_with("s390x")
{
64
} else if triple.starts_with("avr") {
16
} else {
32
}
}
fn normalize(path: &Path, text: &str, filters: &Filter, comments: &Comments) -> String {
let mut text = text.replace(&path.parent().unwrap().display().to_string(), "$DIR");
if let Some(lib_path) = option_env!("RUSTC_LIB_PATH") {
text = text.replace(lib_path, "RUSTLIB");
}
for (regex, replacement) in filters.iter() {
text = regex.replace_all(&text, *replacement).to_string();
}
for (from, to) in &comments.normalize_stderr {
text = from.replace_all(&text, to).to_string();
}
text
}
impl Config {
fn get_host(&self) -> String {
rustc_version::VersionMeta::for_command(std::process::Command::new(&self.program))
.expect("failed to parse rustc version info")
.host
}
}
#[derive(Copy, Clone, Debug)]
pub enum Mode {
Pass,
Panic,
Fail {
require_patterns: bool,
},
}
impl Mode {
fn ok(self, status: ExitStatus) -> Errors {
match (status.code(), self) {
(Some(1), Mode::Fail { .. }) | (Some(101), Mode::Panic) | (Some(0), Mode::Pass) => {
vec![]
}
_ => vec![Error::ExitStatus(self, status)],
}
}
}