Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better string interpolation #1161

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Optimize string interpolation in the compiler.
  • Loading branch information
mhermier committed Mar 23, 2023
commit f7999018fa5ce359a1fdca432a397c1efba84161
28 changes: 16 additions & 12 deletions src/vm/wren_compiler.c
Original file line number Diff line number Diff line change
Expand Up @@ -2435,31 +2435,35 @@ static void literal(Compiler* compiler, bool canAssign)
// ["a ", b + c, " d"].join()
static void stringInterpolation(Compiler* compiler, bool canAssign)
{
// Instantiate a new list.
loadCoreVariable(compiler, "List");
callMethod(compiler, 0, "new()", 5);

bool first = true;
do
{
// The opening string part.
literal(compiler, false);
callMethod(compiler, 1, "addCore_(_)", 11);
if (AS_STRING(compiler->parser->previous.value)->length != 0)
{
literal(compiler, false);
if (!first) callMethod(compiler, 1, "+(_)", 4);
first = false;
}

// The interpolated expression.
ignoreNewlines(compiler);
expression(compiler);
callMethod(compiler, 1, "addCore_(_)", 11);
callMethod(compiler, 0, "toString", 8);
if (!first) callMethod(compiler, 1, "+(_)", 4);
first = false;

ignoreNewlines(compiler);
} while (match(compiler, TOKEN_INTERPOLATION));

// The trailing string part.
consume(compiler, TOKEN_STRING, "Expect end of string interpolation.");
literal(compiler, false);
callMethod(compiler, 1, "addCore_(_)", 11);

// The list of interpolated parts.
callMethod(compiler, 0, "join()", 6);
if (AS_STRING(compiler->parser->previous.value)->length != 0)
{
literal(compiler, false);
ASSERT(!first, "Lexer error: invalid string interpolation token chain");
callMethod(compiler, 1, "+(_)", 4);
}
}

static void super_(Compiler* compiler, bool canAssign)
Expand Down