RFR: 8341782: Allow lambda capture of basic for() loop variables as with enhanced for()
Maurizio Cimadamore
mcimadamore at openjdk.org
Thu Oct 10 11:38:14 UTC 2024
On Thu, 10 Oct 2024 11:21:41 GMT, Maurizio Cimadamore <mcimadamore at openjdk.org> wrote:
> Regardless, I think I found an issue with the current implementation when there are nested loops:
>
> ```
> void test() {
> for (int i = 0; ; ) {
> for (; ;) {
> i = 42;
> Runnable r = () -> System.out.println(i);
> }
> }
> }
> ```
Issues aside, I think a related example:
void test() {
for (int i ; ; ) {
for (; ;) {
i = 42;
Runnable r = () -> System.out.println(i);
}
}
}
Poses an interesting question: should `i` be capturable from the PoV of the inner loop? After all, in the inner loop we know there one value for `i` on each iteration.
Relatedly, what about this?
void test(int x) {
int i = 42;
if (x > 42) {
i = 43;
} else {
Runnable r = () -> System.out.println(i);
}
}
We know that `x` is not reassigned in the `else` branch. But the analysis we have now is not sophisticated enough to detect that.
I think there seem to be some more general principle here that is struggling to get out: sometimes there might be region of code where we know a variable can hold only one value (even if in other regions that variable might be reassigned multiple times). In such case you can imagine to take the content of the variable and assign it to a _new_ variable, local to that "well-behaved" region. That new variable could, of course, be captured. The loop case (handled by this patch) seems to be a special case of this situation.
-------------
PR Review Comment: https://git.openjdk.org/jdk/pull/21415#discussion_r1795257228
More information about the compiler-dev
mailing list