Skip to content

Commit d727690

Browse files
Jarchooli-obk
authored andcommitted
Allow matching errors and warnings by error code.
1 parent 963dfb2 commit d727690

File tree

16 files changed

+414
-79
lines changed

16 files changed

+414
-79
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1111

1212
* Started maintaining a changelog
1313
* `Config::comment_defaults` allows setting `//@` comments for all tests
14+
* `//~` comments can now specify just an error code or lint name, without any message. ERROR level is implied
1415

1516
### Fixed
1617

README.md

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,17 @@ A stable 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`.
24+
* This will only match a diagnostic at the `ERROR` level.
2425

2526
In order to change how a single test is tested, you can add various `//@` comments to the test.
2627
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, OptWithLine, Revisioned, Spanned};
17+
use parser::{ErrorMatch, ErrorMatchKind, OptWithLine, Revisioned, Spanned};
1818
use regex::bytes::{Captures, Regex};
1919
use rustc_stderr::{Level, Message};
2020
use spanned::Span;
@@ -1076,35 +1076,58 @@ fn check_annotations(
10761076
// We will ensure that *all* diagnostics of level at least `lowest_annotation_level`
10771077
// are matched.
10781078
let mut lowest_annotation_level = Level::Error;
1079-
for &ErrorMatch {
1080-
ref pattern,
1081-
level,
1082-
line,
1083-
} in comments
1079+
for &ErrorMatch { ref kind, line } in comments
10841080
.for_revision(revision)
10851081
.flat_map(|r| r.error_matches.iter())
10861082
{
1087-
seen_error_match = Some(pattern.span());
1088-
// If we found a diagnostic with a level annotation, make sure that all
1089-
// diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
1090-
// for this pattern.
1091-
if lowest_annotation_level > level {
1092-
lowest_annotation_level = level;
1083+
match kind {
1084+
ErrorMatchKind::Code(code) => {
1085+
seen_error_match = Some(code.span());
1086+
}
1087+
&ErrorMatchKind::Pattern { ref pattern, level } => {
1088+
seen_error_match = Some(pattern.span());
1089+
// If we found a diagnostic with a level annotation, make sure that all
1090+
// diagnostics of that level have annotations, even if we don't end up finding a matching diagnostic
1091+
// for this pattern.
1092+
if lowest_annotation_level > level {
1093+
lowest_annotation_level = level;
1094+
}
1095+
}
10931096
}
10941097

10951098
if let Some(msgs) = messages.get_mut(line.get()) {
1096-
let found = msgs
1097-
.iter()
1098-
.position(|msg| pattern.matches(&msg.message) && msg.level == level);
1099-
if let Some(found) = found {
1100-
msgs.remove(found);
1101-
continue;
1099+
match kind {
1100+
&ErrorMatchKind::Pattern { ref pattern, level } => {
1101+
let found = msgs
1102+
.iter()
1103+
.position(|msg| pattern.matches(&msg.message) && msg.level == level);
1104+
if let Some(found) = found {
1105+
msgs.remove(found);
1106+
continue;
1107+
}
1108+
}
1109+
ErrorMatchKind::Code(code) => {
1110+
let found = msgs.iter().position(|msg| {
1111+
msg.level == Level::Error
1112+
&& msg.code.as_ref().is_some_and(|msg| *msg == **code)
1113+
});
1114+
if let Some(found) = found {
1115+
msgs.remove(found);
1116+
continue;
1117+
}
1118+
}
11021119
}
11031120
}
11041121

1105-
errors.push(Error::PatternNotFound {
1106-
pattern: pattern.clone(),
1107-
expected_line: Some(line),
1122+
errors.push(match kind {
1123+
ErrorMatchKind::Pattern { pattern, .. } => Error::PatternNotFound {
1124+
pattern: pattern.clone(),
1125+
expected_line: Some(line),
1126+
},
1127+
ErrorMatchKind::Code(code) => Error::CodeNotFound {
1128+
code: code.clone(),
1129+
expected_line: Some(line),
1130+
},
11081131
});
11091132
}
11101133

src/parser.rs

Lines changed: 57 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -212,10 +212,20 @@ pub enum Pattern {
212212
Regex(Regex),
213213
}
214214

215+
#[derive(Debug, Clone)]
216+
pub(crate) enum ErrorMatchKind {
217+
/// A level and pattern pair parsed from a `//~ LEVEL: Message` comment.
218+
Pattern {
219+
pattern: Spanned<Pattern>,
220+
level: Level,
221+
},
222+
/// An error code parsed from a `//~ error_code` comment.
223+
Code(Spanned<String>),
224+
}
225+
215226
#[derive(Debug, Clone)]
216227
pub(crate) struct ErrorMatch {
217-
pub pattern: Spanned<Pattern>,
218-
pub level: Level,
228+
pub(crate) kind: ErrorMatchKind,
219229
/// The line this pattern is expecting to find a message in.
220230
pub line: NonZeroUsize,
221231
}
@@ -302,6 +312,7 @@ impl Comments {
302312
}
303313
}
304314
}
315+
305316
let Revisioned {
306317
span,
307318
ignore,
@@ -788,7 +799,10 @@ impl<CommentsType> CommentParser<CommentsType> {
788799
}
789800

790801
impl CommentParser<&mut Revisioned> {
791-
// parse something like (\[[a-z]+(,[a-z]+)*\])?(?P<offset>\||[\^]+)? *(?P<level>ERROR|HELP|WARN|NOTE): (?P<text>.*)
802+
// parse something like:
803+
// (\[[a-z]+(,[a-z]+)*\])?
804+
// (?P<offset>\||[\^]+)? *
805+
// ((?P<level>ERROR|HELP|WARN|NOTE): (?P<text>.*))|(?P<code>[a-z0-9_:]+)
792806
fn parse_pattern(&mut self, pattern: Spanned<&str>, fallthrough_to: &mut Option<NonZeroUsize>) {
793807
let (match_line, pattern) = match pattern.chars().next() {
794808
Some('|') => (
@@ -831,43 +845,52 @@ impl CommentParser<&mut Revisioned> {
831845
};
832846

833847
let pattern = pattern.trim_start();
834-
let offset = match pattern.chars().position(|c| !c.is_ascii_alphabetic()) {
835-
Some(offset) => offset,
836-
None => {
837-
self.error(pattern.span(), "pattern without level");
838-
return;
839-
}
840-
};
848+
let offset = pattern
849+
.bytes()
850+
.position(|c| !(c.is_ascii_alphanumeric() || c == b'_' || c == b':'))
851+
.unwrap_or(pattern.len());
852+
853+
let (level_or_code, pattern) = pattern.split_at(offset);
854+
if let Some(level) = level_or_code.strip_suffix(":") {
855+
let level = match (*level).parse() {
856+
Ok(level) => level,
857+
Err(msg) => {
858+
self.error(level.span(), msg);
859+
return;
860+
}
861+
};
841862

842-
let (level, pattern) = pattern.split_at(offset);
843-
let level = match (*level).parse() {
844-
Ok(level) => level,
845-
Err(msg) => {
846-
self.error(level.span(), msg);
847-
return;
848-
}
849-
};
850-
let pattern = match pattern.strip_prefix(":") {
851-
Some(offset) => offset,
852-
None => {
853-
self.error(pattern.span(), "no `:` after level found");
854-
return;
855-
}
856-
};
863+
let pattern = pattern.trim();
857864

858-
let pattern = pattern.trim();
865+
self.check(pattern.span(), !pattern.is_empty(), "no pattern specified");
859866

860-
self.check(pattern.span(), !pattern.is_empty(), "no pattern specified");
867+
let pattern = self.parse_error_pattern(pattern);
861868

862-
let pattern = self.parse_error_pattern(pattern);
869+
self.error_matches.push(ErrorMatch {
870+
kind: ErrorMatchKind::Pattern { pattern, level },
871+
line: match_line,
872+
});
873+
} else if (*level_or_code).parse::<Level>().is_ok() {
874+
// Shouldn't conflict with any real diagnostic code
875+
self.error(level_or_code.span(), "no `:` after level found");
876+
return;
877+
} else if !pattern.trim_start().is_empty() {
878+
self.error(
879+
pattern.span(),
880+
format!("text found after error code `{}`", *level_or_code),
881+
);
882+
return;
883+
} else {
884+
self.error_matches.push(ErrorMatch {
885+
kind: ErrorMatchKind::Code(Spanned::new(
886+
level_or_code.to_string(),
887+
level_or_code.span(),
888+
)),
889+
line: match_line,
890+
});
891+
};
863892

864893
*fallthrough_to = Some(match_line);
865-
866-
self.error_matches.push(ErrorMatch {
867-
pattern,
868-
level,
869-
line: match_line,
870-
});
871894
}
872895
}
873896

src/parser/tests.rs

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
use std::path::Path;
22

33
use crate::{
4-
parser::{Condition, Pattern},
4+
parser::{Condition, ErrorMatchKind, Pattern},
55
Error,
66
};
77

@@ -20,8 +20,11 @@ fn main() {
2020
println!("parsed comments: {:#?}", comments);
2121
assert_eq!(comments.revisioned.len(), 1);
2222
let revisioned = &comments.revisioned[&vec![]];
23-
assert_eq!(revisioned.error_matches[0].pattern.line().get(), 5);
24-
match &*revisioned.error_matches[0].pattern {
23+
let ErrorMatchKind::Pattern { pattern, .. } = &revisioned.error_matches[0].kind else {
24+
panic!("expected pattern matcher");
25+
};
26+
assert_eq!(pattern.line().get(), 5);
27+
match &**pattern {
2528
Pattern::SubString(s) => {
2629
assert_eq!(
2730
s,
@@ -32,6 +35,24 @@ fn main() {
3235
}
3336
}
3437

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

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)]
@@ -37,6 +43,7 @@ pub struct Message {
3743
pub(crate) level: Level,
3844
pub(crate) message: String,
3945
pub(crate) line_col: Option<spanned::Span>,
46+
pub(crate) code: Option<String>,
4047
}
4148

4249
/// Information about macro expansion.
@@ -107,6 +114,7 @@ impl RustcMessage {
107114
level: self.level.parse().unwrap(),
108115
message: self.message,
109116
line_col: line.clone(),
117+
code: self.code.map(|x| x.code),
110118
};
111119
if let Some(line) = line.clone() {
112120
if messages.len() <= line.line_start.get() {

0 commit comments

Comments
 (0)