Type use annotations on instanceof patterns
Alex Buckley
alex.buckley at oracle.com
Wed Nov 22 20:48:59 UTC 2023
On 11/22/2023 9:55 AM, Werner Dietl wrote:
> if (x instanceof @TA Float) {
> if (x instanceof @TA Boolean b) {
>
> @Target(ElementType.TYPE_USE)
> @Retention(RetentionPolicy.RUNTIME)
> @interface TA {}
>
> 1) When looking at the bytecode with `javap -v
> InstanceOfPatternVariable.class` I only see one use of @TA:
>
> RuntimeVisibleTypeAnnotations:
> 0: #19(): INSTANCEOF, offset=1
> InstanceOfPatternVariable$TA
>
> The JSL 15.20.2 [1] says "An instanceof expression may perform either
> type comparison or pattern matching."
> The JVMS 4.7.20-B [2] talks about how type annotations on "instanceof
> expressions" are stored.
> It would therefore seem to me that both occurrences of TA should be
> stored in the class file.
(You mean both occurrences of the annotation `@TA`. The annotation
interface `TA` is a distinct thing.)
Yes, both occurrences of `@TA` should be stored. Let's "prove it" for
the second occurrence.
The type pattern `Boolean b` is defined (per 14.30.1) as a local
variable declaration. The annotation `@TA` which syntactically appears
as a modifier on that declaration is interpreted according to 9.7.4. How?
The annotation interface `TA` is defined with TYPE_USE, which means (per
9.6.4.1) that `TA` is applicable in type contexts. One of the type
contexts (per 4.11) is: "The type in a local variable declaration in
either a statement ... or a pattern". So, the following rule in 9.7.4
applies:
```
- If the annotation's interface is applicable in type contexts, and not
in the declaration context corresponding to the declaration, then the
annotation is deemed to apply only to the type which is closest to the
annotation.
```
This means that the annotation `@TA` is a type annotation (applying to
the use of the `Boolean` type within a local variable declaration) and
not a declaration annotation on the overall local variable declaration
`Boolean b`.
Great -- type annotations integrate with type patterns in the JLS as you
would expect. Consequently, `@TA` should appear in the RVTA attribute
via a localvar_target item. Perhaps javac is emitting the item but javap
is unable to render it.
Alex
More information about the compiler-dev
mailing list