gleam
gleam copied to clipboard
String interpolation
Prior discussion: https://github.com/gleam-lang/gleam/discussions/1086
Syntax
let name = "Joe"
let messge = "Hello, ${name}!"
Here a variable is used with the ${} interpolation syntax, but any arbitrary Gleam expression is permitted.
Erlang output
Name = <<"Joe">>,
Message = <<"Hello, "/utf8, Name/binary, "!"/utf8>>.
JavaScript output
let name = "Joe"
let messge = `Hello, ${name}!`
Typing
The interpolated expression within the ${} must be of type String. In future we could permit other types, but not for this first version.
AST
I suggest that this AST node could be represented like so:
StringInterpolation {
location: SrcSpan,
segments: Vec<Expression>
}
When performing code generation we can check to see if each expression is a string literal or not and have a special case for that in order to get the right output syntax.
The implementor may determine that there is a better representation.
Few implementation notes, feel free to correct me @lpil
- Using double quotes
"instead of backticks (a la JavaScript)`, the lexer will be a bit more exciting :grin: - I assume these should all be valid and interpreted as verbatim text:
"Hello ${name""Hello $name}""Hello {name}"
- Guessing these are errors:
"Hello ${}""Hello ${"Dr. ${name}"}"
"Hello ${name": parse error, unexpected EOF"Hello $name}": string"Hello {name}": string"Hello ${}": parse error, unexpected{"Hello ${"Dr. ${name}"}": discouraged but valid nested interpolation
discouraged but valid nested interpolation
I'm assuming this is because the string interpolation is interpreted as a literal? Or do we want arbitrary expressions inside of interpolation? e.g.
"Hello, ${string.append("Wor", "ld")}"
Yes that's right, any arbitrary expression is to be permitted within ${}, similiar to Elixir, JavaScript or Ruby.
Holding off on this as we need to consider how it would fit with string pattern matching.
Closing this because I would like to see how far we get with <> for now.