Skip to content

Consider making nullness fully "tri-state" instead of bi-state-with-some-files-unannotated #2

Closed

Description

@kevin1e100

@abreslav @kevinb9n one thing I've been wrestling with around nullness annotations is whether and how unannotated parameters and method results have their place.

First off, they do seem to have their place, e.g., in Map.get() it can be convenient to leave the result unannotated. That's also a good way to be compatible with more powerful checkers and additional annotations, such as checkerframework.org's type system around known map keys. It seems a similar issue comes up around checkerframework.org's @PolyNull, where we'd probably want to consider any @PolyNull parameters and method results unannotated.

If unannotated types have their place, though, then we have to make sure we accommodate that with defaulting annotations. For instance, @DefaultNotNull can't be placed on Map if we want to leave get's result unannotated. The user would have to instead use @DefaultNotNull on each Map method, or annotate every single type use in the interface explicitly, just so get's result can be unannotated.

Eclipse's annotations seem to have a way of getting around this: it's possible to un-default a method inside a non-null defaulted class, for instance.

Another option would be an explicit way of, well, annotating a given type use as unannotated, e.g., for Map (leaving aside whether Map is a good candidate for defaulting in the first place):

@DefaultNotNull
public interface Map<K extends @Nullable Object, V extends @Nullable Object> { ...
  public @Unannotated V get(K key);
}

While this doesn't look very elegant, it is appealing to allow considering annotations defined by more powerful checkers as effectively meaning "unannotated". For instance, @PolyNull could be interpreted as unannotated, e.g., by placing some marker annotation we define on @PolyNull's definition.

My strawman proposal here is:

  • Allow @DefaultNotNull on methods in addition to classes and packages
  • Add a boolean parameter or similar to allow "canceling out" @DefaultNotNull from a larger scope
  • Allow @DefaultNotNull(false) to be placed as a meta-annotation on other annotations. It could then be placed on @PolyNull or map-related annotations defined for more powerful checkers.

Thoughts?

Activity

  1. self-assigned this
    on Oct 19, 2018
  2. kevin1e100 commented on Oct 19, 2018

    @kevin1e100
    CollaboratorAuthor
  3. donnerpeter commented on Oct 20, 2018

    @donnerpeter
    Collaborator

    I'd vote against having to write false, that's not very readable without code insight. I'm also not sure of use cases for cancelling default in a smaller scope. I'd start with as little as possible, e.g. by having @UnknownNullability applicable to specific members or parameters. Scopes and meta annotations can be added later.

  4. kevin1e100 commented on Oct 22, 2018

    @kevin1e100
    CollaboratorAuthor

    My concern with something like @UnknownNullability is that it may not be very obvious how that's different from @Nullable, "without code insight" as you phrased it. But that offers another possibility:

    @Nullable(checked = false)

    for some attribute name, open to something better than "checked" (and using an enum instead of boolean). A nice benefit is that checkerframework.org can just ignore that attribute to be "sound". WDYT?

  5. abreslav commented on Oct 23, 2018

    @abreslav

    I agree that we need to support "unannotating".

    Regarding its syntactic form:

    • the word "unannotated" is obviously undesirable because annotations are an implementation detail here
    • @DefaultNotNull(false) misses the part where I want to emphasize that something is deliberately not annotated, even if I'm not using any defaults
    • @UnknownNullability looks OK-ish to me, but the fewer annotations the better, IMO
    • @Nullable(checked = false) looks even better, because it communicates the appealing intuition of "it's still nullable sometimes, but we won't be checking here"

    So, I'm for @kevin1e100 's latter proposal

  6. abreslav commented on Oct 23, 2018

    @abreslav

    As a sidenote: I'm not sure how important it is to be able to annotate things like @PolyNull to treat them as "not annotated". If we just ignore @PolyNull, we get the same effect, don't we?

  7. amaembo commented on Oct 24, 2018

    @amaembo
    Collaborator

    Having true/false is not very good idea, as it's not self-documented and not extensible. A separate annotation like @UnknownNullability looks fine, though, as @abreslav noted, if it's possible to reduce number of annotations, that's would be fine. The unannotated word is definitely wrong solution. Don't forget that we are not going to restrict to nullability. What if the same method has another property which should be annotated (e.g. @Immutable). Having @Immutable @Unannotated List<T> get() (might return null, but if List, then it's immutable) would be extremely confusing.

    Probably we may create an enum like this:

      enum OnDereference {
        WARN, IGNORE
      }
      
      @interface Nullable {
        OnDereference onDereference() default OnDereference.WARN;
      }

    And use:

    @Nullable(onDereference = OnDereference.IGNORE) T get() { ... }

    Note that this should be a rare case when it's necessary, so no need to make it very short. Probably this could be generalized:

      enum Report {
        FATAL, ERROR, WARNING, NONE
      }
      
      @interface Nullable {
        Report onViolation() default Report.WARNING;
      }
      
      @interface Immutable {
        Report onViolation() default Report.WARNING;
      }
    
      @Immutable(onViolation = Report.ERROR)
      @Nullable(onViolation = Report.NONE) 
      List<T> get() { .. }

    So the static analysis tools may use the reporting severity level to produce different categories of warnings or to filter them (e.g. displaying only severe problems first).

    Different severity is actually possible. E.g. File::list result should always be checked for null as it's outer world thing which cannot be controlled, so it could be annotated with higher severity level. OTOH something like ArrayDeque::poll returns null only when non-empty, so the dereference is not that severe as non-emptiness could be known before.

    Should we consider other sets of possible static properties? E.g. we may want to annotate return type mutability. Should we allow class-scope @Immutable annotation (all methods return immutable objects/collections)? Or create separate @DefaultImmutable? Should we provide a way to undefault it? Should we introduce @Mutable annotation and annotation which depicts @UnknownMutability? Probably instead of @DefaultImmutable, @DefaultNotNull we should write @Default(NotNull.class)?

  8. kevin1e100 commented on Oct 26, 2018

    @kevin1e100
    CollaboratorAuthor

    Re @PolyNull: Good point that we'd ignore it. My concern here was around hypothetical checkerframework users that want to make their APIs Kotlin friendly and want to use @DefaultNotNull. They'll have to do something like

    @DefaultNotNull
    public class SomeGiantApi {
    //...
      @Nullable(onDereference=IGNORE)
      @PolyNull
      public static String toNullableString(@Nullable(onDereference=IGNORE) @PolyNull Object o) {
        return o != null ? o.toString() : null;
      }
    }
    

    Nonetheless, I'm inclined to agree with previous comments that we can think about meta-annotation features to make, in this example, @PolyNull imply @Nullable(onDereference=IGNORE), later.

    Re @Nullable attribute, I like the Report enum. I believe kotlinc recently introduced a feature to warn instead of error on "recently introduced" nullness annotations? I think I like the more specific onDereference as the attribute name though instead of onViolation. WDYT?

  9. amaembo commented on Oct 26, 2018

    @amaembo
    Collaborator

    onDereference sounds fine, but sometimes it's technically not a dereference. E.g. notNullField = nullableField; is just an assignment, which is a type violation, but not dereference.

    Regarding PolyNull, to me it's quite questionable concept. In JetBrains we use a simple contract language to express such things. JetBrains way to annotate toNullableString would be:

      @Contract("null -> null; !null -> !null")
      public static String toNullableString(Object o) {
        return o != null ? o.toString() : null;
      }

    See https://www.jetbrains.com/help/idea/contract-annotations.html for details. I don't suggest to add it into our project as is, probably we can think up something better, but I suggest not to be eager to add Checkerframework-like PolyNull. Even our simple language allows much more. Soon we will be not satisfied by PolyNull and try to extend it creating a mess of unnecessary annotations.

  10. kevin1e100 commented on Oct 26, 2018

    @kevin1e100
    CollaboratorAuthor

    Ah fair point about assignments creating errors as well.

    I think I'm being confusing around @PolyNull. I'm not suggesting we include it; I'm using it as an example of an annotation one might also want to use besides the "core" ones we're trying to devise here. That concern comes up with @Contract just the same, I believe. Specifically, assuming kotlinc and other tools will ignore @Contract (and @PolyNull), methods annotated with such additional annotations still need to make sense without them. At the same time I think we want to be permissive and not interfere with the use of such additional annotations as much as possible.

    For @PolyNull in particular it appears that often-times one will want to leave @PolyNull types "unannotated" (that is, as "platform types" in Kotlin's terminology), but it could also make sense to use @Nullable. @Contract being more general probably requires case-by-case handling, so in the toNullableString example you'd just also want @Nullable(IGNORE) annotations on the method parameter and result (assuming it's defined in the scope of a @DefaultNotNull, otherwise it's fine as-is). Does that make sense?

  11. amaembo commented on Oct 27, 2018

    @amaembo
    Collaborator

    For @Contract sometimes it's reasonable to combine it with @Nullable (with warning). E.g. @Nullable @Contract("null -> null") which means that "if argument is null, then the result is definitely null, but if argument is not null, null still could be returned and shoud be checked". Though probably we could extend contract language to express this via contract clause itself...

  12. kevin1e100 commented on Oct 30, 2018

    @kevin1e100
    CollaboratorAuthor

    Makes sense, thanks!

  13. abreslav commented on Nov 6, 2018

    @abreslav

    @amaembo

    Having true/false is not very good idea, as it's not self-documented and not extensible.

    Looks like the attribute name is more or less self-documenting: @Nullable(checked = false)

    @Nullable(onDereference = OnDereference.IGNORE) T get() { ... }

    This looks to me like going a bit too low in terms of the level of abstraction: we give too specific instructions to the analyzer, i.e. "report a warning" or "ignore", while the actual tool might do other things. Compared to the checked = false proposal, I find this a bit too much, although I understand the concerns about extensibility and uniformity.

    So the static analysis tools may use the reporting severity level to produce different categories of warnings or to filter them (e.g. displaying only severe problems first).

    Same goes for this argument: analyzers have their own idea of what severities are, and perhaps we shouldn't go too specific when instructing them.

    Note that this should be a rare case when it's necessary, so no need to make it very short.

    I'm not 100% sure how rare it is. Would be nice to have some data. I'd guess for about 20% of the cases for popular (old) APIs. Is such data available?

    Should we consider other sets of possible static properties? E.g. we may want to annotate return type mutability.

    I'd suggest we create a separate issue for this

  14. abreslav commented on Nov 6, 2018

    @abreslav

    @kevin1e100

    Re @nullable attribute, I like the Report enum. I believe kotlinc recently introduced a feature to warn instead of error on "recently introduced" nullness annotations? I think I like the more specific onDereference as the attribute name though instead of onViolation. WDYT?

    This is something that slipped my mind. In the context of migration it may make sense to prescribe severities. Another option would be to capture the intent more directly, i.e. say something like "this is under migration" instead of "report a warning here".

  15. added
    nullness
    on Nov 26, 2018
  16. 8 remaining items

  17. JakeWharton commented on Feb 6, 2019

    @JakeWharton
    Collaborator

    For the Kotlin annotated version of android.jar we do intentionally retain platform unannotated types in order to avoid Kotlin/Checker/NullAway strict enforcement.

    1. Activity.findViewById(int) returns an un-annotated T.

      The general usage pattern here is

      setContentView(R.layout.foo);
      Button button = findViewById(R.id.send);

      A purists view of this function is as @Nullable because send might not be in the view tree created by inflating the foo layout. In practice, users are fine having this explode at runtime.

      We've tried to remedy this somewhat by adding Activity.requireViewById(int) which is annotated as @NonNull allowing the developer to communicate their intent with regard to optionality. There is no explicitly @Nullable version. Maybe in a few years we can make findViewById properly annotated.

    2. Context.getSystemService(Class<T>) returns an un-annotated T.

      The usage pattern is similar

      LayoutInflater inflater = context.getSystemService(LayoutInflater.class);
      FingerprintManager digits = context.getSystemService(FingerprintManager.class);

      Again, a purists view of this function is as @Nullable but for different reasons than the last time:

      1. Users can subclass Context, override getSystemService, and return null for anything.
      2. The only way to assert whether a feature is supported on some devices is if this function returns null.

      The problem is that services like LayoutInflater are guaranteed to exist everywhere (barring someone doing Decide final package name #1) but FingerprintManager is optional. There is no requireSystemService so for now we're stuck leaving it as a platform type.

    3. Fragment.getContext() returns an un-annotated Context (or it would have...)

      Fragments are managed objects which are sometimes user-instantiated and always subclassed. Inside of a fragment, because it's a managed object which is sometimes created by the system, all interaction happens in callbacks. Usage of getContext() looks like

      @Override public void onStart() {
        Something something = getContext().getSomething();
        // ...
      }

      By the time onStart is called, the system managing fragments will have set a Context allowing getContext() to return a non-null reference. However, if you do

      MyFragment fragment = new MyFragment();
      fragment.onStart();

      nothing has set the Context and so it will return null.

      The pure thing to do would be to annotate this as @Nullable because you can observe the method returning null and we eventually actually did this!. This, of course, annoyed users to no end, so we also added Fragment.requireContext() at the same time. In reality the original method should have thrown, but we cannot change that behavior.

      I'm including it in the list because it was one where some were in favor of leaving it unannotated. In fact, there's a version of Fragment in the Android framework where we probably would have left it un-annotated because adding requireContext() wouldn't have been available to our developers for years (until their minimum version was high enough). Thankfully the framework version is deprecated and we have an unbundled library version where we can properly annotate and offer a replacement method which everyone can use right away.

  18. amaembo commented on Feb 7, 2019

    @amaembo
    Collaborator

    As Java IDE developers we want to maximize the usefulness of static nullability analysis we provide with our IDE. We want to warn about possible nullability violation where the problem is "likely" and do not bother user with cases where nullability violation is "unlikely". There are certainly quite many methods in JDK as well as widely used libraries where null result is possible, but often controlled by user, so nullability violation warnings in these cases would be just noise. We cannot force our users to rewrite all the code properly beforehand, use more modern APIs, and turn on the analysis only after that. Producing many noise warnings reduces the usefulness of the analysis in general. So it's crucial for us to have the "unknown" state.

    More examples:

    • Object.toString() (also delegates: String.valueOf(Object), Objects.toString(Object)): sometimes implementations may return null. It doesn't mentioned in the contract whether the null return is prohibited, though it's definitely a bad practice. However sometimes people have to deal with poorly written code and face nulls returned from this method. If we annotate Object.toString() as @NotNull every comparison of result with null would be highlighted as "always false". If we annotate it as @Nullable, we would have many false-positives when it's immediately dereferenced, but developers are sure that their toString implementations are ok.

    • We tried to annotate Throwable.getCause() as @nullable only to get many noise warnings where it was immediately dereferenced (e.g. try { method.invoke(..) } catch(InvocationTargetException ex) { throw ex.getCause(); }): we know that invoke implementation always specifies non-null cause, but analyzer may not know this.

  19. sdeleuze commented on Feb 7, 2019

    @sdeleuze
    Collaborator

    We have use cases like ResourceLoader.getClassLoader() where the null value is possible, but not common and potentially impossible depending on the usage context, so we don't want to enforce checks in a mandatory way.

    We have use cases like HttpMethod.resolve() which is used to get an HttpMethod from it's String variant. It is safe in a lot of use cases where we would like not to enforce checks as well.

    We have implementations of @Nullable inherited methods that are nullable when initialized but will be non-null after the application context has been initialized like in DateTimeFormatterFactoryBean.getObject().

    There is also the case when the returned value will be null only when the input will be null like in TypeDescriptor.forObject.

  20. kevinb9n commented on Feb 8, 2019

    @kevinb9n
    Collaborator

    A few thoughts here.

    First, I think we can probably consider these three use cases separately and discover later whether they call for a common solution or not:

    1. The Object.toString()-like case. A return value that is only technically nullable; non-null being the uncontroversial best practice in all circumstances. It's ideal if we can just go ahead with @NotNull for this case; it's too close to a real @NotNull for the distinction to be interesting. The code overriding toString and returning null would then fail to compile IF it is using an appropriate nullness checker, and if it didn't do that, well, bad things are probably going to happen. (i.e., an unexpected NPE, and in fact even when you try to protect against that you will probably end up having to suppress a "redundant null check of @NotNull expression" warning!) Imho this is a case of "Doctor, it hurts when I do this"... I think we've discussed before that "soundness" isn't the right goal for this project, rather "soundiness" and this is probably a good example of that distinction mattering.

    2. The migration issue. I'd like to explore the idea of a single common annotation like @SuppressCallerWarnings(String...), which says to treat every call site of the annotated API as if it were surrounded by @SuppressWarnings(those same strings). With this ability then the API owner shouldn't have any reason to need to delay annotating. It's then important that users have some way to voluntarily opt-in to having those warnings appear anyway, and API owners should tell their users that they darn well ought to do that opting-in before $$DATE or else risk sudden breakage.

    3. The issue of "nullable only in $$circumstances" which we've had a lot of examples of above (thanks)! Actually, gotta come back to this topic later. <>

  21. amaembo commented on Feb 8, 2019

    @amaembo
    Collaborator

    Concerning @SuppressCallerWarnings(String...): sounds possible, but if we create this annotation in codeanalysis, we would need to specify the warning names in codeanalysis as well, so every particular checker would recognize and respect them. Also please note that there could be arbitrarily big amount of code between the call and the actual warning. E.g.:

    final String value = map.get(key); // assuming that Map::get is annotated with Nullable and SuppressCallerWarnings
    ... 100 lines of code...
    System.out.println(value.trim()); // checker would issue warning here: shall we go back to the var definition and respect that SuppressCallerWarnings?

    It could be even more complex, involving several intermediate variables or even interprocedural analysis.

  22. kevinb9n commented on Feb 8, 2019

    @kevinb9n
    Collaborator

    @amaembo Thanks for pointing this out - that seems to kill the idea of calling it "suppress caller warnings". What it's trying to get across is more like "don't use information gained from annotations on this method for actual enforcement (by default)". And if the API owner needs fine control over which information to treat this way, it may not be the suppression strings themselves we want to use. It could be {Nullable.class, MustUseReturnValue.class} perhaps.

    Still will come back and fill in #3 as soon as I can.

  23. wmdietlGC commented on Feb 18, 2019

    @wmdietlGC
    Collaborator

    I wrote up some thoughts in #27.

  24. kevinb9n commented on May 1, 2019

    @kevinb9n
    Collaborator

    So far, I am still trying to view the third state of nullability (besides "nullable" and "non-nullable") as being "legacy" -- only for code that hasn't adopted our new regime. (It will also get used as a general-purpose cop-out from time to time; I do want us to try to address those use cases (whatever they are) properly instead, but when all is said and done we are deliberately shooting for a lot less expressiveness than CF. So that will happen, but I still think that for now we are best off thinking about it as for the legacy use case only.)

    But even considering only the legacy use case, I have become convinced that we need the ability to default an entire (package/class) to @NotNull and UN-default an individual (class/method) back out - restoring it to the legacy status.

    Primary reason: if any package or class wants to migrate, but can't fully migrate yet, we really want them to be able to at least exist in the state where their NEW code is under the new model by default. That requires changing the default but backing out the problem spots.

    The next question then is whether it's also important to be able to restore "legacy" status at the level of one single type annotation. On that I don't know, but I suspect that we're okay to figure that part out later.

    Thoughts?

  25. abreslav commented on May 13, 2019

    @abreslav

    Primary reason: if any package or class wants to migrate, but can't fully migrate yet, we really want them to be able to at least exist in the state where their NEW code is under the new model by default. That requires changing the default but backing out the problem spots.

    I agree that this use case is very important, and the solution you describe seems very reasonable to me

  26. kevinb9n commented on Jun 19, 2019

    @kevinb9n
    Collaborator

    We are proceeding with the notion that all three kinds of nullability are on equal footing; all can be expressed via explicit type-use annotations and via default annotations.

  27. stephan-herrmann commented on Aug 2, 2019

    @stephan-herrmann

    I admit I didn't closely read all the comments here (and it seems, not all really relate to the subject line?), but if it is about un-annotating some code, then Eclipse does not need a dedicated annotation for this, it comes for free with the way how we define @NonNullByDefault, see my comment in #18.

    BTW, seeing @DefaultNotNull(false) in the initial description of this issue: We did use @NonNullByDefault(false) in the olden days, but that is superseded since 2014, the strict equivalent now would be @NonNullByDefault({}), i.e., apply the default to the empty set of locations.

  28. kevin1e100 commented on Aug 3, 2019

    @kevin1e100
    CollaboratorAuthor

    Right I was aware of Eclipse's (modern) approach when it comes to defaulting, though I didn't realize that Eclipse had previously done @DefaultNotNull(false/true). Because defaulting annotations are currently proposed parameterless, and because we ultimately decided to go with an explicit "tri-state" model, with defaulting possible for all three options, we're instead proposing @DefaultNullable and @DefaultNullnessUnknown (exact names TBD, see issue #32) as separate annotations besides @DefaultNotNull. Specifically, I believe @DefaultNullnessUnknown is meant to accomplish something pretty similar to @NonNullByDefault({}), IIUC.

    (Please note this issue is closed and was more about how to treat "unknown"; if possible let's use other issues to discuss defaulting unless you want to reopen this one.)

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

Labels

designnullness

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions