Add Lyng string interpolation with docs/tests and refresh changelog
This commit is contained in:
1 parent
3b83439788
commit
3d8bfe8863
9 files changed
+497
-178
No files matched your search
@@ -17,6 +17,14 @@ Primary sources used: `lynglib/src/commonMain/kotlin/net/sergeych/lyng/{Parser,T
|
||||
- Supported escapes: `\n`, `\r`, `\t`, `\"`, `\\`, `\uXXXX` (4 hex digits).
|
||||
- Unicode escapes use exactly 4 hex digits (for example: `"\u0416"` -> `Ж`).
|
||||
- Unknown `\x` escapes in strings are preserved literally as two characters (`\` and `x`).
|
||||
- String interpolation is supported:
|
||||
- identifier form: `"$name"`
|
||||
- expression form: `"${expr}"`
|
||||
- escaped dollar: `"\$"` and `"$$"` both produce literal `$`.
|
||||
- `\\$x` means backslash + interpolated `x`.
|
||||
- Per-file opt-out is supported via leading comment directive:
|
||||
- `// feature: interpolation: off`
|
||||
- with this directive, `$...` stays literal text.
|
||||
- Numbers: `Int` (`123`, `1_000`), `Real` (`1.2`, `1e3`), hex (`0xFF`).
|
||||
- Char: `'a'`, escaped chars supported.
|
||||
- Supported escapes: `\n`, `\r`, `\t`, `\'`, `\\`, `\uXXXX` (4 hex digits).
|
||||
|
||||
@@ -1573,6 +1573,52 @@ same as:
|
||||
assert(s[1] == 'a')
|
||||
>>> void
|
||||
|
||||
### String interpolation
|
||||
|
||||
Supported forms:
|
||||
|
||||
- `$name`
|
||||
- `${expr}`
|
||||
|
||||
Literal dollar forms:
|
||||
|
||||
- `\$` -> `$`
|
||||
- `$$` -> `$`
|
||||
|
||||
Example:
|
||||
|
||||
val name = "Lyng"
|
||||
assertEquals("hello, Lyng!", "hello, $name!")
|
||||
assertEquals("sum=3", "sum=${1+2}")
|
||||
assertEquals("\$name", "\$name")
|
||||
assertEquals("\$name", "$$name")
|
||||
assertEquals("\\Lyng", "\\$name")
|
||||
>>> void
|
||||
|
||||
Interpolation and `printf`-style formatting can be combined when needed:
|
||||
|
||||
val method = "transfer"
|
||||
val argc = 2
|
||||
val compact = "%s:%d"(method, argc)
|
||||
assertEquals("call=transfer:2", "call=$compact")
|
||||
assertEquals("[transfer:2] ok", "[${"%s:%d"(method, argc)}] ok")
|
||||
>>> void
|
||||
|
||||
Interpolation also works well with regex patterns. To keep a literal `$` in the
|
||||
regex, escape it in the resulting pattern:
|
||||
|
||||
val currency = "USD"
|
||||
val amount = 15
|
||||
val escapedDollar = "\\$"
|
||||
val re = Regex("^${currency}${escapedDollar}${amount}$")
|
||||
assert("USD$15" =~ re)
|
||||
assert("USD15" !~ re)
|
||||
>>> void
|
||||
|
||||
If you need old literal behavior in a file, add a leading directive comment:
|
||||
|
||||
// feature: interpolation: off
|
||||
|
||||
### Char literal escapes
|
||||
|
||||
Are the same as in string literals with little difference:
|
||||
|
||||
Reference in new issue
Block a user