Skip to content

Commit 0c3adfb

Browse files
compiler: diagnose anon const items written as exprs
1 parent b922653 commit 0c3adfb

File tree

3 files changed

+8
-5
lines changed

3 files changed

+8
-5
lines changed

compiler/rustc_parse/src/parser/item.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,11 @@ impl<'a> Parser<'a> {
8181
span,
8282
"consider using `const` or `static` instead of `let` for global variables",
8383
);
84+
} else if self.parse_const_block(span, false).is_ok() {
85+
err.span_label(
86+
span,
87+
"if you meant to create an anonymous const, use `const (): _ = {};` instead"
88+
);
8489
} else {
8590
err.span_label(span, "expected item")
8691
.note("for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>");

tests/ui/inline-const/expr-in-item-context.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,8 @@ const _: () = {};
77
// const _ are often used as compile-time assertions that don't conflict with other const items
88

99
const { assert!(size_of::<u32>() <= size_of::<usize>()) };
10-
//~^ error: expected item
11-
//~| for a full list of items
10+
//~^ expected item, found keyword
11+
//~| if you meant to create an anonymous const
1212

1313
fn main() {
1414
const { assert!(size_of::<u32>() <= size_of::<usize>()) };

tests/ui/inline-const/expr-in-item-context.stderr

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,7 @@ error: expected item, found keyword `const`
22
--> $DIR/expr-in-item-context.rs:9:1
33
|
44
LL | const { assert!(size_of::<u32>() <= size_of::<usize>()) };
5-
| ^^^^^ expected item
6-
|
7-
= note: for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>
5+
| ^^^^^ if you meant to create an anonymous const, use `const (): _ = {};` instead
86

97
error: aborting due to 1 previous error
108

0 commit comments

Comments
 (0)