Skip to content

Commit cfb9778

Browse files
committed
compiletest: Improve diagnostics for line annotation mismatches
1 parent 5fe04cb commit cfb9778

File tree

5 files changed

+179
-39
lines changed

5 files changed

+179
-39
lines changed

src/tools/compiletest/src/errors.rs

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ pub enum ErrorKind {
1515
Note,
1616
Suggestion,
1717
Warning,
18+
/// Used for better recovery and diagnostics in compiletest.
19+
Unknown,
1820
}
1921

2022
impl ErrorKind {
@@ -30,20 +32,24 @@ impl ErrorKind {
3032

3133
/// Either the canonical uppercase string, or some additional versions for compatibility.
3234
/// FIXME: consider keeping only the canonical versions here.
33-
pub fn from_user_str(s: &str) -> ErrorKind {
34-
match s {
35+
fn from_user_str(s: &str) -> Option<ErrorKind> {
36+
Some(match s {
3537
"HELP" | "help" => ErrorKind::Help,
3638
"ERROR" | "error" => ErrorKind::Error,
37-
// `MONO_ITEM` makes annotations in `codegen-units` tests syntactically correct,
38-
// but those tests never use the error kind later on.
39-
"NOTE" | "note" | "MONO_ITEM" => ErrorKind::Note,
39+
"NOTE" | "note" => ErrorKind::Note,
4040
"SUGGESTION" => ErrorKind::Suggestion,
4141
"WARN" | "WARNING" | "warn" | "warning" => ErrorKind::Warning,
42-
_ => panic!(
42+
_ => return None,
43+
})
44+
}
45+
46+
pub fn expect_from_user_str(s: &str) -> ErrorKind {
47+
ErrorKind::from_user_str(s).unwrap_or_else(|| {
48+
panic!(
4349
"unexpected diagnostic kind `{s}`, expected \
4450
`ERROR`, `WARN`, `NOTE`, `HELP` or `SUGGESTION`"
45-
),
46-
}
51+
)
52+
})
4753
}
4854
}
4955

@@ -55,6 +61,7 @@ impl fmt::Display for ErrorKind {
5561
ErrorKind::Note => write!(f, "NOTE"),
5662
ErrorKind::Suggestion => write!(f, "SUGGESTION"),
5763
ErrorKind::Warning => write!(f, "WARN"),
64+
ErrorKind::Unknown => write!(f, "UNKNOWN"),
5865
}
5966
}
6067
}
@@ -72,11 +79,6 @@ pub struct Error {
7279
}
7380

7481
impl Error {
75-
pub fn render_for_expected(&self) -> String {
76-
use colored::Colorize;
77-
format!("{: <10}line {: >3}: {}", self.kind, self.line_num_str(), self.msg.cyan())
78-
}
79-
8082
pub fn line_num_str(&self) -> String {
8183
self.line_num.map_or("?".to_string(), |line_num| line_num.to_string())
8284
}
@@ -165,8 +167,10 @@ fn parse_expected(
165167
let rest = line[tag.end()..].trim_start();
166168
let (kind_str, _) =
167169
rest.split_once(|c: char| c != '_' && !c.is_ascii_alphabetic()).unwrap_or((rest, ""));
168-
let kind = ErrorKind::from_user_str(kind_str);
169-
let untrimmed_msg = &rest[kind_str.len()..];
170+
let (kind, untrimmed_msg) = match ErrorKind::from_user_str(kind_str) {
171+
Some(kind) => (kind, &rest[kind_str.len()..]),
172+
None => (ErrorKind::Unknown, rest),
173+
};
170174
let msg = untrimmed_msg.strip_prefix(':').unwrap_or(untrimmed_msg).trim().to_owned();
171175

172176
let line_num_adjust = &captures["adjust"];

src/tools/compiletest/src/header.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -593,7 +593,7 @@ impl TestProps {
593593
config.parse_name_value_directive(ln, DONT_REQUIRE_ANNOTATIONS)
594594
{
595595
self.dont_require_annotations
596-
.insert(ErrorKind::from_user_str(err_kind.trim()));
596+
.insert(ErrorKind::expect_from_user_str(err_kind.trim()));
597597
}
598598
},
599599
);

src/tools/compiletest/src/runtest.rs

Lines changed: 56 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -713,6 +713,7 @@ impl<'test> TestCx<'test> {
713713
// Parse the JSON output from the compiler and extract out the messages.
714714
let actual_errors = json::parse_output(&diagnostic_file_name, &proc_res.stderr, proc_res);
715715
let mut unexpected = Vec::new();
716+
let mut unimportant = Vec::new();
716717
let mut found = vec![false; expected_errors.len()];
717718
for mut actual_error in actual_errors {
718719
actual_error.msg = self.normalize_output(&actual_error.msg, &[]);
@@ -737,14 +738,9 @@ impl<'test> TestCx<'test> {
737738
&& expected_kinds.contains(&actual_error.kind)
738739
&& !self.props.dont_require_annotations.contains(&actual_error.kind)
739740
{
740-
self.error(&format!(
741-
"{}:{}: unexpected {}: '{}'",
742-
file_name,
743-
actual_error.line_num_str(),
744-
actual_error.kind,
745-
actual_error.msg
746-
));
747741
unexpected.push(actual_error);
742+
} else {
743+
unimportant.push(actual_error);
748744
}
749745
}
750746
}
@@ -754,39 +750,77 @@ impl<'test> TestCx<'test> {
754750
// anything not yet found is a problem
755751
for (index, expected_error) in expected_errors.iter().enumerate() {
756752
if !found[index] {
757-
self.error(&format!(
758-
"{}:{}: expected {} not found: {}",
759-
file_name,
760-
expected_error.line_num_str(),
761-
expected_error.kind,
762-
expected_error.msg
763-
));
764753
not_found.push(expected_error);
765754
}
766755
}
767756

768757
if !unexpected.is_empty() || !not_found.is_empty() {
769758
self.error(&format!(
770-
"{} unexpected errors found, {} expected errors not found",
759+
"{} unexpected diagnostics reported, {} expected diagnostics not reported",
771760
unexpected.len(),
772761
not_found.len()
773762
));
774-
println!("status: {}\ncommand: {}\n", proc_res.status, proc_res.cmdline);
763+
let print = |e: &Error| {
764+
println!("{file_name}:{}: {}: {}", e.line_num_str(), e.kind, e.msg.cyan())
765+
};
766+
// Fuzzy matching quality:
767+
// - message and line / message and kind - great, suggested
768+
// - only message - good, suggested
769+
// - known line and kind - ok, suggested
770+
// - only known line - meh, but suggested
771+
// - others are not worth suggesting
775772
if !unexpected.is_empty() {
776-
println!("{}", "--- unexpected errors (from JSON output) ---".green());
773+
println!("{}", "--- reported but not expected (from JSON output) ---".green());
777774
for error in &unexpected {
778-
println!("{}", error.render_for_expected());
775+
print(error);
776+
for candidate in &not_found {
777+
if error.msg.contains(&candidate.msg) {
778+
let prefix = if candidate.line_num != error.line_num {
779+
"expected on a different line"
780+
} else {
781+
"expected with a different kind"
782+
}
783+
.red();
784+
print!(" {prefix}: ");
785+
print(candidate);
786+
} else if candidate.line_num.is_some()
787+
&& candidate.line_num == error.line_num
788+
{
789+
print!(" {}: ", "expected with a different message".red());
790+
print(candidate);
791+
}
792+
}
779793
}
780794
println!("{}", "---".green());
781795
}
782796
if !not_found.is_empty() {
783-
println!("{}", "--- not found errors (from test file) ---".red());
797+
println!("{}", "--- expected but not reported (from test file) ---".red());
784798
for error in &not_found {
785-
println!("{}", error.render_for_expected());
799+
print(error);
800+
for candidate in unexpected.iter().chain(&unimportant) {
801+
if candidate.msg.contains(&error.msg) {
802+
let prefix = if candidate.line_num != error.line_num {
803+
"reported on a different line"
804+
} else {
805+
"reported with a different kind"
806+
}
807+
.green();
808+
print!(" {prefix}: ");
809+
print(candidate);
810+
} else if candidate.line_num.is_some()
811+
&& candidate.line_num == error.line_num
812+
{
813+
print!(" {}: ", "reported with a different message".green());
814+
print(candidate);
815+
}
816+
}
786817
}
787-
println!("{}", "---\n".red());
818+
println!("{}", "---".red());
788819
}
789-
panic!("errors differ from expected");
820+
panic!(
821+
"errors differ from expected\nstatus: {}\ncommand: {}\n",
822+
proc_res.status, proc_res.cmdline
823+
);
790824
}
791825
}
792826

@@ -2069,7 +2103,6 @@ impl<'test> TestCx<'test> {
20692103
println!("{}", String::from_utf8_lossy(&output.stdout));
20702104
eprintln!("{}", String::from_utf8_lossy(&output.stderr));
20712105
} else {
2072-
use colored::Colorize;
20732106
eprintln!("warning: no pager configured, falling back to unified diff");
20742107
eprintln!(
20752108
"help: try configuring a git pager (e.g. `delta`) with `git config --global core.pager delta`"
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//@ should-fail
2+
3+
// The warning is reported with unknown line
4+
//@ compile-flags: -D raw_pointer_derive
5+
//~? WARN kind and unknown line match the reported warning, but we do not suggest it
6+
7+
// The error is expected but not reported at all.
8+
//~ ERROR this error does not exist
9+
10+
// The error is reported but not expected at all.
11+
// "`main` function not found in crate" (the main function is intentionally not added)
12+
13+
// An "unimportant" diagnostic is expected on a wrong line.
14+
//~ ERROR aborting due to
15+
16+
// An "unimportant" diagnostic is expected with a wrong kind.
17+
//~? ERROR For more information about an error
18+
19+
fn wrong_line_or_kind() {
20+
// A diagnostic expected on a wrong line.
21+
unresolved1;
22+
//~ ERROR cannot find value `unresolved1` in this scope
23+
24+
// A diagnostic expected with a wrong kind.
25+
unresolved2; //~ WARN cannot find value `unresolved2` in this scope
26+
27+
// A diagnostic expected with a missing kind (treated as a wrong kind).
28+
unresolved3; //~ cannot find value `unresolved3` in this scope
29+
30+
// A diagnostic expected with a wrong line and kind.
31+
unresolved4;
32+
//~ WARN cannot find value `unresolved4` in this scope
33+
}
34+
35+
fn wrong_message() {
36+
// A diagnostic expected with a wrong message, but the line is known and right.
37+
unresolvedA; //~ ERROR stub message 1
38+
39+
// A diagnostic expected with a wrong message, but the line is known and right,
40+
// even if the kind doesn't match.
41+
unresolvedB; //~ WARN stub message 2
42+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
warning: lint `raw_pointer_derive` has been removed: using derive with raw pointers is ok
2+
|
3+
= note: requested on the command line with `-D raw_pointer_derive`
4+
= note: `#[warn(renamed_and_removed_lints)]` on by default
5+
6+
error[E0425]: cannot find value `unresolved1` in this scope
7+
--> $DIR/line-annotation-mismatches.rs:21:5
8+
|
9+
LL | unresolved1;
10+
| ^^^^^^^^^^^ not found in this scope
11+
12+
error[E0425]: cannot find value `unresolved2` in this scope
13+
--> $DIR/line-annotation-mismatches.rs:25:5
14+
|
15+
LL | unresolved2;
16+
| ^^^^^^^^^^^ not found in this scope
17+
18+
error[E0425]: cannot find value `unresolved3` in this scope
19+
--> $DIR/line-annotation-mismatches.rs:28:5
20+
|
21+
LL | unresolved3;
22+
| ^^^^^^^^^^^ not found in this scope
23+
24+
error[E0425]: cannot find value `unresolved4` in this scope
25+
--> $DIR/line-annotation-mismatches.rs:31:5
26+
|
27+
LL | unresolved4;
28+
| ^^^^^^^^^^^ not found in this scope
29+
30+
error[E0425]: cannot find value `unresolvedA` in this scope
31+
--> $DIR/line-annotation-mismatches.rs:37:5
32+
|
33+
LL | unresolvedA;
34+
| ^^^^^^^^^^^ not found in this scope
35+
36+
error[E0425]: cannot find value `unresolvedB` in this scope
37+
--> $DIR/line-annotation-mismatches.rs:41:5
38+
|
39+
LL | unresolvedB;
40+
| ^^^^^^^^^^^ not found in this scope
41+
42+
warning: lint `raw_pointer_derive` has been removed: using derive with raw pointers is ok
43+
|
44+
= note: requested on the command line with `-D raw_pointer_derive`
45+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
46+
47+
error[E0601]: `main` function not found in crate `line_annotation_mismatches`
48+
--> $DIR/line-annotation-mismatches.rs:42:2
49+
|
50+
LL | }
51+
| ^ consider adding a `main` function to `$DIR/line-annotation-mismatches.rs`
52+
53+
warning: lint `raw_pointer_derive` has been removed: using derive with raw pointers is ok
54+
|
55+
= note: requested on the command line with `-D raw_pointer_derive`
56+
= note: duplicate diagnostic emitted due to `-Z deduplicate-diagnostics=no`
57+
58+
error: aborting due to 7 previous errors; 3 warnings emitted
59+
60+
Some errors have detailed explanations: E0425, E0601.
61+
For more information about an error, try `rustc --explain E0425`.

0 commit comments

Comments
 (0)