@@ -115,6 +115,7 @@ impl FormatStrParser {
115115 // "{MyStruct { val_a: 0, val_b: 1 }}".
116116 let mut inexpr_open_count = 0 ;
117117
118+ // We need to escape '\' and '$'. See the comments on `get_receiver_text()` for detail.
118119 let mut chars = self . input . chars ( ) . peekable ( ) ;
119120 while let Some ( chr) = chars. next ( ) {
120121 match ( self . state , chr) {
@@ -127,6 +128,9 @@ impl FormatStrParser {
127128 self . state = State :: MaybeIncorrect ;
128129 }
129130 ( State :: NotExpr , _) => {
131+ if matches ! ( chr, '\\' | '$' ) {
132+ self . output . push ( '\\' ) ;
133+ }
130134 self . output . push ( chr) ;
131135 }
132136 ( State :: MaybeIncorrect , '}' ) => {
@@ -150,6 +154,9 @@ impl FormatStrParser {
150154 self . state = State :: NotExpr ;
151155 }
152156 ( State :: MaybeExpr , _) => {
157+ if matches ! ( chr, '\\' | '$' ) {
158+ current_expr. push ( '\\' ) ;
159+ }
153160 current_expr. push ( chr) ;
154161 self . state = State :: Expr ;
155162 }
@@ -187,13 +194,19 @@ impl FormatStrParser {
187194 inexpr_open_count += 1 ;
188195 }
189196 ( State :: Expr , _) => {
197+ if matches ! ( chr, '\\' | '$' ) {
198+ current_expr. push ( '\\' ) ;
199+ }
190200 current_expr. push ( chr) ;
191201 }
192202 ( State :: FormatOpts , '}' ) => {
193203 self . output . push ( chr) ;
194204 self . state = State :: NotExpr ;
195205 }
196206 ( State :: FormatOpts , _) => {
207+ if matches ! ( chr, '\\' | '$' ) {
208+ self . output . push ( '\\' ) ;
209+ }
197210 self . output . push ( chr) ;
198211 }
199212 }
@@ -241,8 +254,11 @@ mod tests {
241254 fn format_str_parser ( ) {
242255 let test_vector = & [
243256 ( "no expressions" , expect ! [ [ "no expressions" ] ] ) ,
257+ ( r"no expressions with \$0$1" , expect ! [ r"no expressions with \\\$0\$1" ] ) ,
244258 ( "{expr} is {2 + 2}" , expect ! [ [ "{} is {}; expr, 2 + 2" ] ] ) ,
245259 ( "{expr:?}" , expect ! [ [ "{:?}; expr" ] ] ) ,
260+ ( "{expr:1$}" , expect ! [ [ r"{:1\$}; expr" ] ] ) ,
261+ ( "{$0}" , expect ! [ [ r"{}; \$0" ] ] ) ,
246262 ( "{malformed" , expect ! [ [ "-" ] ] ) ,
247263 ( "malformed}" , expect ! [ [ "-" ] ] ) ,
248264 ( "{{correct" , expect ! [ [ "{{correct" ] ] ) ,
0 commit comments