Skip to content

Improve error message argument.type.incompatible for wildcards #1281

@aosen-xiong

Description

@aosen-xiong

Get the error from eisop/jdk#122.

After looking around, I realize this issue is the same as typetool#520. But I think it is important to put it in EISOP as well.

import java.util.function.Consumer;
import java.lang.StackWalker.StackFrame;

public class Demo{
    public void tryAdvance(Consumer<? super StackFrame> action, StackFrame frame1) {
            StackFrame frame = null;
            action.accept(frame);
    }
}
Demo.java:8: error: [argument.type.incompatible] incompatible argument for parameter arg0 of Consumer.accept.
            action.accept(frame);
                          ^
  found   : @Nullable StackFrame
  required: capture#01 extends @Nullable Object super @NonNull StackFrame
1 error

The error message is not as informative as it should be. From first look, the found type in the range and no error should be issued.

However, we should only pass subtype of wildcard's lower bound to be safe because ? stands for unknown type.

Simliarly, when read from a wildcard, we should declare a super type of wildcard upperbound to store it.

I am using the following list example to show the difference.

List<? super Number> numbers = new ArrayList<Object>();

// ✅ Writing: allowed
numbers.add(new Integer(1));

// ❌ Writing: not allowed
numbers.add(new Object()); // Error: Object is not a subtype of Number

// ✅ Reading: always safe as Object
Object o = numbers.get(0);

// ❌ Reading: not allowed as Number
Number n = numbers.get(0); // Error: type is only known to be ? super Number

Fix this issue can also unskip https://github.com/eisop/checker-framework/blob/master/checker/tests/nullness/Issue520.java

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions