templater: parse "\t" and "\r" as escape sequence

This commit is contained in:
Yuya Nishihara 2023-03-03 15:41:12 +09:00
parent d9ed2895db
commit 224edd73ee
2 changed files with 18 additions and 1 deletions

View file

@ -19,7 +19,7 @@
whitespace = _{ " " | "\t" | "\n" }
escape = @{ "\\" ~ ("n" | "\"" | "\\") }
escape = @{ "\\" ~ ("t" | "r" | "n" | "\"" | "\\") }
literal_char = @{ !("\"" | "\\") ~ ANY }
raw_literal = @{ literal_char+ }
literal = { "\"" ~ (raw_literal | escape)* ~ "\"" }

View file

@ -258,6 +258,8 @@ fn parse_string_literal(pair: Pair<Rule>) -> String {
Rule::escape => match part.as_str().as_bytes()[1] as char {
'"' => result.push('"'),
'\\' => result.push('\\'),
't' => result.push('\t'),
'r' => result.push('\r'),
'n' => result.push('\n'),
char => panic!("invalid escape: \\{char:?}"),
},
@ -1261,6 +1263,21 @@ mod tests {
assert!(parse_template(r#" label("",,"") "#).is_err());
}
#[test]
fn test_string_literal() {
// "\<char>" escapes
assert_eq!(
parse_into_kind(r#" "\t\r\n\"\\" "#),
Ok(ExpressionKind::String("\t\r\n\"\\".to_owned())),
);
// Invalid "\<char>" escape
assert_eq!(
parse_into_kind(r#" "\y" "#),
Err(TemplateParseErrorKind::SyntaxError),
);
}
#[test]
fn test_integer_literal() {
assert_eq!(parse_into_kind("0"), Ok(ExpressionKind::Integer(0)));