Type use annotations on instanceof patterns

Angelos Bimpoudis angelos.bimpoudis at oracle.com
Thu Nov 23 13:49:15 UTC 2023


Thanks for the analysis and report

Opened https://bugs.openjdk.org/browse/JDK-8320660

________________________________
From: compiler-dev <compiler-dev-retn at openjdk.org> on behalf of Werner Dietl <wdietl at gmail.com>
Sent: 22 November 2023 18:55
To: compiler-dev <compiler-dev at openjdk.java.net>
Subject: Type use annotations on instanceof patterns

Hi all,

Take the following program:

````
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

public class InstanceOfPatternVariable {
    public void doSomething(final Object x) {
        if (x instanceof @TA Float) {
        }
        if (x instanceof @TA Boolean b) {
        }
    }

    @Target(ElementType.TYPE_USE)
    @Retention(RetentionPolicy.RUNTIME)
    @interface TA {}
}
````

This successfully compiles with javac (anything >=16 should work, I used javac 21.0.1).

I think there are two issues:

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.

2) When looking at the generated ASTs, for the first InstanceOfTree, getType() returns `@TA Float`.
For the second InstanceOfTree, getType() only returns `Boolean`, without the type annotation attached.
For the second InstanceOfTree, getPattern() seems to return a BindingPatternTree that contains a VariableTree which has `@TA Boolean` type.
It would seem more consistent if getType() for both trees returns an annotated type.

Thoughts?

I did not find an existing bug report related to type annotations and binding patterns. Did I miss one?

Thanks,
cu, WMD.

[1] https://docs.oracle.com/javase/specs/jls/se21/html/jls-15.html#jls-15.20.2
[2] https://docs.oracle.com/javase/specs/jvms/se21/html/jvms-4.html#jvms-4.7.20-410

--
https://ece.uwaterloo.ca/~wdietl/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.org/pipermail/compiler-dev/attachments/20231123/eeb1da85/attachment-0001.htm>


More information about the compiler-dev mailing list