POC implementation of string interpolation

Attila Kelemen attila.kelemen85 at gmail.com
Sat Oct 10 16:22:22 UTC 2020


I have implemented a version of string interpolation in my local
fork [1] for fun. I know it is a lot to ask, but I'm hoping to find
some generous souls who could review my changes [2], if this is
sensible way to alter javac.

The format is "\{expression}", where the `expression` can be any
legal Java expression (line endings are currently forbidden). It
works with both normal strings and text blocks (which is of course,
the main pain without string interpolation). Hopefully I did not
miss many features that are a must with such a change. For example,
I have adjusted string folding and the compile time constant parsing
to work with interpolated strings as well.

As for the implementation, I had to allow the tokenizer to create
a parser. This is somewhat awkward, because now the tokenizer is no
longer regular, but I saw no way around it. There are some
controversial parts of the implementation of course:

- I have created `JCInterpolatedString`, which is a list of
  expressions to be concatenated to a string. The only caveat with
  this is that it is possible to nest string literals like "\{"ABC"}".
  If this is parsed naively, then it will contain a single JCLiteral
  (string). However, this would mean that `Pretty` will print it back
  as "ABC", which is surprising. So, I got around this by wrapping
  such string literals into a `JCInterpolatedString`. There are many
  alternatives I have considered, but this seemed to be the least
  error prone to use.
- The string folding within `JavacParser` is currently folding only
  string constants. However, this could be adjusted to fold every
  literal, because unlike `PLUS`, interpolated strings are always
  strings anyway.
- There are no tests at the moment, but that is because it is now
  just a proof of concept, so I didn't want to make extreme efforts
  on that.

Attila Kelemen

[1] https://github.com/kelemen/jdk/tree/string_interpolation
[2] https://github.com/kelemen/jdk/commit/029b4ccde7d43b9ad57b74f3ebfa536084b80910

ps.: LambdaTranslationTest1 and LambdaTranslationTest2 does not work
     on my local, because of the decimal separator being "," instead
     of ".".

More information about the compiler-dev mailing list