@@ -115,6 +115,7 @@ impl FormatStrParser {
115
115
// "{MyStruct { val_a: 0, val_b: 1 }}".
116
116
let mut inexpr_open_count = 0 ;
117
117
118
+ // We need to escape '\' and '$'. See the comments on `get_receiver_text()` for detail.
118
119
let mut chars = self . input . chars ( ) . peekable ( ) ;
119
120
while let Some ( chr) = chars. next ( ) {
120
121
match ( self . state , chr) {
@@ -127,6 +128,9 @@ impl FormatStrParser {
127
128
self . state = State :: MaybeIncorrect ;
128
129
}
129
130
( State :: NotExpr , _) => {
131
+ if matches ! ( chr, '\\' | '$' ) {
132
+ self . output . push ( '\\' ) ;
133
+ }
130
134
self . output . push ( chr) ;
131
135
}
132
136
( State :: MaybeIncorrect , '}' ) => {
@@ -150,6 +154,9 @@ impl FormatStrParser {
150
154
self . state = State :: NotExpr ;
151
155
}
152
156
( State :: MaybeExpr , _) => {
157
+ if matches ! ( chr, '\\' | '$' ) {
158
+ current_expr. push ( '\\' ) ;
159
+ }
153
160
current_expr. push ( chr) ;
154
161
self . state = State :: Expr ;
155
162
}
@@ -187,13 +194,19 @@ impl FormatStrParser {
187
194
inexpr_open_count += 1 ;
188
195
}
189
196
( State :: Expr , _) => {
197
+ if matches ! ( chr, '\\' | '$' ) {
198
+ current_expr. push ( '\\' ) ;
199
+ }
190
200
current_expr. push ( chr) ;
191
201
}
192
202
( State :: FormatOpts , '}' ) => {
193
203
self . output . push ( chr) ;
194
204
self . state = State :: NotExpr ;
195
205
}
196
206
( State :: FormatOpts , _) => {
207
+ if matches ! ( chr, '\\' | '$' ) {
208
+ self . output . push ( '\\' ) ;
209
+ }
197
210
self . output . push ( chr) ;
198
211
}
199
212
}
@@ -241,8 +254,11 @@ mod tests {
241
254
fn format_str_parser ( ) {
242
255
let test_vector = & [
243
256
( "no expressions" , expect ! [ [ "no expressions" ] ] ) ,
257
+ ( r"no expressions with \$0$1" , expect ! [ r"no expressions with \\\$0\$1" ] ) ,
244
258
( "{expr} is {2 + 2}" , expect ! [ [ "{} is {}; expr, 2 + 2" ] ] ) ,
245
259
( "{expr:?}" , expect ! [ [ "{:?}; expr" ] ] ) ,
260
+ ( "{expr:1$}" , expect ! [ [ r"{:1\$}; expr" ] ] ) ,
261
+ ( "{$0}" , expect ! [ [ r"{}; \$0" ] ] ) ,
246
262
( "{malformed" , expect ! [ [ "-" ] ] ) ,
247
263
( "malformed}" , expect ! [ [ "-" ] ] ) ,
248
264
( "{{correct" , expect ! [ [ "{{correct" ] ] ) ,
0 commit comments