RFR: 8193904: Uninitialized final field access and qualified this [v2]

Archie L. Cobbs duke at openjdk.org
Thu Nov 17 19:10:54 UTC 2022


> If a class `MyClass` has a blank final field `foo` that has not yet been assigned, the compiler prevents you from accessing it via the expressions `foo` or `this.foo`. However, it does not prevent you from accessing it via the expression `MyClass.this.foo`.
> 
> Here's a simple example:
> 
> class QualifiedThis {
>     final int foo;
>     QualifiedThis() {
>         System.err.println(QualifiedThis.this.foo);   // should get an error here
>         this.foo = 42;
>     }
> }
> 
> 
> This patch fixes that omission.
> 
> I couldn't find an existing method that answers the question "Is this AST tree a reference to the current instance of the class I'm now compiling?" so I wrote a new one `TreeInfo.isThisReference()`.
> 
> The question itself is a little tricky. For example, `this` alone always is, but `Foo.this` is if the class being compiled is `Foo` or any supertype of `Foo`, *except* when `Foo` is an outer class containing the class being compiled, when it instead refers to that outer instance.
> 
> On the other hand, `Foo.super` (which, unlike `Foo.this`, can only be used to invoke a method), when `Foo` is a type and not a variable, refers to the current 'this' instance when the class being compiled is `Foo` or any supertype of `Foo`, period.

Archie L. Cobbs has updated the pull request with a new target base due to a merge or a rebase. The incremental webrev excludes the unrelated changes brought in by the merge/rebase. The pull request contains three additional commits since the last revision:

 - Replace any remaining uses of TreeInfo.isThisQualifier().
   
   Bug 8193904 describes how "A.this.foo" is not detected as an early reference to
   the uninitialized final variable "foo". There is also a flip-side to this bug,
   which is that "A.this.foo = ..." is not accepted as a valid assignment to the
   uninitialized final variable "foo". This commit fixes that part of the bug.
   
   Also do some minor refactoring for clarity.
 - Merge branch 'master' into JDK-8193904
 - Disallow early access to final fields via qualified 'this'.

-------------

Changes:
  - all: https://git.openjdk.org/jdk/pull/10956/files
  - new: https://git.openjdk.org/jdk/pull/10956/files/7dfff1a4..bbb800a9

Webrevs:
 - full: https://webrevs.openjdk.org/?repo=jdk&pr=10956&range=01
 - incr: https://webrevs.openjdk.org/?repo=jdk&pr=10956&range=00-01

  Stats: 89224 lines in 1450 files changed: 30188 ins; 52786 del; 6250 mod
  Patch: https://git.openjdk.org/jdk/pull/10956.diff
  Fetch: git fetch https://git.openjdk.org/jdk pull/10956/head:pull/10956

PR: https://git.openjdk.org/jdk/pull/10956


More information about the compiler-dev mailing list