gleam icon indicating copy to clipboard operation
gleam copied to clipboard

String interpolation

Open lpil opened this issue 3 years ago • 5 comments

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.

lpil avatar Jan 20 '22 17:01 lpil

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}"}"

J3RN avatar Jan 20 '22 21:01 J3RN

  • "Hello ${name" : parse error, unexpected EOF
  • "Hello $name}" : string
  • "Hello {name}" : string
  • "Hello ${}" : parse error, unexpected {
  • "Hello ${"Dr. ${name}"}" : discouraged but valid nested interpolation

lpil avatar Jan 20 '22 21:01 lpil

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")}"

J3RN avatar Jan 20 '22 21:01 J3RN

Yes that's right, any arbitrary expression is to be permitted within ${}, similiar to Elixir, JavaScript or Ruby.

lpil avatar Jan 20 '22 21:01 lpil

Holding off on this as we need to consider how it would fit with string pattern matching.

lpil avatar Sep 20 '22 14:09 lpil

Closing this because I would like to see how far we get with <> for now.

lpil avatar Nov 05 '22 09:11 lpil