From 98518c2379d4bcf6909817758eb0bfd50557d51b Mon Sep 17 00:00:00 2001 From: chenyukang Date: Thu, 11 Aug 2022 22:26:26 +0800 Subject: [PATCH] suggest const or static for global variable --- compiler/rustc_parse/src/parser/item.rs | 7 ++++++- src/test/ui/parser/suggest-const-for-global-var.rs | 6 ++++++ src/test/ui/parser/suggest-const-for-global-var.stderr | 8 ++++++++ 3 files changed, 20 insertions(+), 1 deletion(-) create mode 100644 src/test/ui/parser/suggest-const-for-global-var.rs create mode 100644 src/test/ui/parser/suggest-const-for-global-var.stderr diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index 72c23776d3399..197c038489835 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -68,7 +68,12 @@ impl<'a> Parser<'a> { if !self.maybe_consume_incorrect_semicolon(&items) { let msg = &format!("expected item, found {token_str}"); let mut err = self.struct_span_err(self.token.span, msg); - err.span_label(self.token.span, "expected item"); + let label = if self.is_kw_followed_by_ident(kw::Let) { + "consider using `const` or `static` instead of `let` for global variables" + } else { + "expected item" + }; + err.span_label(self.token.span, label); return Err(err); } } diff --git a/src/test/ui/parser/suggest-const-for-global-var.rs b/src/test/ui/parser/suggest-const-for-global-var.rs new file mode 100644 index 0000000000000..d6216cb7ac275 --- /dev/null +++ b/src/test/ui/parser/suggest-const-for-global-var.rs @@ -0,0 +1,6 @@ +let X: i32 = 12; +//~^ ERROR expected item, found keyword `let` + +fn main() { + println!("{}", X); +} diff --git a/src/test/ui/parser/suggest-const-for-global-var.stderr b/src/test/ui/parser/suggest-const-for-global-var.stderr new file mode 100644 index 0000000000000..94e44ec7f6ce1 --- /dev/null +++ b/src/test/ui/parser/suggest-const-for-global-var.stderr @@ -0,0 +1,8 @@ +error: expected item, found keyword `let` + --> $DIR/suggest-const-for-global-var.rs:1:1 + | +LL | let X: i32 = 12; + | ^^^ consider using `const` or `static` instead of `let` for global variables + +error: aborting due to previous error +