From 224edd73ee024e34efff9c484508763a4dc53b15 Mon Sep 17 00:00:00 2001 From: Yuya Nishihara Date: Fri, 3 Mar 2023 15:41:12 +0900 Subject: [PATCH] templater: parse "\t" and "\r" as escape sequence --- src/template.pest | 2 +- src/template_parser.rs | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/template.pest b/src/template.pest index 76a60192a..2cc038a09 100644 --- a/src/template.pest +++ b/src/template.pest @@ -19,7 +19,7 @@ whitespace = _{ " " | "\t" | "\n" } -escape = @{ "\\" ~ ("n" | "\"" | "\\") } +escape = @{ "\\" ~ ("t" | "r" | "n" | "\"" | "\\") } literal_char = @{ !("\"" | "\\") ~ ANY } raw_literal = @{ literal_char+ } literal = { "\"" ~ (raw_literal | escape)* ~ "\"" } diff --git a/src/template_parser.rs b/src/template_parser.rs index 5dd192657..9c347d2e8 100644 --- a/src/template_parser.rs +++ b/src/template_parser.rs @@ -258,6 +258,8 @@ fn parse_string_literal(pair: Pair) -> 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() { + // "\" escapes + assert_eq!( + parse_into_kind(r#" "\t\r\n\"\\" "#), + Ok(ExpressionKind::String("\t\r\n\"\\".to_owned())), + ); + + // Invalid "\" 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)));