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 1:

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: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6614974

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

Solution 2:

This is called the let form and is used for "abbreviating".

On the other hand, in procedural languages this is called "declaring a variable" because the variable's "value" cell can mutate in procedure languages. (In functional languages, it's just an abbreviation and no different to just writing it out in the first place)

I can think of a lot of languages that use it in the source code the language user writes (Haskell, ML, Scheme, SBCL, Arc, ...), so not sure how you didn't see it yet...

Or did you mean just in Java?

let x = 2 in (x + 5)

Is shorthand for:

(\x (x + 5)) 2

which will eventually be reduced to

(2 + 5)

where \ is supposed to be lambda.

As for why it's in Java, not sure. What it's supposed to do is declare variables, so check whether it's used there.