eclipse-jdt / eclipse.jdt.core

Eclipse Public License 2.0
168 stars 132 forks source link

[Enhanced Switch][Null] Inconsistent nullness propagation #3319

Open srikanth-sankaran opened 1 week ago

srikanth-sankaran commented 1 week ago

Found by code inspection:

With null analysis enabled, we report two warnings in foo(Object) Null comparison always yields false: The variable o cannot be null at this location but none in foo(X) (with redundant null check set to warning)

import org.eclipse.jdt.annotation.NonNull;

public class X {
    static @NonNull Object foo(Object o) {
        switch (o) {
            case String s -> {
                if (o == null) {
                    System.out.println("o cannot be null at all!");
                }
                System.out.println();
            }
            default -> {
                if (o == null) {
                    System.out.println("o cannot be null at all!");
                }
                System.out.println();   
            }
        }
        return new Object();
    }

    static @NonNull Object foo(X o) {
        switch (o) {
            case X s  -> {
                if (o == null) {
                    System.out.println("o cannot be null at all!");
                }
                System.out.println(s);
            }
        }
        return new Object();
    }
}

This is because of the incorrect asymmetry in org.eclipse.jdt.internal.compiler.ast.SwitchStatement.analyseCode(BlockScope, FlowContext, FlowInfo) between a regular case and a default.

srikanth-sankaran commented 1 week ago

This is because of the incorrect asymmetry in org.eclipse.jdt.internal.compiler.ast.SwitchStatement.analyseCode(BlockScope, FlowContext, FlowInfo) between a regular case and a default.

Not entirely sure of this. Need to study in detail.

At the outset it does look like there is some inconsistent behavior. Cause may be different than hypothesized.