Skip to content

Commit

Permalink
Merge pull request #239 from zedar/fix/better_error_when_keyword_as_i…
Browse files Browse the repository at this point in the history
…dentifier

Improve error when a keyword is used as identifier
  • Loading branch information
mimoo authored Dec 10, 2024
2 parents 5c048f4 + 57c9e17 commit 321b047
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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),

Expand Down
16 changes: 16 additions & 0 deletions src/parser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
}
}
}
7 changes: 7 additions & 0 deletions src/parser/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())),
Expand Down

0 comments on commit 321b047

Please sign in to comment.