redhat-developer / vscode-java

Java Language Support for Visual Studio Code
Eclipse Public License 2.0
2.08k stars 441 forks source link

Type parameter related false positive error messages. #3816

Open QinlinChen opened 1 month ago

QinlinChen commented 1 month ago

I encountered some error messages on my code that can be correctly compiled and run, meaning that these errors could be false positives. After simplifying the code, I found that these false positives could be caused by incorrect name shadowing for type parameters.

Environment
Steps To Reproduce
  1. Create an empty java project and open it with vscode.
  2. Create a package demo and a App.java file in this package.
  3. Paste the code below into App.java:
    
    package demo;

interface BinaryExpr { interface Op { }

Op getOperator();

}

abstract class AbstractBinaryExpr implements BinaryExpr { private final Op op;

public AbstractBinaryExpr(Op op) { this.op = op; }

@Override
public Op getOperator() {
    return op;
}

}

final class ArithExpr extends AbstractBinaryExpr { enum Op implements BinaryExpr.Op { ADD, SUB }

public ArithExpr(Op op) { super(op); }

}

public class App {

public static void main(String[] args) {
    var e = new ArithExpr(ArithExpr.Op.ADD);
    System.out.println(toStr(e));
}

public static String toStr(ArithExpr e) {
    return switch(e.getOperator()) {
        case ADD -> "+";
        case SUB -> "-";
    };
}

}


##### Current Result

You will see the following three error messages:
```java
// ...
public static String toStr(ArithExpr e) {
    return switch(e.getOperator()) { // Error 1: A switch expression should have a default case
        case ADD -> "+"; // Error 2: ADD cannot be resolved to a variable
        case SUB -> "-"; // Error 3: SUB cannot be resolved to a variable
    };
}
Expected Result

No error messages are expected because java compiler can handle it correctly.

Additional Informations

If you rename the type parameter Op and its following occurrances in class AbstractBinaryExpr into O, the error messages will disappear. This hints that the return type Op of AbstractBinaryExpr.getOperator() may be resolved to the Op in the superclass BinaryExpr rather than the type parameter.

snjeza commented 1 month ago

This is an upstream jdt issue. I can reproduce it in the Eclipse master branch, but I can't reproduce it in the javac branch.