Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

compiler: suggest const _ for a misplaced const {} #128374

Draft
wants to merge 6 commits into
base: master
Choose a base branch
from
Draft
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 18 additions & 3 deletions compiler/rustc_parse/src/parser/item.rs
Original file line number Diff line number Diff line change
@@ -86,9 +86,24 @@ impl<'a> Parser<'a> {
"consider using `const` or `static` instead of `let` for global variables",
);
} else {
err.span_label(span, "expected item")
.note("for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>");
};
let snapshot = self.create_snapshot_for_diagnostic();
match self.parse_const_block(span, false) {
Ok(_) => {
err.span_suggestion_verbose(
span.shrink_to_lo(),
"to evaluate a const expression, use an anonymous const",
"const _: () = ",
Applicability::MaybeIncorrect,
);
}
Err(diag) => {
diag.cancel();
self.restore_snapshot(snapshot);
err.span_label(span, "expected item")
.note("for a full list of items that can appear in modules, see <https://doc.rust-lang.org/reference/items.html>");
}
}
}
return Err(err);
}
}
15 changes: 15 additions & 0 deletions tests/ui/inline-const/expr-in-item-context.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// reported in https://github.com/rust-lang/rust/issues/128338

// This had an overly-terse diagnostic, because we recognized this is where an item should be, but
// but didn't recognize an inline const in this place is probably trying to be an "anon const item".
// Those are written like this:
const _: () = {};
// const _ are often used as compile-time assertions that don't conflict with other const items

const { assert!(size_of::<u32>() <= size_of::<usize>()) };
//~^ expected item, found keyword
//~| to evaluate a const expression, use an anonymous const

fn main() {
const { assert!(size_of::<u32>() <= size_of::<usize>()) };
}
13 changes: 13 additions & 0 deletions tests/ui/inline-const/expr-in-item-context.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
error: expected item, found keyword `const`
--> $DIR/expr-in-item-context.rs:9:1
|
LL | const { assert!(size_of::<u32>() <= size_of::<usize>()) };
| ^^^^^
|
help: to evaluate a const expression, use an anonymous const
|
LL | const _: () = const { assert!(size_of::<u32>() <= size_of::<usize>()) };
| +++++++++++++

error: aborting due to 1 previous error

Loading