From 5818956cdc5cb85952cf21166703a5444175a033 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20D=C3=A4schle?= Date: Sun, 12 Apr 2020 15:24:23 +0200 Subject: [PATCH] cgen: % escape in string interpolated literals * cgen: % escape in c call to _STR * tests: add test for string % escape * Add a test for the % escaping when interpolating inside strings --- vlib/v/gen/cgen.v | 2 +- vlib/v/tests/inout/string_interp.out | 1 + vlib/v/tests/inout/string_interp.vv | 6 ++++++ vlib/v/tests/string_interpolation_test.v | 7 +++++++ 4 files changed, 15 insertions(+), 1 deletion(-) create mode 100644 vlib/v/tests/inout/string_interp.out create mode 100644 vlib/v/tests/inout/string_interp.vv diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 0696f612bb..6238774774 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -2363,7 +2363,7 @@ fn (g mut Gen) string_inter_literal(node ast.StringInterLiteral) { g.write('_STR("') // Build the string with % for i, val in node.vals { - escaped_val := val.replace_each(['"', '\\"', '\r\n', '\\n', '\n', '\\n']) + escaped_val := val.replace_each(['"', '\\"', '\r\n', '\\n', '\n', '\\n', '%', '%%']) g.write(escaped_val) if i >= node.exprs.len { continue diff --git a/vlib/v/tests/inout/string_interp.out b/vlib/v/tests/inout/string_interp.out new file mode 100644 index 0000000000..ea52e4b808 --- /dev/null +++ b/vlib/v/tests/inout/string_interp.out @@ -0,0 +1 @@ +%.*sworldhello \ No newline at end of file diff --git a/vlib/v/tests/inout/string_interp.vv b/vlib/v/tests/inout/string_interp.vv new file mode 100644 index 0000000000..875f0d85be --- /dev/null +++ b/vlib/v/tests/inout/string_interp.vv @@ -0,0 +1,6 @@ + +fn main() { + test := 'hello' + hello := 'world' + println('%.*s$hello$test') +} diff --git a/vlib/v/tests/string_interpolation_test.v b/vlib/v/tests/string_interpolation_test.v index 809bcc42ed..9d45beb88c 100644 --- a/vlib/v/tests/string_interpolation_test.v +++ b/vlib/v/tests/string_interpolation_test.v @@ -55,3 +55,10 @@ fn test_implicit_str() { text := '$i' + '42' assert text == '4242' } + +fn test_string_interpolation_percent_escaping(){ + test := 'hello' + hello := 'world' + x := '%.*s$hello$test |${hello:-30s}|' + assert x == '%.*sworldhello |world |' +}