Skip to content

Commit c8133f6

Browse files
authored
Rollup merge of #91133 - terrarier2111:unsafe-diagnostic, r=jackh726
Improve `unsafe` diagnostic This fixes: #90880 I didn't use the exact proposed messages though.
2 parents 58f1179 + 3a13a72 commit c8133f6

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

compiler/rustc_parse/src/parser/item.rs

+25-3
Original file line numberDiff line numberDiff line change
@@ -999,10 +999,32 @@ impl<'a> Parser<'a> {
999999
attrs: &mut Vec<Attribute>,
10001000
unsafety: Unsafe,
10011001
) -> PResult<'a, ItemInfo> {
1002+
let sp_start = self.prev_token.span;
10021003
let abi = self.parse_abi(); // ABI?
1003-
let items = self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?;
1004-
let module = ast::ForeignMod { unsafety, abi, items };
1005-
Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1004+
match self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No)) {
1005+
Ok(items) => {
1006+
let module = ast::ForeignMod { unsafety, abi, items };
1007+
Ok((Ident::empty(), ItemKind::ForeignMod(module)))
1008+
}
1009+
Err(mut err) => {
1010+
let current_qual_sp = self.prev_token.span;
1011+
let current_qual_sp = current_qual_sp.to(sp_start);
1012+
if let Ok(current_qual) = self.span_to_snippet(current_qual_sp) {
1013+
if err.message() == "expected `{`, found keyword `unsafe`" {
1014+
let invalid_qual_sp = self.token.uninterpolated_span();
1015+
let invalid_qual = self.span_to_snippet(invalid_qual_sp).unwrap();
1016+
1017+
err.span_suggestion(
1018+
current_qual_sp.to(invalid_qual_sp),
1019+
&format!("`{}` must come before `{}`", invalid_qual, current_qual),
1020+
format!("{} {}", invalid_qual, current_qual),
1021+
Applicability::MachineApplicable,
1022+
).note("keyword order for functions declaration is `default`, `pub`, `const`, `async`, `unsafe`, `extern`");
1023+
}
1024+
}
1025+
Err(err)
1026+
}
1027+
}
10061028
}
10071029

10081030
/// Parses a foreign item (one in an `extern { ... }` block).

src/test/ui/parser/issues/issue-19398.stderr

+6-1
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,15 @@ error: expected `{`, found keyword `unsafe`
44
LL | trait T {
55
| - while parsing this item list starting here
66
LL | extern "Rust" unsafe fn foo();
7-
| ^^^^^^ expected `{`
7+
| --------------^^^^^^
8+
| | |
9+
| | expected `{`
10+
| help: `unsafe` must come before `extern "Rust"`: `unsafe extern "Rust"`
811
LL |
912
LL | }
1013
| - the item list ends here
14+
|
15+
= note: keyword order for functions declaration is `default`, `pub`, `const`, `async`, `unsafe`, `extern`
1116

1217
error: aborting due to previous error
1318

0 commit comments

Comments
 (0)