Simple string interpolation.

This allows "%(...)" inside a string literal to interpolate the
stringified result of an expression.

It doesn't support custom interpolators or format strings, but we can
consider extending that later.
This commit is contained in:
Bob Nystrom
2015-11-11 07:55:48 -08:00
parent 71575d9179
commit 78655c68b0
41 changed files with 321 additions and 129 deletions
+15 -2
View File
@@ -133,6 +133,19 @@ static const char* coreModuleSource =
"class String is Sequence {\n"
" bytes { StringByteSequence.new(this) }\n"
" codePoints { StringCodePointSequence.new(this) }\n"
"\n"
" static interpolate_(parts) {\n"
" var result = \"\"\n"
" for (part in parts) {\n"
" if (part is String) {\n"
" result = result + part\n"
" } else {\n"
" result = result + part.call().toString\n"
" }\n"
" }\n"
"\n"
" return result\n"
" }\n"
"}\n"
"\n"
"class StringByteSequence is Sequence {\n"
@@ -167,7 +180,7 @@ static const char* coreModuleSource =
" return other\n"
" }\n"
"\n"
" toString { \"[\" + join(\", \") + \"]\" }\n"
" toString { \"[%(join(\", \"))]\" }\n"
"\n"
" +(other) {\n"
" var result = this[0..-1]\n"
@@ -189,7 +202,7 @@ static const char* coreModuleSource =
" for (key in keys) {\n"
" if (!first) result = result + \", \"\n"
" first = false\n"
" result = result + key.toString + \": \" + this[key].toString\n"
" result = result + \"%(key): %(this[key])\"\n"
" }\n"
"\n"
" return result + \"}\"\n"