From 598be6e5ea97839b3e32af682087755960d71e49 Mon Sep 17 00:00:00 2001 From: Jeong YunWon Date: Fri, 19 Aug 2022 05:48:38 +0900 Subject: [PATCH] Fix nested-fstring unbalanced brace pairs handling --- parser/src/fstring.rs | 21 +++++++++---------- ...ing__tests__parse_fstring_nested_spec.snap | 2 +- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/parser/src/fstring.rs b/parser/src/fstring.rs index d4e8b086c..3db0cce01 100644 --- a/parser/src/fstring.rs +++ b/parser/src/fstring.rs @@ -91,20 +91,19 @@ impl<'a> FStringParser<'a> { } ':' if delims.is_empty() => { - let mut in_nested = false; + let mut nested = 0; let mut spec_constructor = Vec::new(); let mut constant_piece = String::new(); let mut formatted_value_piece = String::new(); - let mut spec_delims = Vec::new(); while let Some(&next) = self.chars.peek() { match next { - '{' if in_nested => { - spec_delims.push(next); + '{' if nested > 0 => { + nested += 1; formatted_value_piece.push(next); } - '}' if in_nested => { - if spec_delims.is_empty() { - in_nested = false; + '}' if nested > 0 => { + nested -= 1; + if nested == 0 { formatted_value_piece.push(next); spec_constructor.push( self.expr(ExprKind::FormattedValue { @@ -122,21 +121,21 @@ impl<'a> FStringParser<'a> { ); formatted_value_piece.clear(); } else { - spec_delims.pop(); formatted_value_piece.push(next); } } - _ if in_nested => { + _ if nested > 0 => { formatted_value_piece.push(next); } '{' => { - in_nested = true; + nested += 1; spec_constructor.push(self.expr(ExprKind::Constant { value: constant_piece.to_owned().into(), kind: None, })); constant_piece.clear(); formatted_value_piece.push(next); + formatted_value_piece.push(' '); } '}' => break, _ => { @@ -150,7 +149,7 @@ impl<'a> FStringParser<'a> { kind: None, })); constant_piece.clear(); - if in_nested { + if nested > 0 { return Err(UnclosedLbrace); } spec = Some(Box::new(self.expr(ExprKind::JoinedStr { diff --git a/parser/src/snapshots/rustpython_parser__fstring__tests__parse_fstring_nested_spec.snap b/parser/src/snapshots/rustpython_parser__fstring__tests__parse_fstring_nested_spec.snap index 8ba0b5661..3bf74c02c 100644 --- a/parser/src/snapshots/rustpython_parser__fstring__tests__parse_fstring_nested_spec.snap +++ b/parser/src/snapshots/rustpython_parser__fstring__tests__parse_fstring_nested_spec.snap @@ -76,7 +76,7 @@ Located { value: Located { location: Location { row: 1, - column: 2, + column: 3, }, custom: (), node: Name {