kuroko-lang / kuroko

Dialect of Python with explicit variable declaration and block scoping, with a lightweight and easy-to-embed bytecode compiler and interpreter.
https://kuroko-lang.github.io/
MIT License
427 stars 25 forks source link

Add support for format specs in f-strings. #10

Closed klange closed 2 years ago

notwa commented 2 years ago

this might belong in a separate issue, but note that brace-escapes (or whatever Python calls them) are currently unavailable as well:

print(f"{{")  # SyntaxError: Unterminated string.
print(f"}}")  # prints two braces instead of one
klange commented 2 years ago

I think this ought to do it...

diff --git a/src/compiler.c b/src/compiler.c
index 3737fc4..95985e9 100644
--- a/src/compiler.c
+++ b/src/compiler.c
@@ -2493,7 +2493,21 @@ static void string(int exprType) {
                        }
                }
                c += 2;
+           } else if (isFormat && *c == '}') {
+               if (c[1] != '}') {
+                   error("single '}' not allowed in f-string");
+                   FREE_ARRAY(char,stringBytes,stringCapacity);
+                   return;
+               }
+               PUSH_CHAR('}');
+               c += 2;
+               continue;
            } else if (isFormat && *c == '{') {
+               if (c[1] == '{') {
+                   PUSH_CHAR('{');
+                   c += 2;
+                   continue;
+               }
                if (!atLeastOne || stringLength) { /* Make sure there's a string for coersion reasons */
                    emitConstant(OBJECT_VAL(krk_copyString(stringBytes,stringLength)));
                    if (atLeastOne) emitByte(OP_ADD);