String Templates Question - are expressions within a TemplateString literal evaluated immediately, or when a template is applied?

John Rose john.r.rose at oracle.com
Thu Sep 22 21:23:57 UTC 2022


On 22 Sep 2022, at 14:01, Alex Buckley wrote:

> If a future Java platform allows the embedded expressions themselves 
> to be represented at run time (e.g. via a dynamically-computed 
> constant that denotes the AST seen at compile time),

Yes, that’s the essence of what I mean by “expression quoting”.

(A complicating feature is that expressions can refer to local 
variables.  The quoting mechanism must define whether and how these 
variables are “captured” in the AST-like constant.  The comparison 
here with variable capture by lambdas is inescapable.)

> then a template processor could choose to (re)evaluate an embedded 
> expression in the current environment, no lambda "quoting" needed.

Yes.  There are many possible ways to signal that an expression has to 
be stored in some “transparently reprocessable” form, in the class 
file, and there are any number of ways to store such expressions in a 
classfile.  (The basic bytecode sequences used today don’t cut it, 
since they are not self-delimiting, and cannot be recontextualized or 
destructured like an AST could be.)

But:  Almost any expression quoting facility I can imagine for Java is 
largely isomorphic with a lambda-based “quoting” feature, 
disregarding details of surface syntax.  (The bytecode translation of a 
“crackable” lambda would include a bundle of AST associated with the 
lambda object.)

Surface syntax itself is fungible: quote-eliding sugar can make quotes 
(such as the `()->` “operator”) disappear altogether from the source 
code, if we choose.  Auto-quoting could be gated on logic similar to 
auto-boxing.  Or not.  (And whether or not lambdas are part of the 
story.)

One disconnect from lambdas (per se) is that expressions like `a[i++]` 
can produce multiple results via side effects on local variables, which 
lambdas cannot manage directly.  So quoting `a[i++]` is not just a 
matter of saying `()->a[i++]` with or without lambda cracking.  But 
perhaps `a[i++]` could be modeled using pattern-based APIs which output 
multiple named bindings.  And if pattern-deconstructor lambdas “were a 
thing” then once again `()->a[i++]` could be a candidate syntax, as 
well as its auto-quoted version `a[i++]` (contextually processed).

To be clear:  I’m not proposing anything here, just commenting on the 
larger design landscape as I see it.  I’ve probably said more than 
enough for today’s purposes, but I do know people are thinking and 
dreaming about such things, based on discussions of lambda cracking at 
JVM Language Summits of old.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/amber-dev/attachments/20220922/28eaaf43/attachment-0001.htm>


More information about the amber-dev mailing list