RFR: 8300543 Compiler Implementation for Pattern Matching for switch [v2]

Maurizio Cimadamore mcimadamore at openjdk.org
Tue Apr 18 13:46:48 UTC 2023


On Tue, 18 Apr 2023 09:13:01 GMT, Jan Lahoda <jlahoda at openjdk.org> wrote:

>> This is the first draft of a patch for JEP 440 and JEP 441. Changes included:
>> 
>>  - the pattern matching for switch and record patterns features are made final, together with updates to tests.
>>  - parenthesized patterns are removed.
>>  - qualified enum constants are supported for case labels.
>> 
>> This change herein also includes removal record patterns in for each loop, which may be split into a separate PR in the future.
>
> Jan Lahoda has updated the pull request incrementally with six additional commits since the last revision:
> 
>  - Fixing infinite loop where a binding pattern is replaced with a binding pattern for the same type.
>  - Reflecting review comments.
>  - Fixing exhaustiveness for unsealed supertype pattern.
>  - No need to enable features after error reported.
>  - SwitchBootstraps.typeSwitch should not initialize enum classes.
>  - A prototype of avoiding enum initialization.

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java line 812:

> 810:                     if (l instanceof JCPatternCaseLabel patternLabel) {
> 811:                         for (Type component : components(selector.type)) {
> 812:                             patterns = patterns.prepend(PatternDescription.from(types, component, patternLabel.pat));

I noted that this code ends up adding redundant pattern descriptions to the list - for instance:


class Test {
    sealed interface I1 permits B, C { }
    sealed interface I2 permits B, C { }

    static final class B implements I1, I2 { }
    static final class C implements I1, I2 { }

    <Z extends I1 & I2> int test(Z z) {
        return switch (z) {
            case B c -> 2;
            case C d -> 3;
        };
    }
}


In this case the list ends up with 6 elements, [ B, B, B, C, C, C ]. Given that the complexity of the algorithm depends on the number of patterns in the list, it would probably be better to use a set here and try to make the list as small as possible from early on.

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Flow.java line 915:

> 913: 
> 914:                             for (PatternDescription pdOther : patterns) {
> 915:                                 if (pdOther instanceof BindingPattern bpOther) {

This code redundantly checks a pattern against itself, which I think we can avoid.

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

PR Review Comment: https://git.openjdk.org/jdk/pull/13074#discussion_r1170062325
PR Review Comment: https://git.openjdk.org/jdk/pull/13074#discussion_r1170062982


More information about the core-libs-dev mailing list