Skip to content

Commit a21a2d4

Browse files
authored
Handle != in f-string braces, raise EmptyExpression when expected.
1 parent 3b74e78 commit a21a2d4

File tree

1 file changed

+43
-9
lines changed

1 file changed

+43
-9
lines changed

parser/src/fstring.rs

Lines changed: 43 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,39 @@ impl<'a> FStringParser<'a> {
3030
while let Some(ch) = self.chars.next() {
3131
match ch {
3232
'!' if delims.is_empty() => {
33-
conversion = Some(match self.chars.next() {
34-
Some('s') => ConversionFlag::Str,
35-
Some('a') => ConversionFlag::Ascii,
36-
Some('r') => ConversionFlag::Repr,
37-
Some(_) => {
38-
return Err(InvalidConversionFlag);
33+
let x = self.chars.next();
34+
if let Some('=') = x {
35+
expression.push(ch);
36+
expression.push('=');
37+
} else {
38+
if expression.is_empty() {
39+
return Err(EmptyExpression);
3940
}
40-
None => {
41-
break;
41+
42+
conversion = Some(match x {
43+
Some('s') => ConversionFlag::Str,
44+
Some('a') => ConversionFlag::Ascii,
45+
Some('r') => ConversionFlag::Repr,
46+
Some(_) => {
47+
return Err(InvalidConversionFlag);
48+
}
49+
None => {
50+
break;
51+
}
52+
});
53+
54+
match self.chars.peek() {
55+
Some('}') => {
56+
continue;
57+
}
58+
Some(_) => {
59+
return Err(ExpectedRbrace);
60+
}
61+
None => {
62+
break;
63+
}
4264
}
43-
})
65+
}
4466
}
4567
':' if delims.is_empty() => {
4668
let mut nested = false;
@@ -294,11 +316,23 @@ mod tests {
294316
fn test_parse_invalid_fstring() {
295317
assert_eq!(parse_fstring("{"), Err(UnclosedLbrace));
296318
assert_eq!(parse_fstring("}"), Err(UnopenedRbrace));
319+
assert_eq!(parse_fstring("{5!a"), Err(UnclosedLbrace));
320+
assert_eq!(parse_fstring("{5!a1}"), Err(ExpectedRbrace));
321+
assert_eq!(parse_fstring("abc{!a 'cat'}"), Err(EmptyExpression));
322+
assert_eq!(parse_fstring("{!x}"), Err(EmptyExpression));
323+
297324
assert_eq!(parse_fstring("{a:{a:{b}}"), Err(ExpressionNestedTooDeeply));
298325
assert_eq!(parse_fstring("{a:b}}"), Err(UnopenedRbrace));
299326
assert_eq!(parse_fstring("{a:{b}"), Err(UnclosedLbrace));
300327

301328
// TODO: check for InvalidExpression enum?
302329
assert!(parse_fstring("{class}").is_err());
303330
}
331+
332+
#[test]
333+
fn test_parse_fstring_not_equals() {
334+
let source = String::from("{1 != 2}");
335+
let parse_ast = parse_fstring(&source);
336+
assert_ne!(parse_ast, Err(InvalidConversionFlag));
337+
}
304338
}

0 commit comments

Comments
 (0)