From ece7da299aa1bdd8b5e424f574aa6deacb974fcd Mon Sep 17 00:00:00 2001 From: "K. Lange" Date: Mon, 23 May 2022 08:42:40 +0900 Subject: [PATCH] Support = to print f-string expression alongside value --- src/compiler.c | 11 +++++++++++ test/testFormatString.krk | 3 +++ test/testFormatString.krk.expect | 3 +++ 3 files changed, 17 insertions(+) create mode 100644 test/testFormatString.krk create mode 100644 test/testFormatString.krk.expect diff --git a/src/compiler.c b/src/compiler.c index 5461b77..7e77e08 100644 --- a/src/compiler.c +++ b/src/compiler.c @@ -2521,6 +2521,7 @@ static void string(int exprType) { if (atLeastOne) emitByte(OP_ADD); atLeastOne = 1; } + const char * start = c+1; stringLength = 0; KrkScanner beforeExpression = krk_tellScanner(); Parser parserBefore = parser; @@ -2537,6 +2538,15 @@ static void string(int exprType) { parser = parserBefore; c = inner.start; KrkToken which = syntheticToken("str"); + int hasEq = 0; + while (*c == ' ') c++; + if (*c == '=') { + c++; + while (*c == ' ') c++; + emitConstant(OBJECT_VAL(krk_copyString(start,c-start))); + emitByte(OP_SWAP); + hasEq = 1; + } if (*c == '!') { c++; /* Conversion specifiers, must only be one */ @@ -2563,6 +2573,7 @@ static void string(int exprType) { error("Expected closing '}' after expression in f-string"); goto _cleanupError; } + if (hasEq) emitByte(OP_ADD); if (atLeastOne) emitByte(OP_ADD); atLeastOne = 1; c++; diff --git a/test/testFormatString.krk b/test/testFormatString.krk new file mode 100644 index 0000000..564000b --- /dev/null +++ b/test/testFormatString.krk @@ -0,0 +1,3 @@ +print(f'{min([1,2,3]) = }') +print(f'{"test" = !r}') +print(f'abc {123 = } def {456 = } ghi') diff --git a/test/testFormatString.krk.expect b/test/testFormatString.krk.expect new file mode 100644 index 0000000..f3c69c6 --- /dev/null +++ b/test/testFormatString.krk.expect @@ -0,0 +1,3 @@ +min([1,2,3]) = 1 +"test" = 'test' +abc 123 = 123 def 456 = 456 ghi