@@ -2,8 +2,8 @@ use std::iter;
2
2
use std:: mem;
3
3
use std:: str;
4
4
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 } ;
7
7
use crate :: parser:: parse_expression;
8
8
9
9
use self :: FStringErrorType :: * ;
@@ -117,7 +117,7 @@ impl<'a> FStringParser<'a> {
117
117
if nested {
118
118
spec = Some ( Box :: new ( FormattedValue {
119
119
value : Box :: new (
120
- parse_expression ( spec_expression. trim ( ) )
120
+ parse_fstring_expr ( & spec_expression)
121
121
. map_err ( |e| InvalidExpression ( Box :: new ( e. error ) ) ) ?,
122
122
) ,
123
123
conversion : None ,
@@ -158,7 +158,7 @@ impl<'a> FStringParser<'a> {
158
158
if pred_expression_text. is_empty ( ) {
159
159
return Ok ( FormattedValue {
160
160
value : Box :: new (
161
- parse_expression ( expression. trim ( ) )
161
+ parse_fstring_expr ( & expression)
162
162
. map_err ( |e| InvalidExpression ( Box :: new ( e. error ) ) ) ?,
163
163
) ,
164
164
conversion,
@@ -175,7 +175,7 @@ impl<'a> FStringParser<'a> {
175
175
} ,
176
176
FormattedValue {
177
177
value: Box :: new(
178
- parse_expression ( expression. trim ( ) )
178
+ parse_fstring_expr ( & expression)
179
179
. map_err( |e| InvalidExpression ( Box :: new( e. error) ) ) ?,
180
180
) ,
181
181
conversion,
@@ -253,6 +253,13 @@ impl<'a> FStringParser<'a> {
253
253
}
254
254
}
255
255
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
+
256
263
/// Parse an f-string into a string group.
257
264
fn parse_fstring ( source : & str ) -> Result < StringGroup , FStringErrorType > {
258
265
FStringParser :: new ( source) . parse ( )
@@ -297,7 +304,7 @@ mod tests {
297
304
spec: None ,
298
305
} ,
299
306
FormattedValue {
300
- value: Box :: new( mk_ident( "b" , 1 , 1 ) ) ,
307
+ value: Box :: new( mk_ident( "b" , 1 , 2 ) ) ,
301
308
conversion: None ,
302
309
spec: None ,
303
310
} ,
@@ -431,4 +438,11 @@ mod tests {
431
438
let parse_ast = parse_fstring ( & source) ;
432
439
assert ! ( parse_ast. is_ok( ) ) ;
433
440
}
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
+ }
434
448
}
0 commit comments