Skip to content

Commit 478aa41

Browse files
authored
Merge pull request RustPython#4410 from harupy/remove-repetitive-to_string
Remove repetitive `to_string` in `parse_escaped_char`
2 parents 6cbe503 + 8f5bd0b commit 478aa41

File tree

1 file changed

+35
-31
lines changed

1 file changed

+35
-31
lines changed

compiler/parser/src/string_parser.rs

Lines changed: 35 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -130,39 +130,43 @@ impl<'a> StringParser<'a> {
130130

131131
fn parse_escaped_char(&mut self) -> Result<String, LexicalError> {
132132
match self.next_char() {
133-
Some(c) => Ok(match c {
134-
'\\' => '\\'.to_string(),
135-
'\'' => '\''.to_string(),
136-
'\"' => '"'.to_string(),
137-
'\n' => "".to_string(),
138-
'a' => '\x07'.to_string(),
139-
'b' => '\x08'.to_string(),
140-
'f' => '\x0c'.to_string(),
141-
'n' => '\n'.to_string(),
142-
'r' => '\r'.to_string(),
143-
't' => '\t'.to_string(),
144-
'v' => '\x0b'.to_string(),
145-
o @ '0'..='7' => self.parse_octet(o).to_string(),
146-
'x' => self.parse_unicode_literal(2)?.to_string(),
147-
'u' if !self.kind.is_bytes() => self.parse_unicode_literal(4)?.to_string(),
148-
'U' if !self.kind.is_bytes() => self.parse_unicode_literal(8)?.to_string(),
149-
'N' if !self.kind.is_bytes() => self.parse_unicode_name()?.to_string(),
150-
c => {
151-
if self.kind.is_bytes() && !c.is_ascii() {
152-
return Err(LexicalError::new(
153-
LexicalErrorType::OtherError(
154-
"bytes can only contain ASCII literal characters".to_owned(),
155-
),
156-
self.get_pos(),
157-
));
133+
Some(c) => {
134+
let char = match c {
135+
'\\' => '\\',
136+
'\'' => '\'',
137+
'\"' => '"',
138+
'a' => '\x07',
139+
'b' => '\x08',
140+
'f' => '\x0c',
141+
'n' => '\n',
142+
'r' => '\r',
143+
't' => '\t',
144+
'v' => '\x0b',
145+
o @ '0'..='7' => self.parse_octet(o),
146+
'x' => self.parse_unicode_literal(2)?,
147+
'u' if !self.kind.is_bytes() => self.parse_unicode_literal(4)?,
148+
'U' if !self.kind.is_bytes() => self.parse_unicode_literal(8)?,
149+
'N' if !self.kind.is_bytes() => self.parse_unicode_name()?,
150+
// Special cases where the escape sequence is not a single character
151+
'\n' => return Ok("".to_string()),
152+
c => {
153+
if self.kind.is_bytes() && !c.is_ascii() {
154+
return Err(LexicalError {
155+
error: LexicalErrorType::OtherError(
156+
"bytes can only contain ASCII literal characters".to_owned(),
157+
),
158+
location: self.get_pos(),
159+
});
160+
}
161+
return Ok(format!("\\{c}"));
158162
}
159-
format!("\\{c}")
160-
}
163+
};
164+
Ok(char.to_string())
165+
}
166+
None => Err(LexicalError {
167+
error: LexicalErrorType::StringError,
168+
location: self.get_pos(),
161169
}),
162-
None => Err(LexicalError::new(
163-
LexicalErrorType::StringError,
164-
self.get_pos(),
165-
)),
166170
}
167171
}
168172

0 commit comments

Comments
 (0)