RFR: 8334488: Improve error for illegal early access from nested class
Archie Cobbs
acobbs at openjdk.org
Tue Jun 18 16:17:40 UTC 2024
Consider this class:
class CtorPrologueBugTest {
int x;
CtorPrologueBugTest() {
this(new Object() {
{ System.out.println(x); }
});
}
CtorPrologueBugTest(Object obj) {
}
}
Prior to [JDK-8194743](https://bugs.openjdk.org/browse/JDK-8194743), it resulted in this error, generated by `Attr.java`:
CtorPrologueBugTest.java:5: error: cannot reference x before supertype constructor has been called
{ System.out.println(x); }
^
After [JDK-8194743](https://bugs.openjdk.org/browse/JDK-8194743), it resulted in this different error, generated later in the compilation process by `Lower.java`:
CtorPrologueBugTest.java:5: error: no enclosing instance of type CtorPrologueBugTest is in scope
{ System.out.println(x); }
^
There are two problems with this change in behavior:
1. Such errors should be detected by `Attr.java`, not `Lower.java`, so that IDE's that only display errors generated by earlier compilation phases will show them.
1. The wording change in the error message is technically incorrect: `x` is in scope, it's just not yet accessible.
This change in behavior reflects an underlying logic bug, which is that `Attr::visitClassDef` is setting `ctorPrologue = false` on the containing class' environment, instead of the nested class' environment. As a result, when `Attr` descends into the nested class and then finds the `x` symbol in the containing class, it has "forgotten" that it is in an early construction context for `CtorPrologueBugTest` and fails to report the error at that point as it should.
This patch fixes this glitch to the error is detected earlier in the compilation process by `Attr` and is reported with the more correct verbiage.
Thanks to @mcimadamore for pointing out the mistake.
-------------
Commit messages:
- Fix bug where "ctorPrologue" flag was being reset inappropriately.
Changes: https://git.openjdk.org/jdk/pull/19773/files
Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=19773&range=00
Issue: https://bugs.openjdk.org/browse/JDK-8334488
Stats: 26 lines in 7 files changed: 21 ins; 1 del; 4 mod
Patch: https://git.openjdk.org/jdk/pull/19773.diff
Fetch: git fetch https://git.openjdk.org/jdk.git pull/19773/head:pull/19773
PR: https://git.openjdk.org/jdk/pull/19773
More information about the compiler-dev
mailing list