Skip to content

what happens to type variables when @NullnessUnknown (and @NotNull) type parameters are instantiated? #45

Closed

Description

@kevin1e100

Capturing a comment thread here

Let's say there's a class Foo that's not annotated at all, ie., T's effective specifier is "unknown nullness":

public class Foo<T> {
  private T value;
  T getOrThrow() { return checkNotNull(value); }
  T getOrNull() { return value; }
  set(T value); { this.value = checkNotNull(value); }
}

Now in some other Java file you do:

@DefaultNotNull
public class Bar {
  String baz(Foo<String> x) {
    return x.getOrNull();
  }
}

Meaning x has the fully explicit type @NotNull Foo<@NotNull String>. So when considering method calls on x, should we (unsoundly) assume that getOrNull() will return a @NotNull String? That set's parameter is a @NotNull String?

@cpovirk points out:

I commented on this somewhere else, saying that it was pretty scary: Even if Foo is @DefaultNullnessUnknown, then sure, Bar's Foo<String> can mean Foo<@NotNull String>. But I hope that doesn't mean that x.getOrNull() is considered to return @NotNull String. I'm hoping that @NotNull gets trumped by the effectively @NullnessUnknown T return type of getOrNull(), per:

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

I wrote the sentence quoted above but I don't think I anticipated this application of it. We could possibly do it that way but I think we'll want to be sure either way.

In general I believe the mental model I've been working with is that when a type parameter gets instantiated, the instantiation gets "pasted" everywhere the corresponding type variable is used. So T getOrNull() becomes @NotNull String getOrNull(). I think that's what you want to do if T is declared as <T extends @Nullable Object> But if T is bounded by @NullnessUnknown, as in the above example, then we could indeed just consider occurrences of T to have unknown nullness no matter how T is instantiated. And while the language quoted above just discusses type variables, and we've been trying not to specify implementation checking and what happens on method calls, it does seem like we want to formalize what Foo<@NotNull String> means in terms of methods declared in Foo.

Playing with IntelliJ's code completion popups, it seems that Kotlin, given x: Foo<String> indeed types x.getOrNull() : String!, i.e., with unknown nullness as @cpovirk would like. Given y: Foo<String?>, it types y.getOrNull() : String?, i.e., as @Nullable (which also seems sensible but i'm not sure how to specify that).

I'll note that the inverse situation also creates headaches. What I mean is, if Foo was instead declared class Foo<T extends @NotNull Object>, and given a variable Foo<@NullnessUnknown String> z, then should we expect z.getOrNull() to return a @NotNull String or a @NullnessUnknown String? Should we expect z.set(expr) to expect a @NotNull String argument or @NullnessUnknown String? I think the answer here is that it's sensible to use @NotNull String for both method result and method parameter type, though it is weird to get any @NotNull even though we had Foo<@NullnessUnknown String> z. Especially considering that if Foo was declared class Foo<T extends @Nullable Object> then we presumably would expect the same z.getOrNull() to return @NullnessUnknown String.

Maybe the asymmetry pointed out in the last example is ok. I've been trying to avoid that very asymmetry with wildcards, but if we consider it ok here then I think we may need to revisit it there for consistency.

Activity

  1. stephan-herrmann commented on Aug 2, 2019

    @stephan-herrmann

    In this example Eclipse warns at the field Foo.value:

    The field value may not have been initialized, whereas its type 'T' is a free type variable that may represent a '@NonNull' type

    IOW, a type parameter with no nullness constraints must be used with special care. Eclipse also has a separate option to tune the severity of such "pessimistic analysis for free type variables".

  2. kevin1e100 commented on Aug 2, 2019

    @kevin1e100
    CollaboratorAuthor

    @abreslav I believe mentioned there's a writeup of instantiation rules. Any chance you could share that (or paste them into the proposal doc)?

  3. abreslav commented on Aug 2, 2019

    @abreslav

    Did some analysis in the issue linked above: #57

  4. stephan-herrmann commented on Aug 11, 2019

    @stephan-herrmann

    Let's say there's a class Foo that's not annotated at all, ie., T's effective specifier is "unknown nullness":

    I disagree, and that's why I filed #62. I would really want to read T as unconstrained in this situation, not unspecified!
    Otherwise all collection types from the JRE, e.g., could only be instantiated with type arguments of unspecified nullness, which would block a lot of useful analysis.

  5. cpovirk commented on Aug 12, 2019

    @cpovirk
    Collaborator

    I think that, because we're talking about the spec, our discussion have focused to an almost distorted degree on "unknown nullness." In practice, most unannotated types that users see, especially those from java.*, will come with stubs / external annotations / specifications / something. That allows the checkers to treat ArrayList<E> as ArrayList<E extends @Nullable Object> but Optional<T> as Optional<T extends @NotNull Object>. I see stubs as the "real" solution to unannotated code (well, besides the solution of actually annotating the code directly when possible :)), with @NullnessUnknown as more of a fallback because our checkers have to do something besides crash or give up completely.

    Stubs have the advantage that we can catch problems like Optional<@Nullable String>, which we'd permit (albeit with a warning) if the type parameter of Optional had a bound whose nullness was unknown.

    All that said, I think I was confused (and thus misleading) in what I said above. I'm going to reread it and see if I can do any better.

  6. cpovirk commented on Aug 12, 2019

    @cpovirk
    Collaborator

    (Sorry, reading what I just wrote below, I'm unsure whether it's much help or not. I'm posting it, anyway, partially so that I have it for my own reference. But feel very free to skip reading it.)

    OK, I think that what I said does align with the spec text, but all the credit there goes to the spec, because my mental model wasn't very well defined before I read it.

    The way part of me thinks of it is -- again, keeping in mind that the real checkers won't see Map this way because they'll have stubs -- that an unannotated Map class would effectively look like this to the checker:

    public interface Map<K extends @UnknownNullness Object, V extends @UnknownNullness Object> {
      @NullnessUnknown V put(@UnknownNullness K key, @UnknownNullness V value);
      ...
    }

    In other words, part of me thinks of "undefined nullness" as "pasted" not only onto each type variable bound but also onto each type parameter use. (I mean this in a way contrary to what the spec says, even though the spec says something sort of like this. But I endorse the spec; I am just explaining how I originally thought of this in case that somehow helps someonoe.) That would mean that, even if the spec didn't have its current specific rule that says to make every usage of K and V have unknown nullness (on account of their bound), then no matter what type Map is instantiated with, the return type and parameter types of put would have unknown nullness, thanks to the "pasted" @UnknownNullness on those type-parameter usages.

    I guess my thinking is as follows: In the extremely implausible event that Map.java were annotated as follows...

    @DefaultNotNull
    public interface Map<@UnknownNullness K, @UnknownNullness V> {
      @Nullable V put(K key, V value);
      ...
    }

    ...then it seems reasonable for put on a Map<@NotNull K, @NotNull V> to require @NotNull inputs. After all, the type usages are annotated (by the default annotation); the only uncertainty that we're declaring is over whether K and V should be permitted to be @NotNull or @Nullable in the first place. Checkers might well warn about that at the instantiation site, but once they've done that, they've done their job: They don't need to warn about usage sites, too.

    But, again: I do prefer the rules that the spec currently has. I think they work well in practice because they treat a completely unannotated type as if all its parameter and return types, whether they use type parameters or not, have unknown nullness. And that's what I really want, since it produces suppressible warnings for cases the checker is unsure about. If users want more than that, they should annotate the type directly or in stub files.

  7. kevinb9n commented on Aug 14, 2019

    @kevinb9n
    Collaborator

    Let's say there's a class Foo that's not annotated at all, ie., T's effective specifier is "unknown nullness":

    I disagree, and that's why I filed #62. I would really want to read T as unconstrained in this situation, not unspecified!
    Otherwise all collection types from the JRE, e.g., could only be instantiated with type arguments of unspecified nullness, which would block a lot of useful analysis.

    I think interpreting T as unconstrained very likely means that if we were analyzing that (e.g. JRE) class we would probably find violations. Since we're not analyzing that code and those violations aren't being reported, that means the problems they relate to might show up somewhere else.

    Well, surely parameterizing with a nullness-unspecified type argument should be safe and normal. But parameterizing with anything else seems like it should make you suppress a warning to indicate that you're aware of the risk. Of course, to the degree that's annoying, that's supposed to motivate users to bite the bullet and get/provide the right stub files, and that seems kinda working-as-intended to me at the moment.

  8. kevin1e100 commented on Aug 17, 2019

    @kevin1e100
    CollaboratorAuthor

    I suspect there's some kind of disconnect here, specifically around how a type parameter in a legacy file (i.e., a type parameter of "unknown nullness") is different from a known-parametric type parameter (here often referred to as a type parameter whose upper bound is a nullable type, but the idea is just a type parameter that where it is somehow (typically through some form of annotations) known that it can be instantiated with either a nullable or a non-null type, e.g., the type parameter of j.u.List<T>).

    The former will commonly appear in legacy .java files where no-one has take the time to provide any annotations; let's imagine a fictitious Legacy<T> class for that. The latter will commonly appear in .java files that have annotations, for instance, after someone annotated j.u.List, either externally or directly in the source file, so let's assume someone annotated List and we use that as an example of an interface with a known-parametric type parameter in the discussion below. Finally, let's assume someone also annotated j.u.Optional<T>, but (let's assume) its annotations limit T to instantiations to non-null types (which would make sense in this case I believe).

    Now what's the difference? I believe the desire in both cases is that they can be instantiated with type arguments of any nullability. That is, L<@NotNull String>, L<@Nullable String>, and L<@NullnessUnknown> should all be possible for both L = Legacy and L = List. Why? For List that's the explicit intent, and for Legacy, well, we don't know any better, so it should probably allowed (though one could consider generating warnings). (Conversely, only Optional<@NotNull String> should clearly be allowed, while Optional<@Nullable String> should probably result in some kind of "illegal type" error, and Optional<@NullnessUnknown String> also feels suspect if not outright wrong.)

    But on the other hand it feels like something is fishy about just instantiating Legacy<T> with anything. That's what @cpovirk referred to as "pretty scary" in the doc comment quoted above. The issue is that because Legacy hasn't been annotated, we don't know if any of the uses of its type variable are actually parametric with how T was instantiated. For instance, Legacy may define a method T getOrNull() that could always return null, even when called on a Legacy<@NotNull String>. It may define a method setOrClear(T) that could always accept null. Or it could have methods that never accept or return null in places where the type variable T is used.

    Because of that it's problematic and afaict not "typesafe" to just "paste" any type argument where T appears in Legacy's API. What I mean by that is, it's not safe to assume that a call x.getOrNull() on a variable declared Legacy<@NotNull String> x will return a non-null string, for instance. On the other hand, doing that for y.get(0) on List<@NotNull String> y is ok. (Similarly, btw, it's problematic / unsafe to let List just return null from get(int), since the type parameter allows non-null types. Conversely, in Legacy's method bodies we again don't really know what's ok and what isn't, though we probably won't run a checker over unannotated Legacy's implementation.)

    One way of dealing with this is to consider all uses of Legacy's type variable in Legacy's API as having "unknown nullness" regardless of how Legacy's type parameter is instantiated, which is what this issue was originally filed about. Doing that allows tools to raise warnings when dereferencing unknown nullness method results coming from Legacy, and to raise warnings when passing nullable values into Legacy method parameters. Conversely, with List, checkers should likely "paste" any type argument's nullness into any type variable use in List's method parameters or results (unless they were further annotated). And with Optional, its type variable uses can just be considered to represent non-null types (again unless further annotated).

    Nonetheless I want to emphasize that both known-parametric (here often call @Nullable-bounded) type parameters and type parameters "of unknown nullness" (typically appearing in unannotated legacy types) can be instantiated any which way, but at least for a sound checking tool it'll be important to nonetheless treat those instantiations differently: trust them when the type parameter is known parametric, but use "nullness unknown" everywhere if the type parameter itself is "of unknown nullness".

    One source of confusion here, and I'm still not sure I'm explaining all this very well, is that the term "unknown nullness" is decidedly ambiguous when used for type parameters since "unknown" could refer to a known-parametric type parameter, where at the declaration site we don't know whether it'll be instantiated with a nullable or non-null type. That is generally not what I have meant when I've talked about type parameters with unknown nullness. Instead I was referring to situations like Legacy as described above.

  9. stephan-herrmann commented on Aug 20, 2019

    @stephan-herrmann

    Much of what @kevin1e100 writes here, gives a nice motivation for #62 and I concur in many regards.

    What sounds strange to me is the proposal to (a) allow instantiating the legacy type parameter with any nullness, but (b) ignoring the instantiation in so far that references to that type variable are still seen as unspec'ed types. As a user who instantiates Legacy<@Nonnull String> I would feel cheated if that annotation has no positive effect. At least I expect some feedback whether I'm using this instantiated type in a consistent way, e.g., passing null to a parameter of type T should be flagged.

    I know this is a muddled area, and the question how to distinguish Legacy from List is a tough one. In my GenericsEclipsePOV essay I outlined the heuristics employed by Eclipse for deciding whether a T return type can be trusted to support the contract of a nonnull instantiation. It's not perfect but for this migration / legacy topic it helps to put the blame where it belongs without causing trouble in the core semantics.

  10. cpovirk commented on Aug 20, 2019

    @cpovirk
    Collaborator

    Thanks. I came here after reading your email and essay, but thanks for the points here, as well.

    In my original comment, I was concerned about the bad side of trusting Legacy<@NotNull String>: Checkers would assume that a String that comes out of the object is non-null (but more on that later). I had completely overlooked what you point out, which is that we can offer a good side: Checkers would force callers to put in only non-null strings. I can understand feeling cheated if this checking doesn't happen.

    (From that perspective, there's some sense in allowing even Legacy<@Nullable String>, which lets users opt in to stricter checking of values coming out of the object (but then also see looser checking of values put in). But as you point out in your email (which I'm still processing, along with your essay), we already have conflicting requirements for the hierarchy of nullnesses. Permitting Legacy<@Nullable String> for Legacy<T extends @UnknownNullness Object> would make things worse.)

    On the other hand, I still don't love the possibility that Legacy<@NotNull String> would usually effectively mean "Set T to @NotNull String, and also trust that no occurrences of T in the Legacy API should have had overriding nullness annotations." I think that part of what bothers me is the non-local-ness: A suppression on the declaration effectively affects the use sites. Another part may be that I usually expect a suppression to apply to an expression, not to a type. So I might see @SuppressWarnings("nullness") Legacy<@NotNull String> foo = client.getFoo(); and think that the problem is that client.getFoo() doesn't declare nullness, when in fact the problem is that Legacy doesn't declare nullness.

    I understand that Eclipse has heuristics to catch the problems this would otherwise create. I'm wondering if the way to go for both of us, though, is to embrace unknown nullness by getting in the habit of writing Legacy<@UnknownNullness String>. That will produce warnings in similar cases(?) to Eclipse. And I might not care too much what instantiations are possible (since we have enough difficultly already with the hierarchy of nullnesses), given that there's one that produces the behavior that I want.

    I guess my main remaining concern is whether Legacy<@NotNull String> (typically written as just Legacy<String>) will produce a noisy enough warning for me to notice it. I can imagine running in "lenient" mode (i.e., with most unknown-nullness warnings suppressed) a lot of the time, but the danger of interpreting Legacy<@NotNull String> as discussed a couple paragraphs ago feels somehow worse to me than a typical nullness warning. But does that really justify making it an error? (And would a suppressible error be better or worse?) Or maybe I just need to get over the idea that it's a "worse" kind of warning.

    [edit: a late remark on non-local-ness: Many suppressions of nullness warnings can create a NullPointerException later, so we could call those "non-local," too. (In that way, they're just like unchecked warnings.) I still see this case as sort of different, since it's effectively disabling what would otherwise be nullness warnings elsewhere in the code. But I grant that actual runtime effect is the same.]

  11. kevin1e100 commented on Aug 21, 2019

    @kevin1e100
    CollaboratorAuthor

    Just to clarify, my previous comment was mostly to say, in a lot of words, that there seem to be benefits from distinguishing "unknown" (aka unspecified,legacy,whatever) from known-parametric (and known-non-parametric) type parameters.

    One benefit of doing that is that it seemingly allows to more precisely define the heuristics that should be used for "unknown" type parameters, and when to use the heuristics. There's a strong desire to leave those heuristics up to individual checkers, but by defining which type usages (including uses of type variables) have "unknown" nullness we identify where those heuristics should (likely) apply. If a particular tool's heuristics include issuing warnings when a nullable string is passed into a Legacy<@NotNull String> method, and not warning when dereferencing method results coming from such a thing, that's fine as far as I'm concerned. (Though I believe it's not always "safe" to go by these particular heuristics, and they may be noisy sometimes, so some tools may not want to use them. kotlinc for instance uses a slightly different approach, as an example.)

    With that in mind I think it does make sense to assign "unknown" nullness to usages of type parameters which are themselves "unknown" (rather than known-parametric), though I struggle with this myself (see my initial description of this issue), and there could be other ways of achieving this. But I think the intuition is this: if we don't know anything about the type parameter then we probably also shouldn't blindly assume that usages of that type parameter in method parameter and return types are parametric (certainly doesn't seem safe to do so): any given use may be parametric (like List.get), but it seems like it can also always be nullable (like Map.get), or always non-null, and we just have no way of knowing that in a legacy class, unless I'm missing something. Conversely, if someone took the time to mark a type parameter as parametric (or non-parametric) then it seems reasonable to assume that they also went over the usages of that type parameter and annotated any occurrences that need it. In other words, once a type parameter is marked as parametric we can assume any usages to be parametric unless annotated, and it seems safe to do so.

  12. cpovirk commented on Oct 18, 2019

    @cpovirk
    Collaborator

    Copying over some discussion from #74, which I've closed, since it's about one specific case of the general rule discussed here. (Specifically, it's about the case that I hadn't thought of in my original comment quoted in the first post here.)

    In #74, I wrote:

    (Previously I gave an example predicated on using @NullnessUnspecified for Map.get. But there may be less support for that than I'd thought, and anyway, I think this is worth considering independent of that.)

    Any generic type that isn't annotated for nullness is likely to have a method that we consider to return @NullnessUnspecified T. For example[*]:

    class Supplier<T> {
      T get();
    }

    It seems pretty clear that, if I write Supplier<@Nullable String> (probably receiving a warning), I expect for get() to return a @Nullable String.

    But the design proposal currently has the following rule:

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

    So get() returns a @NullnessUnknown String. That's still pretty good, but I can still imagine that users would feel "cheated" here that we didn't respect the @Nullable annotation.

    The purpose of the current rule is, as I understand it, more about @NotNull. We don't want to assume that an unannotated method that returns T is meant to return exactly T as opposed to @Nullable T. (@Nullable T, incidentally, would be the correct return type for an almost identical-looking get() method, the one on java.lang.ref.Reference.)

    Maybe what we really want is a rule about picking the "most nullable" of the nullnesses that are "in play." The type parameter bound says "unspecified," but the instantiation says "nullable," so we go with nullable.

    However, such a rule makes sense only for unspecified nullness, not in general: If the type parameter bound says "nullable" but the instantiation says "not null," then we still want not null. We could have a special case for unspecified nullness (as arguably we already do), but it would feel nice for it to be less of a special case.

    This brings me back to an idea I mentioned once before (in the last paragraph of this post): What if, when determining the nullness of a type-variable usage, we didn't look at the bound at all? Then, to make unspecified nullness work the way we want it to again, we treat defaults as also applying to type-variable usages -- but only in combination with the type parameter that the class is instantiated with (by picking the "most nullable").

    (This better fits my mental model for parametric nullability in unannotated classes, and it also produces a better (IMO) result for incrementally annotating a type, as discussed in bullet 2 in a post I linked earlier.)

    I'm still not sure of the right way to communicate all this. I feel like it wouldn't be significantly more complex than the existing proposal once it's written in definition form. But people would need an intuitive feel for it, too, and I'm not sure I'm getting the intuitive model across.

    [*] edit: Originally I used Reference as my example throughout, rather than using Supplier at the beginning and switching to Reference briefly later, as I now do. The problem with using Reference at the beginning: I would probably annotate Reference as Reference<T [extends @NotNull Object>, forbidding Reference<@Nullable Object>. (The class can still support all callers because its constructor would accept a @Nullable T, and its get method would return a @Nullable T.)

  13. cpovirk commented on Oct 18, 2019

    @cpovirk
    Collaborator

    And @kevinb9n replied:

    Any generic type that isn't annotated for nullness is likely to have a method that we consider to return @NullnessUnspecified T. For example:
    class Reference<T> { T get(); }
    It seems pretty clear that, if I write Reference<@Nullable String> (probably receiving a warning), I
    expect for get() to return a @Nullable String.

    So far I agree: you probably do expect that, and you probably should get a warning, and the question of whether you will get what you expect or not after ignoring/suppressing that warning is probably unanswered. (I believe you should, because (a) look, you were warned, and (b) otherwise the rules for interacting with that reference are different depending on the foreign definition of Reference, and we don't like that.)

    But the design proposal currently has the following rule:

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

    So get() returns a @NullnessUnknown String.

    I believe this part of the spec is only talking about type usages of the type variable itself (which can only occur inside the scope of the Reference class). When analyzing that class itself, T would be seen as having unspecified nullness.

    Reference<@Nullable String> is a parameterization of Reference and has substituted away all occurrences of T, so it's our defined substitution rules that will govern what nullness the get() return type has. As argued above I think @Nullable should probably win.

    So let me pause there and ask you whether that changes the rest of what you want to say here.

  14. cpovirk commented on Oct 18, 2019

    @cpovirk
    Collaborator

    First of all, again, thanks. @kevin1e100 had already tried to explain this to me in the "pasting" model described above, but I had still been under the impression that there was a special case for @NullnessUnspecified, and I forgot to circle back here. But now I understand why @kevin1e100 "didn't anticipate" this application of the rule, which previously appeared to me to be exactly the intended application of said rule :)

    I would like to make the case that the spec is unclear on this:

    • I was confused by this even though I'd seen a long-ago Docs thread about parameteric nullability (resulting in the Box example). Possibly I was confused because I thought that discussion had focused on implementation code. But the concern indeed applies APIs, which is why the design proposal mentions parametric nullability where it does.
    • I may(?) have successfully confused @abreslav, who applied my rule in "Type variables with @NullnessUnknown bounds" in Checking and interpreting type instantiations wrt declared bounds #57. (Or maybe he just anticipated that this current thread was going to result in a change to the current design.)
    • I don't think the spec [edit: meaning specifically the draft design proposal doc] directly addresses this. The closest bit I see is, for starters, under Discussion: Expression Types, which suggests that it doesn't apply to APIs. (This is probably from our early optimism that few issues applied to APIs.) Additionally, while the example there clearly shows some substitution happening, the clearest reference in the text is probably the phrase "considering xs’s type argument."

    I should acknowledge that this behavior is in fact "obvious." But I think it's also obviously dangerous, as discussed in the first post here. Given that, when I saw a phrase in the doc that appeared to be solving the problem, I jumped on it.

    (Aside: In the long term, it may be useful for our docs to acknowledge the cases in which we've set rules that we recognize to be unsound.)

    We can try to make the doc clearer, but before we rush to do that, I want to make the case for different behavior (and also say another thing or two, to no one's surprise :))

  15. 34 remaining items

  16. cpovirk commented on Nov 8, 2019

    @cpovirk
    Collaborator

    An amendment to something I said before:

    I recently said that I was down on the idea of different rules for what @kevinb9n is considering calling "in-types" and "out-types".

    I still stand by that if I am more precise about it: The thing I'm down on is what we might call different "substitution" (and maybe "defaulting") rules for in-types vs. out-types.

    Very broadly speaking, though, I do expect for us to sometimes see "different behavior" for in-types and out-types. This behavior would arise naturally when, for example, we handle parametric nullability: Given a type parameter <T extends @Nullable Object>, we'd forbid dereferencing a parameter of type T (it might be null!), but we'd also forbid returning null from a method that returns T (it might not be null!). This is in some sense asymmetric: "Is T @Nullable or not?"

    But it's still symmetric in terms of substitution rules. That is, we'd still consider the type to be T in both cases: It's just that we're checking conversion rules in "the opposite direction": @Nullable isn't convertible to T, but neither is T convertible to @NotNull.

    (Similar logic may apply for unspecified nullness, but I haven't thought it through deeply.)

    So even though we see "different behavior" for in-types and out-types, it's not because we have different substitution rules for those types: It's just that, thanks to normal type-checking (and sometimes PECS), we sometimes check whether T is convertible to a given nullness, and we sometimes check the reverse. And for "in-between" types like parametric nullness, the two don't have the completely opposite behavior that we'd expect from a simpler system with only @NotNull and @Nullable.

    I think this is probably all reasonably well understood already, but my earlier comments may have been misleading. Plus, I'm still not 100% sure that I have expressed it right :)

  17. kevin1e100 commented on Jan 3, 2020

    @kevin1e100
    CollaboratorAuthor

    Two follow-ups to my previous comment that was trying to tease apart the concerns seemingly at work in "more nullable" concerns @cpovirk has raised on this thread (and elsewhere):

    1. since we're not pursuing default annotations on methods for the time being (Allow annotating null-markedness at method/constructor level? #43), partially annotated files don't seem to be as important ATM: either a class is defaulted/opted-in, or not, IIUC.

    2. experimenting with Kotlin a bit, Kotlin seems to always honor JSR305's @Nonnull, even when placed on a type variable usage (e.g., @Nonnull T foo() { return ... }). I'm not aware of any existing tool that would ignore @No[nt][Nn]ull anywhere, but I haven't explicitly tried other tools in preparation for this post. I still grant that there are (almost) no valid use cases for annotating type variable usages this way, but I do also really struggle to see the point of ignoring explicit @Nonnull annotations in this case, not least since that seems to be at odds with how existing annotations are treated: since, e.g., it would be a breaking change for Kotlin to start ignoring JSR @Nonnull, it seems extremely confusing to ask it to ignore another spelling of that annotation.

  18. kevinb9n commented on Jan 9, 2020

    @kevinb9n
    Collaborator

    I just attempted to read over the 37 screenfuls of chatter on this issue. It didn't go too well.

    I think our new goal should be to get this issue CLOSED, and replaced with a set of specific issues which ask specific answerable questions, and we need to try to keep the chatter on those issues on-topic somehow.

  19. cpovirk commented on Jan 9, 2020

    @cpovirk
    Collaborator

    Yeah, a set of specific issues is the aim of that doc of example code snippets that I have temporarily abandoned. Later, hopefully we can all look at the examples, get an idea of what behavior we'd like for each, and then come up with an overarching principle that makes that happen. Fun to look forward to in Q2 :)

  20. cpovirk commented on Jan 14, 2020

    @cpovirk
    Collaborator

    Kotlin seems to always honor JSR305's @Nonnull, even when placed on a type variable usage (e.g., @Nonnull T foo() { return ... }).... it would be a breaking change for Kotlin to start ignoring JSR @Nonnull, it seems extremely confusing to ask it to ignore another spelling of that annotation.

    Thanks, that is valuable information and a good point, much as I have advocated for the opposite behavior :(

    Furthermore, as I think I said somewhere or other, I acknowledge that people are likely to expect @NonNull T to mean "not null," even without Kotlin precedent.

    (This is part of the reason that I wish we could justify leaving @NonNull out entirely. But I grant that it may be too useful to people who are incrementally annotating a codebase, so I've backed off that somewhat.)

    My recent thinking has been to reimagine @NonNull as something like "@DefaultNullness." The "default nullness" for a type in annotated code is always going to be @NonNull -- except, notably, in case of type-variable usages, for which it can be parametric nullness. Ideally, users will apply the defaults to all types in their file by using the "in the club" annotation -- call it @ApplyNullnessDefaults.

    The name "@DefaultNullness" has the advantage that users are unlikely to apply it frivolously (as we have seen happen with @NonNull). After all, why would they want to explicitly specify the default?

    The only case in which users would explicit specify the default is when they haven't told the checker that it's safe to apply the default universally -- that is, code without @ApplyNullnessDefaults. (Yes, this means that it's not exactly "the default," since users have to opt it. It's "the default for code that is annotated" -- "a default," if you will.)

  21. cpovirk commented on Jan 14, 2020

    @cpovirk
    Collaborator

    it would be a breaking change for Kotlin to start ignoring JSR @Nonnull, it seems extremely confusing to ask it to ignore another spelling of that annotation.

    One other point: We should definitely expect some differences in behavior like this. After all, Kotlin hasn't fully implemented the rules that we're still in the process of defining :)

    For example, if we change the following code to use our annotations and our rules, then the Kotlin code (bottom) shouldn't compile against the Java code (top):

    package demo.java;
    
    import javax.annotation.ParametersAreNonnullByDefault;
    import org.checkerframework.checker.nullness.qual.Nullable;
    
    @ParametersAreNonnullByDefault
    public interface MySupplier<E> {
      static MySupplier<@Nullable String> makeSupplierOfNullable() {
        return () -> null;
      }
    
      E get();
    }
    package demo
    
    import demo.java.MySupplier.makeSupplierOfNullable
    
    fun main(args : Array<String>) { 
      makeSupplierOfNullable().get().length // should be an error
    }

    But currently it compiles:

    $ javac -cp checker-qual-2.8.1.jar:jsr305-3.0.2.jar MySupplier.java -d mylistout && ./kotlinc -d listofnullable.jar -cp mylistout:checker-qual-2.8.1.jar:jsr305-3.0.2.jar -Xjsr305=strict -jvm-target 1.8 UseSupplierOfNullable.kt && echo ok
    ok
    

    We can still seek to minimize such differences, of course. But some are inevitable, barring significant compromises.

  22. cpovirk commented on Jan 15, 2020

    @cpovirk
    Collaborator

    Sorry, another belated reply.

    1. since we're not pursuing default annotations on methods for the time being (Allow annotating null-markedness at method/constructor level? #43), partially annotated files don't seem to be as important ATM: either a class is defaulted/opted-in, or not, IIUC.

    Even without defaulting annotations, it's possible to have a partially annotated file. In particular, it's possible to write my original example, under which the file defaults to unspecified nullness but one particular type is annotated @NonNull.

    This is true even if there is no explicit @DefaultNullnessUnspecified annotation, since that's the default for a file without @DefaultNonNull.

    This is true even if we were to omit projection to @NonNull. If I'm reading the design proposal right, then I could tweak my example to:

    @DefaultNullnessUnspecified
    class MyMap<K, V extends @Nullable Object> {
      V get(Object key) { ... }
      ...
    }
    

    ...and our proposal would still assume that a Map<@NonNull String, @NonNull String> returns a @NonNull String from get.

  23. kevin1e100 commented on Jan 15, 2020

    @kevin1e100
    CollaboratorAuthor

    No argument that if individual methods can't have a default, it's still possible to "sprinkle" @Nullable / @NonNull into a file where the default is (implicitly or explicitly) @DefaultNullnessUnspecified. My intention indeed has been that annotating just a type parameter bound has the effect you mention. The idea behind that was that if someone annotates a bound, that annotation indicates a promise that they went through the type variable's usages and added annotations as needed to them as well, which I feel is consistent with the idea that type variable usages are not affected by the surrounding default.

    No question this is a weird case, and IMHO very much edge cases: it seems much preferable to also slap @DefaultNonNull on a class with an annotated type parameter bound, so I'm not particularly tied to a particular behavior here.

    Indeed Kotlin compatibility could be a consideration here, and I'd be curious to hear @abreslav's and other's perspective on that. But my suspicion is that Kotlin's behavior observed above comes from Kotlin currently completely ignoring type annotations in Java code if it's inside brackets. I'm saying that because it seems to treat MySupplier<@Nullable String> written in Java different from MySupplier<String?> written in Kotlin: the @Nullable is ignored while the ? is used, AFAICT, since the desired error is flagged when implementing makeSupplierOfNullable in Kotlin instead of Java. If existing annotations are completely ignored by Kotlin then to me it seems "our" annotations can induce any meaning we want, but again, I'd love to hear the Kotlin maintainers' perspective on that.

    While we're at it, the inverse case seems very confusing as well:

    @DefaultNonNull
    class MyMap<K, V extends @NullnessUnspecified Object> {
      V get(Object key) { ... }
    }
    ---
    MyMap<@NonNull String, @NonNull String> m =...
    m.get("foo") // do we want to consider m.get() to return non-null?
    

    "More nullable" rules here I believe interpret m.get's return value to be non-null (?), while the proposal in its current form assigns unspecified nullness I believe. Again the latter goes with the idea that annotating a type parameter bound says something about all unannotated type variable usages. To me this is also a very confusing case, and probably even more of an edge case, so again I'm not tied to a particular answer.

    Thinking about idea that there's a promise somewhere that type variable usages were inspected and annotated if needed, with "more nullable", @DefaultNonNull added to the class seems to serve that purpose not just for type variable usages but all type usages, which seems nice.

    The one I'm struggling with more is:

    @DefaultNullnessUnspecified
    class ImmutableMap<K, V extends @NonNull Object> {
      V get(Object key) { ... }
    }
    ---
    ImmutableMap<@NonNull String, @NonNull String> m =...
    m.get("foo") // do we want to consider m.get() to return non-null?
    

    Here I do feel it would be nice if we could know that m.get will return a non-null String. Again, clearly an edge case, so I'm not sure how much it's worth worrying about.

  24. cpovirk commented on Jan 15, 2020

    @cpovirk
    Collaborator

    (Your understanding of Kotlin's behavior matches what I'd been assuming. And I agree that it's tolerable for Kotlin to treat @codeanalysis.annotations.Nullable and @some.other.package.Nullable differently -- not ideal, but the necessary cost of handling nullness better.)

    "More nullable" rules here I believe interpret m.get's return value to be non-null (?)

    [edit: As @kevin1e100 notes below, I misread the example, so I got the following wrong:]

    The model I'm advocating for is a combination of "most nullable" and "apply the default to type-variable usages." As a result of that second point, the return type V gets interpreted as @NullnessUnspecified V. Then we pick the most nullable value from that and the argument @NonNull String, so we get unspecified nullness under my model, too.

    Here I do feel it would be nice if we could know that m.get will return a non-null String. Again, clearly an edge case, so I'm not sure how much it's worth worrying about.

    We don't want that, though, right? get() can return null if the key is not present.

    Of course your point stands if we use List.get instead. I think your model might produce non-null, whereas mine would say: "That V return type is in the scope of @DefaultNullnessUnspecified. Therefore, we don't know that the owner has annotated it properly. So we don't know if we're dealing with a Map.get-like case or a List.get-like case. Let's assume unspecified nullness."

  25. kevin1e100 commented on Jan 15, 2020

    @kevin1e100
    CollaboratorAuthor

    Err, yes, I was thinking of a List.get like situation where the method always returns a value. I guess your choice of Map.get was deliberate here, sorry for not catching on to that.

    The model I'm advocating for is a combination of "most nullable" and "apply the default to type-variable usages." As a result of that second point, the return type V gets interpreted as @NullnessUnspecified V. Then we pick the most nullable value from that and the argument @NonNull String, so we get unspecified nullness under my model, too.

    Really? That surprises me I guess. I hope we're talking about the same example (my mistake for including two in the previous comment). The way I thought you would reason this:

    • the default is @DefaultNonNull
    • the type argument is @NonNull String
    • (the type parameter is bounded by @NullnessUnspecified but I thought that didn't matter)

    Conversely, when using the bound:

    • the type argument is @NonNull String
    • the type variable is "assumed parametric"
    • (the default is @DefaultNonNull but that doesn't matter)

    Again I'm not sure I'm particularly invested one way or the other. I might argue that deriving from the type parameter seems convenient for sprinkling annotations, b/c I can annotate a type parameter bound knowing that this will only affect usages of that type variable. On the other hand it does feel like the default annotation is a better "signal" for indicating "I have thought about this whole file including type variable usages", than to derive that signal from default annotations and annotations on type parameter bounds.

    One consequence of "more nullable" is that type variable usages don't seem to have a nullability per se, unlike other type usages. Any thoughts on how that could be handled in the definition of "effective nullability specifiers"?

    it's tolerable for Kotlin to treat @codeanalysis.annotations.Nullable and @some.other.package.Nullable differently -- not ideal, but the necessary cost of handling nullness better.

    Maybe we're thinking the same thing, but AFAICT Kotlin does honor @Nullable declaration annotations including javax.annotation.Nullable. But it seems to ignore TYPE_USE annotations, in particular, checkerframework's.

  26. kevin1e100 commented on Jan 16, 2020

    @kevin1e100
    CollaboratorAuthor

    To @kevinb9n's point I created issues #89 and #90 to try and peel off some questions. I'm going to go ahead and close this issue (sic), having also created issue #91 for handling of annotations on type variables.

    I think it's fine to close this, modulo issue #91, because I believe we have figured out a number of important things:

    • Specifying parameterized types does matter, at least for specifying overriding, so this is not just an implementation code issue that we can leave to tools. It's also seemingly just better to give meaning to parameterized types, since they're part of APIs. Correspondingly, they're now explicitly discussed in the proposal doc.
    • This issue includes parameterized types referring to completely unannotated generic classes: Unannotated<@NonNull String> / Unannotated<@Nullable String>. Kotlin handles this case in a particular way that we've captured here, and we've found a way ("union type argument with @NullnessUnspecified") to specify that behavior. I feel it's critical we are consistent with Kotlin here, since we would otherwise prescribe something that conflicts with Kotlin's handling of completely unannotated generic classes, seemingly a commonly-enough case to create substantial friction.

    My point being, while there may be different ways of specifying what we need to happen here, I feel we have established what does need to happen. Even if there's disagreement, let's try to create new issues, ideally with smaller scope, to continue the discussion there.

  27. cpovirk commented on Jan 25, 2020

    @cpovirk
    Collaborator

    To close the loop: As I mentioned offline, I did indeed misread your first example. I agree that get would return @NonNull String in that example. That brings us back to the questions of what users would expect, how often this comes up, etc. I'm happy to continue discussing those questions on the other issues that you've opened. Thanks for splitting them off.

  28. added
    design
    on Mar 13, 2024
  29. 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