Skip to content

Commit ea6700c

Browse files
committed
Allow matching errors and warnings by error code.
1 parent 5898e04 commit ea6700c

14 files changed

+316
-71
lines changed

README.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,16 @@ A smaller version of compiletest-rs
1111
## Supported magic comment annotations
1212

1313
If your test tests for failure, you need to add a `//~` annotation where the error is happening
14-
to make sure that the test will always keep failing with a specific message at the annotated line.
14+
to ensure that the test will always keep failing at the annotated line. These comments can take two forms:
1515

16-
`//~ ERROR: XXX` make sure the stderr output contains `XXX` for an error in the line where this comment is written
17-
18-
* Also supports `HELP`, `WARN` or `NOTE` for different kind of message
19-
* if one of those levels is specified explicitly, *all* diagnostics of this level or higher need an annotation. If you want to avoid this, just leave out the all caps level note entirely.
20-
* If the all caps note is left out, a message of any level is matched. Leaving it out is not allowed for `ERROR` levels.
21-
* This checks the output *before* normalization, so you can check things that get normalized away, but need to
22-
be careful not to accidentally have a pattern that differs between platforms.
23-
* if `XXX` is of the form `/XXX/` it is treated as a regex instead of a substring and will succeed if the regex matches.
16+
* `//~ LEVEL: XXX` matches by error level and message text
17+
* `LEVEL` can be one of the following (descending order): `ERROR`, `HELP`, `WARN` or `NOTE`
18+
* If a level is specified explicitly, *all* diagnostics of that level or higher need an annotation. To avoid this see `//@require-annotations-for-level`
19+
* This checks the output *before* normalization, so you can check things that get normalized away, but need to
20+
be careful not to accidentally have a pattern that differs between platforms.
21+
* if `XXX` is of the form `/XXX/` it is treated as a regex instead of a substring and will succeed if the regex matches.
22+
* `//~ CODE` matches by diagnostic code.
23+
* `CODE` can take multiple forms such as: `E####`, `lint_name`, `tool::lint_name`.
2424

2525
In order to change how a single test is tested, you can add various `//@` comments to the test.
2626
Any other comments will be ignored, and all `//@` comments must be formatted precisely as

src/error.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,13 @@ pub enum Error {
2525
/// Can be `None` when it is expected outside the current file
2626
expected_line: Option<NonZeroUsize>,
2727
},
28+
/// A diagnostic code matcher was declared but had no matching error.
29+
CodeNotFound {
30+
/// The code that was not found, and the span of where that code was declared.
31+
code: Spanned<String>,
32+
/// Can be `None` when it is expected outside the current file
33+
expected_line: Option<NonZeroUsize>,
34+
},
2835
/// A ui test checking for failure does not have any failure patterns
2936
NoPatternsFound,
3037
/// A ui test checking for success has failure patterns

src/lib.rs

Lines changed: 44 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ use color_eyre::eyre::{eyre, Result};
1414
use crossbeam_channel::{unbounded, Receiver, Sender};
1515
use dependencies::{Build, BuildManager};
1616
use lazy_static::lazy_static;
17-
use parser::{ErrorMatch, MaybeSpanned, OptWithLine, Revisioned, Spanned};
17+
use parser::{ErrorMatch, ErrorMatchKind, MaybeSpanned, OptWithLine, Revisioned, Spanned};
1818
use regex::bytes::{Captures, Regex};
1919
use rustc_stderr::{Level, Message, Span};
2020
use status_emitter::{StatusEmitter, TestStatus};
@@ -1092,35 +1092,58 @@ fn check_annotations(
10921092
// We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
10931093
// are matched.
10941094
let mut lowest_annotation_level = Level::Error;
1095-
for &ErrorMatch {
1096-
ref pattern,
1097-
level,
1098-
line,
1099-
} in comments
1095+
for &ErrorMatch { ref kind, line } in comments
11001096
.for_revision(revision)
11011097
.flat_map(|r| r.error_matches.iter())
11021098
{
1103-
seen_error_match = Some(pattern.span());
1104-
// If we found a diagnostic with a level annotation, make sure that all
1105-
// diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
1106-
// for this pattern.
1107-
if lowest_annotation_level > level {
1108-
lowest_annotation_level = level;
1099+
match kind {
1100+
ErrorMatchKind::Code(code) => {
1101+
seen_error_match = Some(code.span());
1102+
}
1103+
&ErrorMatchKind::Pattern { ref pattern, level } => {
1104+
seen_error_match = Some(pattern.span());
1105+
// If we found a diagnostic with a level annotation, make sure that all
1106+
// diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
1107+
// for this pattern.
1108+
if lowest_annotation_level > level {
1109+
lowest_annotation_level = level;
1110+
}
1111+
}
11091112
}
11101113

11111114
if let Some(msgs) = messages.get_mut(line.get()) {
1112-
let found = msgs
1113-
.iter()
1114-
.position(|msg| pattern.matches(&msg.message) && msg.level == level);
1115-
if let Some(found) = found {
1116-
msgs.remove(found);
1117-
continue;
1115+
match kind {
1116+
&ErrorMatchKind::Pattern { ref pattern, level } => {
1117+
let found = msgs
1118+
.iter()
1119+
.position(|msg| pattern.matches(&msg.message) && msg.level == level);
1120+
if let Some(found) = found {
1121+
msgs.remove(found);
1122+
continue;
1123+
}
1124+
}
1125+
ErrorMatchKind::Code(code) => {
1126+
let found = msgs.iter().position(|msg| {
1127+
msg.level >= Level::Warn
1128+
&& msg.code.as_ref().is_some_and(|msg| *msg == **code)
1129+
});
1130+
if let Some(found) = found {
1131+
msgs.remove(found);
1132+
continue;
1133+
}
1134+
}
11181135
}
11191136
}
11201137

1121-
errors.push(Error::PatternNotFound {
1122-
pattern: pattern.clone(),
1123-
expected_line: Some(line),
1138+
errors.push(match kind {
1139+
ErrorMatchKind::Pattern { pattern, .. } => Error::PatternNotFound {
1140+
pattern: pattern.clone(),
1141+
expected_line: Some(line),
1142+
},
1143+
ErrorMatchKind::Code(code) => Error::CodeNotFound {
1144+
code: code.clone(),
1145+
expected_line: Some(line),
1146+
},
11241147
});
11251148
}
11261149

src/parser.rs

Lines changed: 57 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -178,10 +178,20 @@ pub enum Pattern {
178178
Regex(Regex),
179179
}
180180

181+
#[derive(Debug, Clone)]
182+
pub(crate) enum ErrorMatchKind {
183+
/// A level and pattern pair parsed from a `//~ LEVEL: Message` comment.
184+
Pattern {
185+
pattern: Spanned<Pattern>,
186+
level: Level,
187+
},
188+
/// An error code parsed from a `//~ error_code` comment.
189+
Code(Spanned<String>),
190+
}
191+
181192
#[derive(Debug)]
182193
pub(crate) struct ErrorMatch {
183-
pub pattern: Spanned<Pattern>,
184-
pub level: Level,
194+
pub(crate) kind: ErrorMatchKind,
185195
/// The line this pattern is expecting to find a message in.
186196
pub line: NonZeroUsize,
187197
}
@@ -260,6 +270,7 @@ impl Comments {
260270
}
261271
}
262272
}
273+
263274
if parser.errors.is_empty() {
264275
Ok(parser.comments)
265276
} else {
@@ -707,7 +718,10 @@ impl<CommentsType> CommentParser<CommentsType> {
707718
}
708719

709720
impl CommentParser<&mut Revisioned> {
710-
// parse something like (\[[a-z]+(,[a-z]+)*\])?(?P<offset>\||[\^]+)? *(?P<level>ERROR|HELP|WARN|NOTE): (?P<text>.*)
721+
// parse something like:
722+
// (\[[a-z]+(,[a-z]+)*\])?
723+
// (?P<offset>\||[\^]+)? *
724+
// ((?P<level>ERROR|HELP|WARN|NOTE): (?P<text>.*))|(?P<code>[a-z0-9_:]+)
711725
fn parse_pattern(&mut self, pattern: Spanned<&str>, fallthrough_to: &mut Option<NonZeroUsize>) {
712726
let (match_line, pattern) = match pattern.chars().next() {
713727
Some('|') => (
@@ -750,43 +764,52 @@ impl CommentParser<&mut Revisioned> {
750764
};
751765

752766
let pattern = pattern.trim_start();
753-
let offset = match pattern.chars().position(|c| !c.is_ascii_alphabetic()) {
754-
Some(offset) => offset,
755-
None => {
756-
self.error(pattern.span(), "pattern without level");
757-
return;
758-
}
759-
};
767+
let offset = pattern
768+
.bytes()
769+
.position(|c| !(c.is_ascii_alphanumeric() || c == b'_' || c == b':'))
770+
.unwrap_or(pattern.len());
771+
772+
let (level_or_code, pattern) = pattern.split_at(offset);
773+
if let Some(level) = level_or_code.strip_suffix(":") {
774+
let level = match (*level).parse() {
775+
Ok(level) => level,
776+
Err(msg) => {
777+
self.error(level.span(), msg);
778+
return;
779+
}
780+
};
760781

761-
let (level, pattern) = pattern.split_at(offset);
762-
let level = match (*level).parse() {
763-
Ok(level) => level,
764-
Err(msg) => {
765-
self.error(level.span(), msg);
766-
return;
767-
}
768-
};
769-
let pattern = match pattern.strip_prefix(":") {
770-
Some(offset) => offset,
771-
None => {
772-
self.error(pattern.span(), "no `:` after level found");
773-
return;
774-
}
775-
};
782+
let pattern = pattern.trim();
776783

777-
let pattern = pattern.trim();
784+
self.check(pattern.span(), !pattern.is_empty(), "no pattern specified");
778785

779-
self.check(pattern.span(), !pattern.is_empty(), "no pattern specified");
786+
let pattern = self.parse_error_pattern(pattern);
780787

781-
let pattern = self.parse_error_pattern(pattern);
788+
self.error_matches.push(ErrorMatch {
789+
kind: ErrorMatchKind::Pattern { pattern, level },
790+
line: match_line,
791+
});
792+
} else if (*level_or_code).parse::<Level>().is_ok() {
793+
// Shouldn't conflict with any real diagnostic code
794+
self.error(pattern.span(), "no `:` after level found");
795+
return;
796+
} else if !pattern.trim_start().is_empty() {
797+
self.error(
798+
pattern.span(),
799+
format!("text found after error code `{}`", *level_or_code),
800+
);
801+
return;
802+
} else {
803+
self.error_matches.push(ErrorMatch {
804+
kind: ErrorMatchKind::Code(Spanned::new(
805+
level_or_code.to_string(),
806+
level_or_code.span(),
807+
)),
808+
line: match_line,
809+
});
810+
};
782811

783812
*fallthrough_to = Some(match_line);
784-
785-
self.error_matches.push(ErrorMatch {
786-
pattern,
787-
level,
788-
line: match_line,
789-
});
790813
}
791814
}
792815

src/parser/tests.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use crate::{
2-
parser::{Condition, Pattern},
2+
parser::{Condition, ErrorMatchKind, Pattern},
33
Error,
44
};
55

@@ -18,8 +18,11 @@ fn main() {
1818
println!("parsed comments: {:#?}", comments);
1919
assert_eq!(comments.revisioned.len(), 1);
2020
let revisioned = &comments.revisioned[&vec![]];
21-
assert_eq!(revisioned.error_matches[0].pattern.line().get(), 5);
22-
match &*revisioned.error_matches[0].pattern {
21+
let ErrorMatchKind::Pattern { pattern, .. } = &revisioned.error_matches[0].kind else {
22+
panic!("expected pattern matcher");
23+
};
24+
assert_eq!(pattern.line().get(), 5);
25+
match &**pattern {
2326
Pattern::SubString(s) => {
2427
assert_eq!(
2528
s,
@@ -30,6 +33,24 @@ fn main() {
3033
}
3134
}
3235

36+
#[test]
37+
fn parse_error_code_comment() {
38+
let s = r"
39+
fn main() {
40+
let _x: i32 = 0u32; //~ E0308
41+
}
42+
";
43+
let comments = Comments::parse(s).unwrap();
44+
println!("parsed comments: {:#?}", comments);
45+
assert_eq!(comments.revisioned.len(), 1);
46+
let revisioned = &comments.revisioned[&vec![]];
47+
let ErrorMatchKind::Code(code) = &revisioned.error_matches[0].kind else {
48+
panic!("expected diagnostic code matcher");
49+
};
50+
assert_eq!(code.line().get(), 3);
51+
assert_eq!(**code, "E0308");
52+
}
53+
3354
#[test]
3455
fn parse_missing_level() {
3556
let s = r"
@@ -44,7 +65,7 @@ fn main() {
4465
assert_eq!(errors.len(), 1);
4566
match &errors[0] {
4667
Error::InvalidComment { msg, span } if span.line_start.get() == 5 => {
47-
assert_eq!(msg, "unknown level `encountered`")
68+
assert_eq!(msg, "text found after error code `encountered`")
4869
}
4970
_ => unreachable!(),
5071
}

src/rustc_stderr.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,19 @@ use std::{
55
path::{Path, PathBuf},
66
};
77

8+
#[derive(serde::Deserialize, Debug)]
9+
struct RustcDiagnosticCode {
10+
code: String,
11+
}
12+
813
#[derive(serde::Deserialize, Debug)]
914
struct RustcMessage {
1015
rendered: Option<String>,
1116
spans: Vec<RustcSpan>,
1217
level: String,
1318
message: String,
1419
children: Vec<RustcMessage>,
20+
code: Option<RustcDiagnosticCode>,
1521
}
1622

1723
#[derive(Copy, Clone, Debug, PartialOrd, Ord, PartialEq, Eq)]
@@ -31,6 +37,7 @@ pub struct Message {
3137
pub(crate) level: Level,
3238
pub(crate) message: String,
3339
pub(crate) line_col: Option<Span>,
40+
pub(crate) code: Option<String>,
3441
}
3542

3643
/// Information about macro expansion.
@@ -126,6 +133,7 @@ impl RustcMessage {
126133
level: self.level.parse().unwrap(),
127134
message: self.message,
128135
line_col: line,
136+
code: self.code.map(|x| x.code),
129137
};
130138
if let Some(line) = line {
131139
if messages.len() <= line.line_start.get() {

0 commit comments

Comments
 (0)