[jdk17] RFR: 8268766: Desugaring of pattern matching enum switch should be improved

Jan Lahoda jlahoda at openjdk.java.net
Wed Jun 16 18:40:30 UTC 2021

On Wed, 16 Jun 2021 15:15:25 GMT, Jan Lahoda <jlahoda at openjdk.org> wrote:

> Currently, an enum switch with patterns is desugared in a very non-standard, and potentially slow, way. It would be better to use the standard `typeSwitch` bootstrap to classify the enum constants. The bootstrap needs to accept enum constants as labels in order to allow this. A complication is that if an enum constant is missing, that is not an incompatible change for the switch, and the switch should simply work as if the case for the missing constant didn't exist. So, the proposed solution is to have a new bootstrap `enumConstant` that converts the enum constant name to the enum constant, returning `null`, if the constant does not exist. It delegates to `ConstantBootstraps.enumConstant` to do the actual conversion. And `typeSwitch` accepts `null`s as padding.
> How does this look?

I was thinking of having a new bootstrap method for enums, but then (in a discussion with Maurizio), it turned out it might be better to reuse `typeSwitch` for consistency and orthogonality. The usecase is not really much different from e.g. pattern switches over Strings (or Integers). One can write something like:

         String sel = "";
         switch (sel) {
             case "a" -> {}
             case String s && s.length() < 5 -> {}
             case "toolong" -> {}
             case String s -> {}

And javac will use `typeSwitch` for that (and I think it is more or less necessary to mix constants and patterns in the static arguments of the bootstrap method, as the switch may mix constants and patterns with guards in any order). We can do something similar with enums:

         E sel = null;
         switch (sel) {
             case A -> {}
             case E e && "B".equals(e.name()) -> {}
             case C -> {}
             case E e -> {}

Does not seem much different, the only change is that the constants are enum constants, not String constants (which brings some challenges - like the possibility that the enum constant cannot be resolved).

But I can create a separate bootstrap method, if strongly preferred.


PR: https://git.openjdk.java.net/jdk17/pull/81

More information about the compiler-dev mailing list