Skip to content

Commit

Permalink
Emit UnclosedRbrace err token in the lexer
Browse files Browse the repository at this point in the history
  • Loading branch information
dhruvmanila committed Aug 28, 2023
1 parent 8f28d97 commit 2a75ece
Showing 1 changed file with 37 additions and 2 deletions.
39 changes: 37 additions & 2 deletions crates/ruff_python_parser/src/lexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -689,6 +689,29 @@ impl<'source> Lexer<'source> {
false
};

if let Some(fstring_context) = self.fstring_stack.last() {
// When we are in an f-string, check whether does the initial quote
// matches with f-strings quotes and if it is, then this must be a
// missing '}' token so raise the proper error.
if fstring_context.quote_char.as_char() == quote {
match fstring_context.quote_size {
StringQuoteSize::Single if !triple_quoted => {
return Err(LexicalError {
error: LexicalErrorType::FStringError(FStringErrorType::UnclosedLbrace),
location: self.offset() - TextSize::new(1),
});
}
StringQuoteSize::Triple if triple_quoted => {
return Err(LexicalError {
error: LexicalErrorType::FStringError(FStringErrorType::UnclosedLbrace),
location: self.offset() - TextSize::new(3),
});
}
_ => {}
}
}
}

let value_start = self.offset();

let value_end = loop {
Expand Down Expand Up @@ -2119,14 +2142,26 @@ allowed {x}"""} string""#;
LexicalErrorType::FStringError(error) => error,
_ => panic!("Expected FStringError: {err:?}"),
},
_ => panic!("Expected exactly one FStringError"),
_ => panic!("Expected atleast one FStringError"),
}
}

#[test]
fn test_fstring_error() {
use FStringErrorType::{UnterminatedString, UnterminatedTripleQuotedString};
use FStringErrorType::{
UnclosedLbrace, UnterminatedString, UnterminatedTripleQuotedString,
};

assert_eq!(lex_fstring_error(r#"f"{""#), UnclosedLbrace);
assert_eq!(lex_fstring_error(r#"f"{foo!r""#), UnclosedLbrace);
assert_eq!(
lex_fstring_error(
r#"f"{"
"#
),
UnclosedLbrace
);
assert_eq!(lex_fstring_error(r#"f"""{""""#), UnclosedLbrace);
assert_eq!(lex_fstring_error(r#"f""#), UnterminatedString);
assert_eq!(lex_fstring_error(r#"f'"#), UnterminatedString);
assert_eq!(lex_fstring_error(r#"f""""#), UnterminatedTripleQuotedString);
Expand Down

0 comments on commit 2a75ece

Please sign in to comment.