Skip to content

Require a finding on a contravariant parameter type? [working decision: no] #49

Open

Description

@dzharkov

In the draft proposal, there's a part that allows for overrides to have value parameters with contravariant nullability:

The method’s parameter types may have wider nullability than the corresponding superparameters' types, meaning, it suffices for superparameters to be type-convertible to the overriding method’s parameter types (while base types have to follow the normal rules of the compiler so overriding works as expected).

That might be a problem for the Kotlin compiler since in pure Kotlin value parameters are not contravariant in overrides and we apply the same logic when looking at the annotated Java code.

The reason we don't allow contravariant parameters in override is basically the same as in Java: they might be considered as overloads. In Java, one can not override with a wider-typed parameter (types should be equal). The same applies for Kotlin, but we have nullability as a built-in part of the type system.

interface A {
    fun foo(x: String)
}

class B : A {
    override fun foo(x: String) {
        
    }
    
    @JvmName("fooNullable")
    fun foo(x: String?) {} // is a different overload for `foo`
}

fun main() {
    B().foo("") // resolved to the not-nullable
    B().foo(null) // resolved to nullable
}

That means that when we see contravariant nullability in Java annotations, such code is assumed to be illegal thus we ignore annotations info for such parts completely as inconsistent:

interface A {
    void foo(@NotNull String x);
}

class B implements A {
    @Override
    public void foo(@Nullable String x) {

    }
}

B::foo has signature like fun foo(x: String!), i.e. it has unknown nullability from Kotlin point-of-view.

But at the same time it's fine transforming from unknown nullness to both NotNull and Nullable:

interface A {
    void foo(String x, String y);
}

class B implements A {
    @Override
    public void foo(@Nullable String x, @NotNull String y) {

    }
}

In the above example B::foo is perceived by Kotlin as fun foo(x: String?, y: String)

Activity

  1. donnerpeter commented on Jul 23, 2019

    @donnerpeter
    Collaborator

    In Java, IntelliJ IDEA's inspections currently allow nullable parameters overriding notnull ones, as there were such requests from users.

  2. kevin1e100 commented on Jul 23, 2019

    @kevin1e100
    Collaborator

    As mentioned before I think we can just leave out parameter type contravariance for now to unblock prototyping, as from the Java point of view we should be able to safely add it later (please correct me if I'm missing something).

    I'll just point out that the overload-vs-override concern seems possibly solvable to me, since Kotlin uses different JVM method names in that case. That technically would be consistent with a proposal that allows contravariant nullability specifiers for methods that override each other according to the JVM, though it probably couldn't be allowed in a Kotlin class overriding another Kotlin class.

    The fact that kotlinc infers platform types when it sees contravariant overrides is certainly problematic but maybe could be avoided as well? Again I'm happy to defer this, but I do expect users to ask for contravariance eventually (see @donnerpeter comment above), so maybe worth thinking about if it could somehow be accommodated in kotlinc.

  3. kevin1e100 commented on Jul 23, 2019

    @kevin1e100
    Collaborator

    For posterity, here's some (about-to-be-deleted) rationale that was in the proposal for why contravariant parameter types might be interesting:

    • This rule differs from the situation for base types, which cannot have contravariant parameters for reasons that are much less applicable to us.
    • This also should make things more forgiving when subclassing legacy code (you can mark parameters nullable if you want to accept null, and, with the unchecked conversions mentioned above, you can mark parameters that are “unknown” in the base class as not-null as well). It also means that a method can override corresponding methods of multiple supertypes even when they are annotated differently (but compatibly).
  4. cpovirk commented on Jul 24, 2019

    @cpovirk
    Collaborator

    One distinction that is already made in the doc but I want to call out here is that we still plan to accommodate overriding methods whose parameters types include unknown nullability. That solves part of the problem here. (And it solves that part of the problem better than mere contravariance, since it applies also to conversions between List<@NullnessUnknown String> and List<@NotNull String>, which are unrelated types and thus would not be covered by contravariance support.) I'm hoping that it solves a lot of the problem. And I'm hoping that another part of the problem is methods whose parameters types are traditionally annotated as non-null because people are using annotations/tools that don't support annotating type parameter bounds but should instead have parametric nullability. Once parametric nullability is widely supported, users might see less need for contravariant parameter types. And, as noted earlier, contravariance doesn't help with cases like List<@NullnessUnknown String> and List<@NotNull String>, anyway.

    I still can imagine that we'd want to support this someday, but +1 for putting it off for now. And when we do allow it, I think it's worth considering whether it's worthy of a warning, since it might happen accidentally (or intentionally but in cases in which there's a better solution available) as much as it happens in "good" cases.

  5. kevinb9n commented on Jul 24, 2019

    @kevinb9n
    Collaborator

    I am also more than happy to jettison parameter contravariance for the time being.

  6. cpovirk commented on Sep 23, 2019

    @cpovirk
    Collaborator

    If we really wanted, we could annotate Collection.contains and similar methods as requiring [@NotNull] Object, since some collections do throw when called with contains(null). Then we'd want for subclasses to be able to override those to accept @Nullable Object. However:

    • Overriding often won't help, since users don't generally maintain a reference of type, e.g., ArrayList.
    • My guess is that we'd just declare it as contains(@Nullable Object) and live with the occasional NullPointerException. (This appears to be what the Checker Framework does -- though then it defines TreeSet with contains(Object). I'm a little surprised that that is allowed (probably it isn't, except in stubs?). But it is safer for people who have a reference of type TreeSet, albeit only by being even more conservative than ideal.) Or at most we'd use @NullUnspecified, which might permit subclasses to change nullability in overrides in even more flexible ways.
  7. cpovirk commented on Oct 11, 2019

    @cpovirk
    Collaborator

    It sounds like we can probably close this, at least as a way of saying "not yet?" (Or maybe we want some other way of marking issues as "post-1.0?")

    (As for my post just above this one, it seems pretty clear that kevinb9n, at least, is in favor of contains(@Nullable Object), too, based on this and this.)

  8. mernst commented on May 28, 2020

    @mernst
    Contributor

    Formal parameter type contravariance is consistent with Java, so it is natural and strongly desirable. If we were designing Kspecify rather than Jspecify, we might make a different decision.

    I think we should accommodate Kotlin whenever we can, but we should never degrade the behavior of Jspecify on Java code in order to conform to Kotlin's different semantics.

  9. kevinb9n commented on May 28, 2020

    @kevinb9n
    Collaborator

    I've kept coming back to this in my mind, and am just gonna reopen it for now. It may not be a critical priority right now, but I don't think that's what the open/close status is supposed to show.

    If we don't have parameter contravariance, doesn't that mean that a method and all of its overrides can only have their annotations changed in perfect lockstep? That's against a project requirement, and it just feels bad to prohibit a method from accepting null if it wants to unless it changes the whole world around it.

  10. cpovirk commented on May 29, 2020

    @cpovirk
    Collaborator

    (Reopening sounds fine.)

    RE: changing annotations in lockstep: No, that's not required. See #49 (comment). Note also that, even with specified nullness, library authors are likely to have the option to suppress the error on the overriding method. (But I grant that it's unfortunate to have to suppress in the case of a contravariant override (which is safe) just as you do for a covariant override (which is not).)

    RE: consistency with Java: I can see how contravariance is:

    • sound
    • compatible with plain Java (since Java won't care about our annotations at all)

    The one way in which it's arguably inconsistent is that Java doesn't support such contravariance at present. For example, I can't override foo(String) with foo(Object): I just get an overload.

    Now, again, overloading isn't possible in our case (since foo(String) and foo(@Nullable String) have the same erasure), so I'm not saying that users should be able to define two separate methods with those signatures. I just mean that, if users are able to override one with the other, we'd be somewhat breaking new ground.

    I think we're all in agreement on this, but I wanted to make sure I'm not missing a deeper point that you're making.

    Furthermore, breaking new ground might be perfectly fine. (I don't think I've formed a strong opinion yet. My main opinion so far is "not yet" :))

  11. kevinb9n commented on Jun 4, 2020

    @kevinb9n
    Collaborator

    re: "lockstep", right, I forgot that we were going to have to special-case unspecified. It would just be nicer to have the right thing happen for unspecified as a simple consequence of our general contravariant-parameters and covariant-returns support.

  12. kevinb9n commented on Jun 4, 2020

    @kevinb9n
    Collaborator

    BTW, in the case of covariant returns I don't think jspecify even needs to do anything; just by explaining how the annotations are meant to modify types, users "should" assume they can do covariant returns because that's just how return types work.

    This one would need to be called out somehow though, because existing knowledge of types makes the wrong implication.

  13. cpovirk commented on Jun 12, 2020

    @cpovirk
    Collaborator

    It would just be nicer to have the right thing happen for unspecified as a simple consequence of our general contravariant-parameters and covariant-returns support.

    Even with contravariant parameter types, we'd still like for unspecified to be considered to be "the same type" as both nullable and non-null.

    The reason is parameterized types: Suppose a method in an unannotated interface accepts a type like @Unspec List<@Unspec String>. If we want to implement that in an annotated class, we would like to avoid @Unspec. Even if the right type is @Nullable List<@Nullable String>, that's not a supertype of the old method's parameters because parameterized types are invariant. So contravariance isn't enough.

    But you have made me see that, just as the "same type" check can permit things that contravariant parameter types cannot, the reverse is also true: Contravariant parameter types can permit some declarations to work without warnings or errors, like if I override a method that accepts @Unspec Object with one that accepts @Nullable Object.

    Still, I see "the same type" as the essential feature and contravariant parameter types as the possible add-on.

  14. 41 remaining items

  15. added
    designAn issue that is resolved by making a decision, about whether and how something should work.
    on Mar 13, 2024
  16. netdpb commented on Apr 9, 2024

    @netdpb
    Collaborator

    Current decision: When a parameter type is a supertype of the parameter type it overrides (a "contravariant parameter"), there is no resulting "JSpecify-based" finding. (A tool can report something if it wants to, but that is separate and should not be enabled when running JSpecify tests.)

    Argument for changing: Kotlin does not allow such overrides. However, JSpecify focuses on Java declarations.

    Timing: This must be decided before version 1.0 of the spec.

    Proposal for 1.0: Finalize the current decision. If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.

  17. cpovirk commented on Apr 11, 2024

    @cpovirk
    Collaborator

    I keep feeling that I'm almost on top of this issue, only for things to get slippery again.

    JSpecify currently says essentially nothing about when its subtyping check and similar checks should be deployed on Java source. This issue might be about starting to say such things, or it might be about what conformance tests we write.

    Part of my concern has been that we both seem to want to say "We don't tell checkers when to apply or not apply our checks" and also seem to want to say "But by writing a conformance test about this situation, we are implicitly telling checkers that applying our checks here would be in some way 'unjustified.'"

    The samples tried to dodge this question by saying that they're written under the assumption of JLS-like rules (which of course ban contravariant parameters) but that that those rules (a) have no necessary connection to what checkers do and (b) are more strict than "necessary":

    You can think of these as extending the normal JLS type rules to cover types that have been augmented with nullness information. (For example, the value of a return statement must be convertible to the method's return type, and the receiver in a method call should not be @Nullable.) ... Nullness checkers are... not obligated to do anything for any particular comment.... Note that a nullness checker can be sound even if it does not issue errors for some cases of jspecify_nullness_mismatch or jspecify_nullness_not_enough_information!

    [edit: The spec says something similar.]

    I would like more clarity on whether this issue is "We will not write a conformance test for this case" or "We will write a conformance test for this case that contains no cannot-convert comment (or override-conflict comment or whatever)" or "We will recommend that tools not produce errors in such situations" or some combination of those or what.

    I also wonder a little if we're opening a can of worms by trying to go beyond the JLS rules for when to apply checks. For example, if a supermethod has a type parameter <T extends Object>, is it OK for a submethod to declare it as <T extends @Nullable Object> if the resulting changes produce only covariant return-type changes and contravariant parameter-type changes? Maybe we don't need to care about that relative edge case. I just think I recall some complexity in the Checker Framework that seemed to arise from trying to handle such overrides. [edit: It came up not long after I wrote this :)] So I'd also like to have some idea of whether we want to say something like "We've thought specifically about contravariant parameter types, and we think they work well in practice" or "We think that going beyond the JLS is safe in general."

    I may be making a big thing out of an inconsequential decision. Part of my concern is that it keeps sounding inconsequential, only for phrasing about what is (e.g.) "correct" to crop back up.

    If I had managed to collect my thoughts earlier, I would have talked to kevinb9n about this (more) in person.... We should probably talk sometime.

  18. cpovirk commented on Apr 12, 2024

    @cpovirk
    Collaborator

    tl;dr I think that "finding" and "JSpecify-based" are undefined terms that are making the question slippery.

    My proposal would be:

    If it helps, I would also be open to agreeing to expand some non-normative resources to explain why contravariant parameters are worth considering.

  19. cpovirk commented on Apr 29, 2024

    @cpovirk
    Collaborator

    After some discussion elsewhere, I think I could get behind the proposal if we change "'JSpecify-based' finding" to "JSpecify conformance finding," which I think makes clearer that this is about what the checker must be able to recognize internally in order to pass our tests. (There are surely other formulations that could work, too, but that one might minimize the edit distance :))

  20. cpovirk commented on May 14, 2024

    @cpovirk
    Collaborator

    Fun fact that I can't resist posting here: In one narrow way, you totally can declare a contravariant parameter type in Java:

    class OverrideNoTypeVariable {
      interface Super<T> {
        void x(T t);
      }
    
      interface Sub<T> extends Super<T> {
        @Override
        void x(Object t);
      }
    }

    It builds without even a warning.

    ("the signature of m1 is the same as the erasure (§4.6) of the signature of m2.")

  21. cpovirk commented on May 19, 2024

    @cpovirk
    Collaborator

    I just tried the contravariant parameter type with ImmutableMultimap.get, since it could be nice for it to accept Object instead of K (though, if we do that, we should probably update https://errorprone.info/bugpattern/CollectionIncompatibleType accordingly :)).

    That turns out to not go so great: Calls that pass a K appear to start resolving to the supermethod Multimap.get, whose return type is Collection instead of ImmutableCollection, leading to build errors in code that expects ImmutableCollection.

  22. netdpb commented on Jun 13, 2024

    @netdpb
    Collaborator

    Proposal: As described in JSpecify Conformance: Questions and Answers, conformance tests will check that tools can recognize when a parameter's type is nullness-contravariant with respect to its supermethod, but that will impose no requirement on tools to report anything in particular to users.

    Timing: This must be decided before version 1.0 of the spec.

    If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.

  23. kevinb9n commented on Jun 14, 2024

    @kevinb9n
    Collaborator

    This seems different from what Chris and I were approaching agreement on, but I am considering just agreeing to get this over with, and it probably wouldn't be a disaster. Just for now though, I am keeping this in my "probably need to create a doc to get resolution on" bucket.

  24. cpovirk commented on Jun 14, 2024

    @cpovirk
    Collaborator

    Is the difference just between...

    • "This is a different case than non-contravariant parameter changes, so our conformance tests will require tools to distinguish those cases by expecting no finding in this case."
    • "This is a different case than non-contravariant parameter changes, so our conformance tests will require tools to distinguish those cases by expecting a different kind of finding in this case."

    ...or is there anything deeper going on? Either way, we'll probably want to take it to a doc, as you said.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    designAn issue that is resolved by making a decision, about whether and how something should work.nullnessFor issues specific to nullness analysis.

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions