Search code examples
javacompiler-constructionlanguage-designlet

Purpose of "let expression" (LetExpr) in the Java compiler?


The Java compiler seems to have support for let expressions in com.sun.tools.javac.tree.* (look for LetExpr).

One comment in JCTree even mentions some syntax

(let int x = 3; in x+2)

which of course is not accepted by the grammar of the language and rejected in an earlier compiler phase.

I'm wondering about the origin of this construct, which I have never seen before.

Is it used internally by javac or is it synthesized by other tools? Is it maybe just an artifact from the very early days of Java from a language feature which never saw the light?

Is there anything useful which can be done with it today?

Generally speaking, why does it exist?


Solution

  • Generally speaking, why does it exist?

    It exists for autoboxing as Google suggests.

    If you have code like this:

    Integer foo = 0;
    foo++;
    

    Java internally makes this into this helper expression:

    Integer foo = 0;
    let int foo_helper = foo.intValue() in foo_helper++;
    

    Source: https://bugs.java.com/bugdatabase/view_bug?bug_id=6614974

    That expression obviously has no syntax representation, it's just an AST level transformation to simplify compilation.