From 57c9e17e84cbdad35cc3420306d59f6cc3f4c98c Mon Sep 17 00:00:00 2001 From: Robert Zakrzewski Date: Tue, 3 Dec 2024 15:32:06 +0100 Subject: [PATCH] Improve error when a keyword is used as identifier --- src/error.rs | 3 +++ src/parser/mod.rs | 16 ++++++++++++++++ src/parser/types.rs | 7 +++++++ 3 files changed, 26 insertions(+) diff --git a/src/error.rs b/src/error.rs index b6ec94e24..a4542e4a2 100644 --- a/src/error.rs +++ b/src/error.rs @@ -104,6 +104,9 @@ pub enum ErrorKind { #[error("invalid token, expected: {0}")] ExpectedToken(TokenKind), + #[error("invalid token, unexpected keyword: {0}, expected: {1}")] + ExpectedTokenNotKeyword(String, TokenKind), + #[error("invalid path: {0}")] InvalidPath(&'static str), diff --git a/src/parser/mod.rs b/src/parser/mod.rs index 3f09d2da0..e69ee0ee3 100644 --- a/src/parser/mod.rs +++ b/src/parser/mod.rs @@ -238,4 +238,20 @@ mod tests { let parsed = Stmt::parse(ctx, tokens).unwrap(); println!("{:?}", parsed); } + + #[test] + fn expected_token_not_keyword_as_identifier() { + let code = r#"Foo { pub: Field }"#; + let tokens = &mut Token::parse(0, code).unwrap(); + let ctx = &mut ParserCtx::default(); + let parsed = StructDef::parse(ctx, tokens); + assert!(parsed.is_err()); + assert!(parsed.as_ref().err().is_some()); + match &parsed.as_ref().err().unwrap().kind { + ErrorKind::ExpectedTokenNotKeyword(keyword, _) => { + assert_eq!(keyword, "pub"); + } + _ => panic!("expected error: ExpectedTokenNotKeyword"), + } + } } diff --git a/src/parser/types.rs b/src/parser/types.rs index a68a3c566..4b79db677 100644 --- a/src/parser/types.rs +++ b/src/parser/types.rs @@ -674,6 +674,13 @@ impl Ident { value: ident, span: token.span, }), + TokenKind::Keyword(keyword) => Err(ctx.error( + ErrorKind::ExpectedTokenNotKeyword( + keyword.to_string(), + TokenKind::Identifier("".to_string()), + ), + token.span, + )), _ => Err(ctx.error( ErrorKind::ExpectedToken(TokenKind::Identifier("".to_string())),