Skip to content

Parametric nullability for <T extends @NullnessUnspecified Object> #76

Closed

Description

@cpovirk

I think the current proposal is likely to produce the results we want in practice. But it feels like a special case to me, and I think that some of the alternative rules under discussion can make that happen.


The design proposal currently has:

If the bound’s effective specifier is @NotNull or @NullnessUnknown, then that is the type variable usage’s effective specifier.

For @NotNull, I think we all agree that this is desirable.

For @NullnessUnknown, I'm hoping to replace this and other one-off rules (like #45) with my mental model for @NullnessUnspecified -- which it's sounding like is similar to Kolin's flexible/platform types and to existential types, as laid out by @mernst.

To see what that looks like, let's first look at our existing rule for @Nullable. It produces results like this:

@DefaultNotNull
class Manager<T extends @Nullable Object> {
  void log(T obj) {
    Logger.log(obj.toString()); // ERROR: null might be possible
  }

  T create() {
    return canCreate ? doCreate() : null; // ERROR: null might be forbidden
  }
}

Now let's look at the current proposal's rule for @NullnessUnspecified. It considers both usages of T to have unspecified nullness. That demotes both errors to warnings:

[@DefaultNullnessUnspecified]
class Manager<T> {
  void log(T obj) {
    Logger.log(obj.toString()); // WARNING: null might be possible
  }

  T create() {
    return canCreate ? doCreate() : null; // WARNING: null might be forbidden
  }
}

I think this is clearly right for log. If we apply my mental model of analyzing the code twice, once with unspecified nullness replaced by @NotNull and once with it replaced by @Nullable:

  • If T "should" extend @NotNull, then the implementation is safe.
  • If T "should" extend @Nullable, then it's not safe.

Under my mental model, we look at both outcomes and say that the code deserves a warning.

But for create:

  • If T "should" extend @NotNull, then the implementation is not safe.
  • If T "should" extend @Nullable, then it's also not safe (because of parametric nullability).

On the surface, this suggests that the more appropriate outcome for create would be an error.

But that seems wrong: Manager is completely unannotated. Maybe create is "intended" to have a signature of @Nullable T create(). So we should permit that method to return null after all -- with a warning, of course.

This whole outcome can fall out of some generalized alternative rules we've been discussing! Specifically:

  • if @DefaultNullnessUnspecified "contributes to" the effective nullness of create's return type
  • if we combine that unspecified nullness with the nullness T is instantiated with -- and do so by picking the "most nullable" value

...then we conclude that create returns either @Nullable or parametric nullness. Returning null is safe in the first case but not the second, so we issue a warning, as desired.

Activity

  1. cpovirk commented on Nov 4, 2019

    @cpovirk
    CollaboratorAuthor

    Here's another example -- though a fairly artificial one, as it's a partially annotated file that's been partially annotated in an unlikely way:

    @DefaultNotNull
    class Manager<T extends @NullnessUnspecified Object> {
      ...
    
      T create() {
        return canCreate ? doCreate() : null; // warning or error?
      }
    }

    I think that this should be an error: Neither <T extends @Nullable Object> nor <T [extends @NotNull Object]> can make this valid code.

    I believe it ends up being valid under the current proposal but invalid under the alternative rules I've been discussing.

  2. cpovirk commented on Nov 26, 2019

    @cpovirk
    CollaboratorAuthor

    though a fairly artificial one, as it's a partially annotated file that's been partially annotated in an unlikely way

    We may want to consider the possibility that such unlikely combinations could arise during automated migrations. I'm not sure how likely I think that is yet.

  3. kevinb9n commented on Nov 27, 2019

    @kevinb9n
    Collaborator

    Sorry, just gonna capture some thoughts here that may or may not help.

    Under the assumption of the nn <= unspec <= nullable are subtypes (NUNAS?) model [#33] (ignore this whole comment if we don't go that way),

    And given Foo<T> or Foo<T extends SomeType> in an unannotated/unspecified-nullness context,

    Then I believe it does not make sense that we interpret unspec-ness as applying specifically to the upper bound of T. I believe the behavior of unspec with respect to nullable and to not-null should be highly symmetrical. I can't see a reason why instantiating Foo with a not-null type is any safer than with nullable, except when Foo is a consumer type -- which are, ironically, relatively rare.

    This may in fact be a deep flaw with the entire NUNAS model (#33). But it might be that the model is fine, as long as we just rethink what an unspec type parameter really is. Roughly, it might make more sense in the case above to:

    • Consider the bound of T to be unconstrained/nullable
    • While analyzing Foo, treat every unannotated type variable usage of T within Foo as having unspecified nullness (not parametric). Effect: assignable from nullable to it, or from it to not-null, should yield the softer "unchecked"-style warning.
    • When instantiated with either specified nullness, give one big bad scary warning, then go ahead and let the chosen nullness "win" during all substitutions of T

    (There may be another issue here somewhere discussing the last point specifically.)

    (Note: if we ended up doing something like this, the next question is how a user should write that they want this handling for T even when inside a not-null context; i.e. should we have them write Foo<@Unspec T> after all, to avoid confusing the issue.)

  4. kevinb9n commented on Dec 3, 2019

    @kevinb9n
    Collaborator

    As far as I can tell, I think the topic I'm exploring in the last comment strikes at the heart of the whole "is nullness info carried entirely by types, or do type parameters have additional properties" debate (#60). You could view what I'm suggesting as a partial deviation from the former toward the latter.

    (Still, apart from this one issue, I'm not really clear on any other compelling flaw with the former or benefit to the latter. But that's not to be debated here.)

  5. kevin1e100 commented on Dec 5, 2019

    @kevin1e100
    Collaborator

    Agree that distinguishing "unspecified nullness"-bounded type parameters is highly awkward, and that they seem (almost) indistinguishably close to parametric type parameters. In my mind there are two key things we're trying to capture:

    • we don't know whether @Nullable parameterizations make sense for unspecified nullness-bounded type parameters
    • assuming a @NotNull parameterization, we don't know whether any of the occurrences of type variable can actually be assumed to be @NotNull in the resulting parameterized type. (@cpovirk has convinced me that @Nullable parameterizations don't have this issue, but as said above, the problem with those is that we don't know if they're even intended.)

    One takeaway from these two bullets is that the two possible parameterizations seemingly have asymmetric problems (!). Nonetheless, nullness-unspecified type parameters have these two challenges, and that's different from a nullness-unspecified String or other base type usage.

    Anyway, I'll point out that tools have the freedom to warn or error or be silent in the examples given in the leading comment of this issue, no matter what the specification says. Defining type variable usages as "nullness unspecified" from the specification's point of view is just a technical means that helps us define nullness of members of parameterized types; for the generic class itself only implementation code will care, which tools can treat as they like.

  6. kevinb9n commented on Dec 5, 2019

    @kevinb9n
    Collaborator

    I'm now thinking that unspecified-nullness type parameters are exactly the "parametric nulllness" case that you get with extends @Nullable, just a subcategory with some additional properties too.

    After all, we have no information about nullness, therefore we have no basis for constraining how it can be parameterized.

    I'm still not sure that the problems of @Nullable/@NotNull parameterizations aren't symmetric. I think I somewhat follow Chris's mental model of "consider both possibilities for how T might be bounded with a proper nullness in the future". But one reason I'm not sure that's valid is that it doesn't necessarily have to be the case that either of those is correct. The third possibility is that the only way to correctly annotate the class must involve both setting the right bound for T and tweaking one or more of the T usages to be projected types at the same time.

    The symmetric way to look at it is more like:

    (Assume class Legacy<T> is in an unspec context, and contains type usages of T as both in-types and out-types.)

    • With Legacy<@Nullable Blah>, out-types are safe, but it lets you send null as an in-type, which might be a bug (not necessarily resulting in immediate NPE).

    • With Legacy<@NotNull Blah>, in-types are safe, but it lets you receive a non-nullable out-type, which might actually hold null at runtime, which would be a bug (not necessarily resulting in immediate NPE).

    (We still have a separate discussion somewhere about whether this project needs to establish whether to treat only that parameterization itself as problematic, or each individual API usage of the kinds above.)

    Is that symmetry appropriate/desirable?

  7. kevin1e100 commented on Dec 7, 2019

    @kevin1e100
    Collaborator

    The symmetric way to look at it is more like:

    (Assume class Legacy<T> is in an unspec context, and contains type usages of T as both in-types and out-types.)

    • With Legacy<@Nullable Blah>, out-types are safe, but it lets you send null as an in-type, which might be a bug (not necessarily resulting in immediate NPE).

    In principle this is certainly true, but there are several things that work in our favor:

    • unless a sound nullness checker is used to check all code, and in particular, to check both caller and callee, there can be "bugs" anywhere, even behind a simple @Nullable String x method parameter: annotating a method parameter @Nullable is kind of a promise that the method will be careful with dereferencing x, but nothing really guarantees that the method implementation adheres to that promise. A method parameter that "becomes" @Nullable String because of a type parameterization doesn't seem to be fundamentally more or less dangerous.
    • as with a simple @Nullable String method parameter, we have a counter-move, which is to optimistically assume something about the callee. That assumption ends up imposing a requirement on the callee's implementation code. Specifically, for a T x method parameter (even if it has unspecified nullness) we can simply assume that it won't be just blindly dereferenced. If a tool ever gets to check the callee's implementation it would be expected to flag such blind dereferences not preceded by a null check. This "trick" that all modular analyses use ends up allowing us to "tune" how optimistic we want to be at call sites, by imposing more or fewer requirements on callees. Again, this isn't fundamentally that different from making assumptions about a @Nullable String x method parameter.
    • @cpovirk's key observation about this point was that if a @Nullable parameterization is supported at all by the generic class then it's very likely that occurrences of T are indeed expected to be @Nullable in @Nullable parameterizations of the generic class. So the practical likelihood of a "bug" is seemingly low in this case, but there does seem a good chance that @Nullable parameterizations may not be valid in the first place.
    • With Legacy<@NotNull Blah>, in-types are safe, but it lets you receive a non-nullable out-type, which might actually hold null at runtime, which would be a bug (not necessarily resulting in immediate NPE).

    Right. Technically we can apply the same "trick" as mentioned above here, which is to just assume that the callee returning a @NotNull Blah will do so, and hope that the callee implementation will be checked accordingly. There are two differences to the case above, though:

    • There are plenty of examples where the return type of an unannotated T foo() method in fact needs an @Nullable annotation to be correctly specified (e.g., getOrNull-type methods). Meaning, the likelihood of a hidden bug here is seemingly higher than in the previous case.
    • Because of the "not-null" <= "null unspec" <= "nullable" hierarchy and assuming only upper bounds can be specified, @NotNull is technically always a legal parameterization (possibly justifying not warning about them).

    (We still have a separate discussion somewhere about whether this project needs to establish whether to treat only that parameterization itself as problematic, or each individual API usage of the kinds above.)

    Agreed, and as alluded to, the nuances mentioned above (that @cpovirk initially observed) may help give an answer here, but I agree that it's seemingly always sufficient to warn on either parameterization or API usages.

    Is that symmetry appropriate/desirable?

    I think it's fine, despite the mentioned "likelihood" nuances, to stick to a symmetric view. I personally do find it somewhat compelling, for usability's sake, to take advantage of the mentioned nuanced differences between in- and out-types, assuming we can convince ourselves that we believe in them sufficiently. Regardless of whether we're going symmetric or asymmetric, it's been helpful for me to keep in mind that we're always playing the mentioned "trick", where we draw a line at which to start making assumptions about callees (wrt both in-types and out-types), and to realize that this "trick" can be used to make asymmetric assumptions just as soundly as symmetric ones. Does that make sense?

  8. added
    nullness
    on Dec 12, 2019
  9. kevin1e100 commented on Jan 3, 2020

    @kevin1e100
    Collaborator

    For reference, I tried reworking the proposal document to treat usages of type variables declared as

    <T extends [@NullnessUnspecified] X>

    as "assumed parametric nullability" (term not final). I would have preferred not creating a separate category for this, but this ends up being a bit cleaner I feel than labeling these type variable usages @NullnessUnspecified, which was always a kluge and I believe prompted this issue (see quoted text above).

    In case you haven't seen it, the proposal now also has explicit text on how to interpret parameterized types. Distinguishing "parametric nullability" and "assumed parametric nullability" type parameters allows giving the latter, effectively, "more nullable" semantics without changing how type parameters work overall. Using this semantics I believe matches how Kotlin handles unannotated classes with type parameters that are parameterized in a Kotlin file (see #45), and it seems desirable for the specification to agree with Kotlin on that point: it's not clear to me how Kotlin and the spec can disagree on how to handle unannotated files (since unannotated files can't give clues as to whether they want to adhere to the spec), and the alternative would be a breaking change to Kotlin, which seems gratuitous for this case.

  10. kevinb9n commented on Jun 23, 2021

    @kevinb9n
    Collaborator

    It's been an eventful 18 months since the last comment on this issue. @cpovirk, can you give a fresh description of what's solved and what's not solved here?

  11. cpovirk commented on Jul 14, 2021

    @cpovirk
    CollaboratorAuthor

    I think that this was solved with the addition of "assumed parametric nullability": If a type like List is unannotated, we're able to detect that List<@Nullable String> has @Nullable types for, e.g., the return value of get.

  12. added
    design
    on Mar 13, 2024
  13. added this to the 0.3 milestone on Mar 27, 2024
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

    designnullness

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions