[string-templates] Accidental use of StringTemplate instead of string

Tagir Valeev amaembo at gmail.com
Fri Oct 21 20:34:24 UTC 2022


Hello!

On Fri, Oct 21, 2022, 15:05 Victor Nazarov <asviraspossible at gmail.com>
wrote:

> Hello!
>
> I think one suggestion that fixes stated problems was already proposed
> before and I heard no arguments against going this route
> ...
>
> One suggestion that fixes this problem is to forbid bare template strings
> without policy-prefixes and instead introduce some policy that returns
> TemplateString itself.
>
> ````
>     StringTemplate tmpl = TMPL."\{x} plus \{y} equals \{x + y}" ;
>     String s1 = tmpl.apply(STR);
>     String s2 = STR."\{x} plus \{y} equals \{x + y}";
>     assertEquals(s1, s2);
> ````
>
> In this world the following can be observed:
>
> ````
>     System.out.println(STR."\{x} plus \{y} equals \{x + y}"); // Prints
> "10 plus 20 equals 30"
>     System.out.println(TMPL."\{x} plus \{y} equals \{x + y}"); // Prints
> "StringTemplate{segments = ["", " plus ", " equals "], values = [10, 20,
> 30]}"
>     System.out.println("\{x} plus \{y} equals \{x + y}"); // COMPILATION
> ERROR: error: unrecognized escape sequence '\{', policy is required for
> template strings
> ````
>

Sounds really good to me. In any case, template expression is not directly
substitutable. E.g. you cannot replace

STR."Hello \{user}"

with

StringTemplate t = "Hello \{user}"
STR.t

Instead, you need to desugar to a method call, like STR.process(t). I think
that in Java, all the expressions we had before were substitutable in this
sense: you could extract them to variable, and use that variable instead.
So it would be more consistent to avoid naming the right part of process
template expression as expression itself. I would suggest the following:

If parser meets a dot that follows single double quote, or triple double
quote, then the right part is always a string template, or a text blocks
template, and the whole thing including qualifier is process template
expression. Template may have no substitutions at all, in this case it
looks exactly like string or text block, but it's a template. Template is
not an expression and cannot appear in any context other than in process
template expression.

This simplifies grammar somewhat, as we say that template without
placeholders is still a template. Also, having an identity template
processor, like TMPL proposed by Victor, makes it possible and consistent
to instantiate the StringTemplate object that contains no placeholders. The
cost is five characters (TMPL.) necessary for presumably rare and advanced
uses of templates where one wants to store it without immediate processing.

What do you think?
Tagir Valeev
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-spec-observers/attachments/20221021/235fcb35/attachment-0001.htm>


More information about the amber-spec-observers mailing list