1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

cgen: escape quotes & nl in string literals

This commit is contained in:
Joe Conigliaro 2020-03-12 21:13:46 +11:00
parent bb5034f3fe
commit 99398ba652
2 changed files with 12 additions and 14 deletions

View File

@ -872,11 +872,7 @@ fn (p mut Parser) type_decl() {
}
p.cgen.consts << '#define SumType_${name}_$child_type_name $idx // DEF2'
ctype_names << child_type_name
sum_variants << if p.mod in ['builtin', 'main'] || child_type_name in builtin_types {
child_type_name
} else {
p.prepend_mod(child_type_name)
}
sum_variants << if p.mod in ['builtin', 'main'] || child_type_name in builtin_types { child_type_name } else { p.prepend_mod(child_type_name) }
}
if done {
break
@ -2598,10 +2594,9 @@ fn (p mut Parser) char_expr() {
fn format_str(_str string) string {
// TODO don't call replace 3 times for every string, do this in scanner.v
mut str := _str.replace('"', '\\"')
str = str.replace('\r\n', '\\n')
str = str.replace('\n', '\\n')
return str
return _str.replace_each(['"', '\\"',
'\n', '\\n',
'\r\n', '\\n'])
}
// m := map[string]int{}

View File

@ -809,11 +809,14 @@ fn (g mut Gen) expr(node ast.Expr) {
ast.StringLiteral {
// In C calls we have to generate C strings
// `C.printf("hi")` => `printf("hi");`
escaped_val := it.val.replace_each(['"', '\\"',
'\n', '\\n',
'\r\n', '\\n'])
if g.is_c_call {
g.write('"$it.val"')
g.write('"$escaped_val"')
}
else {
g.write('tos3("$it.val")')
g.write('tos3("$escaped_val")')
}
}
// `user := User{name: 'Bob'}`