Repository navigation
Description
@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
@DefaultNotNullon methods in addition to classes and packages - Add a boolean parameter or similar to allow "canceling out"
@DefaultNotNullfrom a larger scope - Allow
@DefaultNotNull(false)to be placed as a meta-annotation on other annotations. It could then be placed on@PolyNullor map-related annotations defined for more powerful checkers.
Thoughts?
Activity
kevin1e100 commentedon Oct 19, 2018
@amaembo
donnerpeter commentedon Oct 20, 2018
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@UnknownNullabilityapplicable to specific members or parameters. Scopes and meta annotations can be added later.kevin1e100 commentedon Oct 22, 2018
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?
abreslav commentedon Oct 23, 2018
I agree that we need to support "unannotating".
Regarding its syntactic form:
@DefaultNotNull(false)misses the part where I want to emphasize that something is deliberately not annotated, even if I'm not using any defaults@UnknownNullabilitylooks 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
abreslav commentedon Oct 23, 2018
As a sidenote: I'm not sure how important it is to be able to annotate things like
@PolyNullto treat them as "not annotated". If we just ignore@PolyNull, we get the same effect, don't we?amaembo commentedon Oct 24, 2018
Having true/false is not very good idea, as it's not self-documented and not extensible. A separate annotation like
@UnknownNullabilitylooks fine, though, as @abreslav noted, if it's possible to reduce number of annotations, that's would be fine. Theunannotatedword 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
enumlike this:And use:
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:
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::listresult should always be checked fornullas it's outer world thing which cannot be controlled, so it could be annotated with higher severity level. OTOH something likeArrayDeque::pollreturns 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
@Immutableannotation (all methods return immutable objects/collections)? Or create separate@DefaultImmutable? Should we provide a way to undefault it? Should we introduce@Mutableannotation and annotation which depicts@UnknownMutability? Probably instead of@DefaultImmutable,@DefaultNotNullwe should write@Default(NotNull.class)?kevin1e100 commentedon Oct 26, 2018
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 likeNonetheless, I'm inclined to agree with previous comments that we can think about meta-annotation features to make, in this example,
@PolyNullimply@Nullable(onDereference=IGNORE), later.Re
@Nullableattribute, I like theReportenum. I believe kotlinc recently introduced a feature to warn instead of error on "recently introduced" nullness annotations? I think I like the more specificonDereferenceas the attribute name though instead ofonViolation. WDYT?amaembo commentedon Oct 26, 2018
onDereferencesounds 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 annotatetoNullableStringwould be: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 byPolyNulland try to extend it creating a mess of unnecessary annotations.kevin1e100 commentedon Oct 26, 2018
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@Contractjust 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
@PolyNullin particular it appears that often-times one will want to leave@PolyNulltypes "unannotated" (that is, as "platform types" in Kotlin's terminology), but it could also make sense to use@Nullable.@Contractbeing more general probably requires case-by-case handling, so in thetoNullableStringexample 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?amaembo commentedon Oct 27, 2018
For
@Contractsometimes 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...kevin1e100 commentedon Oct 30, 2018
Makes sense, thanks!
abreslav commentedon Nov 6, 2018
@amaembo
Looks like the attribute name is more or less self-documenting:
@Nullable(checked = false)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 = falseproposal, I find this a bit too much, although I understand the concerns about extensibility and uniformity.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.
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?
I'd suggest we create a separate issue for this
abreslav commentedon Nov 6, 2018
@kevin1e100
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".
8 remaining items
JakeWharton commentedon Feb 6, 2019
For the
Kotlinannotated version of android.jar we do intentionally retainplatformunannotated types in order to avoid Kotlin/Checker/NullAway strict enforcement.Activity.findViewById(int)returns an un-annotatedT.The general usage pattern here is
A purists view of this function is as
@Nullablebecausesendmight not be in the view tree created by inflating thefoolayout. 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@NonNullallowing the developer to communicate their intent with regard to optionality. There is no explicitly@Nullableversion. Maybe in a few years we can makefindViewByIdproperly annotated.Context.getSystemService(Class<T>)returns an un-annotatedT.The usage pattern is similar
Again, a purists view of this function is as
@Nullablebut for different reasons than the last time:Context, overridegetSystemService, and return null for anything.The problem is that services like
LayoutInflaterare guaranteed to exist everywhere (barring someone doing Decide final package name #1) butFingerprintManageris optional. There is norequireSystemServiceso for now we're stuck leaving it as a platform type.Fragment.getContext()returns an un-annotatedContext(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 likeBy the time
onStartis called, the system managing fragments will have set aContextallowinggetContext()to return a non-null reference. However, if you donothing has set the
Contextand so it will return null.The pure thing to do would be to annotate this as
@Nullablebecause you can observe the method returning null and we eventually actually did this!. This, of course, annoyed users to no end, so we also addedFragment.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
Fragmentin the Android framework where we probably would have left it un-annotated because addingrequireContext()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.amaembo commentedon Feb 7, 2019
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@NotNullevery 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.sdeleuze commentedon Feb 7, 2019
We have use cases like
ResourceLoader.getClassLoader()where thenullvalue 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 anHttpMethodfrom it'sStringvariant. It is safe in a lot of use cases where we would like not to enforce checks as well.We have implementations of
@Nullableinherited methods that are nullable when initialized but will be non-null after the application context has been initialized like inDateTimeFormatterFactoryBean.getObject().There is also the case when the returned value will be
nullonly when the input will benulllike in TypeDescriptor.forObject.kevinb9n commentedon Feb 8, 2019
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:
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.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.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. <>
amaembo commentedon Feb 8, 2019
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.:It could be even more complex, involving several intermediate variables or even interprocedural analysis.
kevinb9n commentedon Feb 8, 2019
@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.
wmdietlGC commentedon Feb 18, 2019
I wrote up some thoughts in #27.
kevinb9n commentedon May 1, 2019
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?
abreslav commentedon May 13, 2019
I agree that this use case is very important, and the solution you describe seems very reasonable to me
kevinb9n commentedon Jun 19, 2019
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.
stephan-herrmann commentedon Aug 2, 2019
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.kevin1e100 commentedon Aug 3, 2019
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@DefaultNullableand@DefaultNullnessUnknown(exact names TBD, see issue #32) as separate annotations besides@DefaultNotNull. Specifically, I believe@DefaultNullnessUnknownis 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.)