RFR: 8268320: Better error recovery for broken patterns in switch

Rémi Forax forax at openjdk.java.net
Thu Jun 10 10:02:16 UTC 2021


On Wed, 9 Jun 2021 19:50:00 GMT, Jan Lahoda <jlahoda at openjdk.org> wrote:

> Trying to improve error recovery in case the user wanted to use a type-pattern in the switch construct, but didn't put a binding variable name after the type name. E.g.:
> 
> $ cat test/langtools/tools/javac/diags/examples/PatternExpected.java
> [snip]
> class PatternSwitch {
>     private void doSwitch(Object o) {
>         switch (o) {
>             case String: break;
>             default: break;
>         }
>     }
> }
> $ javac --enable-preview -source 17  test/langtools/tools/javac/diags/examples/PatternExpected.java
> test/langtools/tools/javac/diags/examples/PatternExpected.java:32: error: type pattern expected
>             case String: break;
>                  ^
> Note: test/langtools/tools/javac/diags/examples/PatternExpected.java uses preview features of Java SE 17.
> Note: Recompile with -Xlint:preview for details.
> 1 error

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java line 1748:

> 1746:                                     }
> 1747:                                 } else if (!stringSwitch && !types.isAssignable(seltype, syms.intType)) {
> 1748:                                     log.error(pat.pos(), Errors.ConstantLabelNotCompatible(pattype, seltype));

I wonder if in the long term it's not better instead of having several ad-hoc way to find the kind of switch it is,
`types.isAssignable(seltype, syms.intType)`, `stringSwitch` or `pattype.constValue() == null && s.kind == TYP`
to have an enum with 4 values INT_SWITCH, STRING_SWITCH, ENUM_SWITCH and PATTERN_SWITCH.

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

PR: https://git.openjdk.java.net/jdk/pull/4441


More information about the compiler-dev mailing list