Skip to content

Commit

Permalink
Merge pull request #423 from sunng87/fix/remove-string-escape
Browse files Browse the repository at this point in the history
Fix json string escape
  • Loading branch information
sunng87 committed Mar 26, 2021
2 parents 4e12c39 + dda5576 commit 3394484
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 5 deletions.
8 changes: 7 additions & 1 deletion src/grammar.pest
Expand Up @@ -15,7 +15,13 @@ literal = { string_literal |
null_literal = @{ "null" ~ !symbol_char }
boolean_literal = @{ ("true"|"false") ~ !symbol_char }
number_literal = @{ "-"? ~ ASCII_DIGIT+ ~ "."? ~ ASCII_DIGIT* ~ ("E" ~ "-"? ~ ASCII_DIGIT+)? }
string_literal = @{ ("\"" ~ (!"\"" ~ ("\\\"" | ANY))* ~ "\"") | ("'" ~ (!"'" ~ ("\\'" | ANY))* ~ "'") }
json_char = {
!("\"" | "\\") ~ ANY
| "\\" ~ ("\"" | "\\" | "/" | "b" | "f" | "n" | "r" | "t")
| "\\" ~ ("u" ~ ASCII_HEX_DIGIT{4})
}
string_inner = @{ json_char* }
string_literal = ${ "\"" ~ string_inner ~ "\"" }
array_literal = { "[" ~ literal? ~ ("," ~ literal)* ~ "]" }
object_literal = { "{" ~ (string_literal ~ ":" ~ literal)?
~ ("," ~ string_literal ~ ":" ~ literal)* ~ "}" }
Expand Down
3 changes: 1 addition & 2 deletions src/grammar.rs
Expand Up @@ -125,8 +125,6 @@ mod test {
let s = vec![
"\"json string\"",
"\"quot: \\\"\"",
"'json string'",
"'quot: \\''",
"[]",
"[\"hello\"]",
"[1,2,3,4,true]",
Expand Down Expand Up @@ -174,6 +172,7 @@ mod test {
"{{exp 1}}",
"{{exp \"literal\"}}",
"{{exp \"literal with space\"}}",
r#"{{exp "literal with escape \\\\"}}"#,
"{{exp ref}}",
"{{exp (sub)}}",
"{{exp (sub 123)}}",
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Expand Up @@ -358,7 +358,7 @@
//!
//!

#![allow(dead_code)]
#![allow(dead_code, clippy::upper_case_acronyms)]
#![warn(rust_2018_idioms)]
#![recursion_limit = "200"]

Expand Down
24 changes: 23 additions & 1 deletion tests/escape.rs
Expand Up @@ -3,7 +3,7 @@ extern crate handlebars;
#[macro_use]
extern crate serde_json;

use handlebars::Handlebars;
use handlebars::{handlebars_helper, Handlebars};

#[test]
fn test_escape_216() {
Expand All @@ -19,3 +19,25 @@ fn test_escape_216() {
r"\\\\ foo bar foobar foo#bar foo//bar foo\foo foo\\\foo\\foo \\foo {{FOO}} {{FOO}}"
);
}

#[test]
fn test_string_no_escape_422() {
let mut hbs = Handlebars::new();

handlebars_helper!(replace: |input: str, from: str, to: str| {
input.replace(from, to)
});
hbs.register_helper("replace", Box::new(replace));

assert_eq!(
r#"some\ path"#,
hbs.render_template(r#"{{replace "some/path" "/" "\\ " }}"#, &())
.unwrap()
);

assert_eq!(
r#"some\path"#,
hbs.render_template(r#"{{replace "some/path" "/" "\\" }}"#, &())
.unwrap()
);
}

0 comments on commit 3394484

Please sign in to comment.