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

ast: use string builder for StringInterLiteral.str() (#10207)

This commit is contained in:
Lukas Neubert 2021-05-27 09:17:51 +02:00 committed by GitHub
parent 9ee1d8c848
commit d5cacd1e5f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 12 deletions

View File

@ -362,26 +362,26 @@ pub fn (x Expr) str() string {
return '__offsetof($x.struct_type, $x.field)' return '__offsetof($x.struct_type, $x.field)'
} }
StringInterLiteral { StringInterLiteral {
mut res := []string{} mut res := strings.new_builder(50)
res << "'" res.write_string("'")
for i, val in x.vals { for i, val in x.vals {
res << val res.write_string(val)
if i >= x.exprs.len { if i >= x.exprs.len {
break break
} }
res << '$' res.write_string('$')
fspec_str, needs_braces := x.get_fspec_braces(i) fspec_str, needs_braces := x.get_fspec_braces(i)
if needs_braces { if needs_braces {
res << '{' res.write_string('{')
res << x.exprs[i].str() res.write_string(x.exprs[i].str())
res << fspec_str res.write_string(fspec_str)
res << '}' res.write_string('}')
} else { } else {
res << x.exprs[i].str() res.write_string(x.exprs[i].str())
} }
} }
res << "'" res.write_string("'")
return res.join('') return res.str()
} }
StringLiteral { StringLiteral {
return "'$x.val'" return "'$x.val'"

View File

@ -2389,7 +2389,6 @@ pub fn (mut f Fmt) string_literal(node ast.StringLiteral) {
} }
pub fn (mut f Fmt) string_inter_literal(node ast.StringInterLiteral) { pub fn (mut f Fmt) string_inter_literal(node ast.StringInterLiteral) {
// TODO: this code is very similar to ast.Expr.str()
mut quote := "'" mut quote := "'"
for val in node.vals { for val in node.vals {
if val.contains('\\"') { if val.contains('\\"') {
@ -2407,6 +2406,9 @@ pub fn (mut f Fmt) string_inter_literal(node ast.StringInterLiteral) {
quote = '"' quote = '"'
} }
} }
// TODO: this code is very similar to ast.Expr.str()
// serkonda7: it can not fully be replaced tho as ´f.expr()´ and `ast.Expr.str()`
// work too different for the various exprs that are interpolated
f.write(quote) f.write(quote)
for i, val in node.vals { for i, val in node.vals {
f.write(val) f.write(val)