@@ -2,8 +2,8 @@ use std::iter;
22use std:: mem;
33use std:: str;
44
5- use crate :: ast:: { ConversionFlag , Location , StringGroup } ;
6- use crate :: error:: { FStringError , FStringErrorType } ;
5+ use crate :: ast:: { ConversionFlag , Expression , Location , StringGroup } ;
6+ use crate :: error:: { FStringError , FStringErrorType , ParseError } ;
77use crate :: parser:: parse_expression;
88
99use self :: FStringErrorType :: * ;
@@ -117,7 +117,7 @@ impl<'a> FStringParser<'a> {
117117 if nested {
118118 spec = Some ( Box :: new ( FormattedValue {
119119 value : Box :: new (
120- parse_expression ( spec_expression. trim ( ) )
120+ parse_fstring_expr ( & spec_expression)
121121 . map_err ( |e| InvalidExpression ( Box :: new ( e. error ) ) ) ?,
122122 ) ,
123123 conversion : None ,
@@ -158,7 +158,7 @@ impl<'a> FStringParser<'a> {
158158 if pred_expression_text. is_empty ( ) {
159159 return Ok ( FormattedValue {
160160 value : Box :: new (
161- parse_expression ( expression. trim ( ) )
161+ parse_fstring_expr ( & expression)
162162 . map_err ( |e| InvalidExpression ( Box :: new ( e. error ) ) ) ?,
163163 ) ,
164164 conversion,
@@ -175,7 +175,7 @@ impl<'a> FStringParser<'a> {
175175 } ,
176176 FormattedValue {
177177 value: Box :: new(
178- parse_expression ( expression. trim ( ) )
178+ parse_fstring_expr ( & expression)
179179 . map_err( |e| InvalidExpression ( Box :: new( e. error) ) ) ?,
180180 ) ,
181181 conversion,
@@ -253,6 +253,13 @@ impl<'a> FStringParser<'a> {
253253 }
254254}
255255
256+ fn parse_fstring_expr ( source : & str ) -> Result < Expression , ParseError > {
257+ let fstring_body = format ! ( "({})" , source) ;
258+ let mut expression = parse_expression ( & fstring_body) ?;
259+ expression. location . go_left ( ) ;
260+ Ok ( expression)
261+ }
262+
256263/// Parse an f-string into a string group.
257264fn parse_fstring ( source : & str ) -> Result < StringGroup , FStringErrorType > {
258265 FStringParser :: new ( source) . parse ( )
@@ -297,7 +304,7 @@ mod tests {
297304 spec: None ,
298305 } ,
299306 FormattedValue {
300- value: Box :: new( mk_ident( "b" , 1 , 1 ) ) ,
307+ value: Box :: new( mk_ident( "b" , 1 , 2 ) ) ,
301308 conversion: None ,
302309 spec: None ,
303310 } ,
@@ -431,4 +438,11 @@ mod tests {
431438 let parse_ast = parse_fstring ( & source) ;
432439 assert ! ( parse_ast. is_ok( ) ) ;
433440 }
441+
442+ #[ test]
443+ fn test_parse_fstring_yield_expr ( ) {
444+ let source = String :: from ( "{yield}" ) ;
445+ let parse_ast = parse_fstring ( & source) ;
446+ assert ! ( parse_ast. is_ok( ) ) ;
447+ }
434448}
0 commit comments