You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow annotating null-markedness at method/constructor level? #43
It's possible we don't need to. It also has drawbacks, such as when you compare two signatures that look similar without realizing they're very different.
AFAIU signatures in one class may not differ by nullability only, not even in Kotlin. Or do you mean signatures in different classes? Then those can be different due to different class-level defaults.
By "similar" I don't mean "exactly the same" -- suppose they have different names. Suppose I see two methods listed in my IDE index like
foo(Bar a, @Nullable Bar b)
baz(Qux c, @NullnessUnknown Qux d)
When I see that, I think "Probably this is a @DefaultNotNull class, so a and c are @NotNull", or something like that, but I probably don't think about the possibility that the two methods are operating under different defaults.
[EDIT: this may not really constitute an argument against the feature; just part of our advice to users why the feature shouldn't be overused.]
Thanks for the clarification! Those signatures can still reside in different classes with the same effect, although probably that wouldn't happen often.
I wouldn't add method-level defaults until we have a demand for that.
I think the use-case we had in mind for method/constructor-level defaults is classes that can be mostly migrated, but have a few methods that need to remain @NullnessUnknown.
Having method/constructor-level defaults requires only a single annotation on those method declarations, instead of having to make sure all parameters/return types (and all type arguments, etc.) are annotated as @NullnessUnknown.
Regarding IDE representations: I would imagine settings to highlight what defaults have been applied and what the effective nullness annotations are. So hopefully this isn't a big concern.
But if we're no longer concerned with this migration use case, I'm fine with leaving out method-level defaults until users request them.
I think I'm the one that got Kevin to file this bug. I think I'm pretty well convinced by the arguments here. Probably much of my concern was that people would apply @DefaultNullable as a "convenience," which I think would be misguided. But @DefaultNullnessUnknown makes more sense, and my concerns about @DefaultNullable aren't specific to per-method usage, anyway.
Now having an object sub of type Sub I see completion options in my IDE like sub.foo(Object) and sub.bar(Object). I can quickly check method JavaDoc or definition, but unless it's explicitly mentioned in the JavaDoc this doesn't give me a clue about an effective nullability. On the other hand, this could be solved on the IDE level: IDE authors may add new features to display somehow an effective nullability.
I consider this question to be back on the table. After we get a revised/improved requirement about incrementality/adoptability I will come argue why I think we might need method/constructor-level defaults at least. We would still persuade users to really try not to leave things that way but use it as a temporary stepping stone only (in full knowledge that the advice won't always be heeded).
Random point that shouldn't weigh too heavily here (and which I may have made previously somewhere?):
In domains other than nullness, we are likely to have annotations that apply at both the class scope and the method scope. So there could be a tiny argument for supporting that here for "consistency."
One example is @MustUseResult. However, that example is somewhat different: @MustUseResult is (arguably?) an intrinsically per-method concept, not a per-type concept. At the very least, there's no other annotation that it goes along with. (Contrast with @NullExplicit, which goes along with @Nullable.) So maybe consistency between @MustUseResult and @NullExplicit would actually be misleading.
Very minor point in either case -- just trying to get it out of my head.
I should point out that, our adoptability requirements notwithstanding, supporting partially annotated files is out of scope for 0.1, so we shouldn't worry about this issue right now.
Then Java will effectively "paste" @DefaultNonNull onto the field, getter method, and parameter of the constructor it generates -- or rather, all of those locations where it is permitted. So:
Suppose that we forbid defaults on methods. Then surely we'll forbid them on fields and parameters, too. That would make @DefaultNonNull useless on records. (Hopefully javac would outright forbid it, but I haven't confirmed.) But it's consistent (which is good), in contrast to...
Suppose that we allow defaults on methods but not fields or parameters. Then Java will definitely allow the annotation on components in the record header, and it will:
copy it to getters: That's presumably as intended.
not copy it to fields: That's presumably "wrong" but fairly harmless: The fields are private fields, and there is not any source code that directly accesses those fields, so checkers aren't likely to care about the annotations. (I'm not even sure yet if javac generates getter-implementation bytecode at compile time (which a bytecode-analyzing tool could theoretically look at -- though it could easily exclude such generated code) or if it's all done at runtime with invokedynamic or similar. [edit: It's invokedynamic.])
not copy it to the constructor parameter: That's presumably wrong, and it matters: If I thought that I was making Bar non-nullable in my example above, I turn out to be wrong. Worse, the getter says that it's non-nullable, but it's a lie!
(Note that record authors can manually declare the getters or constructors themselves, specifying the appropriate annotations. And they can probably just annotate the whole record at once already -- especially since records will appear only in newer code, which we can hope is more likely to get annotated for nullness than legacy code is. So I am probably making too much of a minor issue that arises only if users do something highly weird.)
I still think it's reasonable for this not to be our top priority, but another quick thought:
Even if we wanted to tell users "Don't expose a half-annotated class to users," I think that method-level defaults could be useful: When I go to annotate a legacy type, it could be nice to be able to annotate a single method or two, deal with the fallout, and then repeat until the whole class is done. Then I would switch to a class-level annotation before submitting my change. This iterative process is probably less intimidating -- and maybe even easier, since I can easily pick out all errors related to a given getFoo() method to address together.
I had observed in #50 (comment) that bytecode doesn't always fully distinguish between what's done by a field initializer and what's done by a constructor. We avoided the important part of that problem by rejecting @NullMarked on fields, but we're still theoretically vulnerable to part of it by permitting @NullMarked on constructors [edit: and methods].
Fortunately, constructors [and methods] present much less of a problem: Basically any class defined inside a constructor [or method] produces bytecode that identifies it as "enclosed by" that constructor [or method]. Thus, tools that are looking at that class will know to consult the annotations on the constructor [or method]. (Presumably the same would hold true if Java were to permit methods defined directly inside constructors/methods in the future.)
(This is different than the situation with fields: If we see an anonymous class with no enclosing method/constructor, then we probably(?) know that it's defined either in a static (clinit) block or in the initializer of some field, but we don't know which of those it is, and we certainly don't know which field. Thus, we wouldn't know how to react if a class had a clinit method or if only some fields in a class were null-marked. [edit: Oh, and Java offers instance initializers { ... }, too. I forgot about them.])
But wait, not every class defined inside a constructor [or method] produces the bytecode we want:
new Object() {} is quite clearly enclosed by the EnclosingInLambda constructor as far as the syntax tree goes. But its bytecode (and thus the java.lang.reflect API) disagrees. [edit: Granted, you could guess that it's enclosed by the constructor on account of the $new in the name... I think? Still, that's only a guess, and it wouldn't help in case of classes with multiple constructors or multiple methods of the same name (i.e., overloads).] So, in theory, a tool that tried to analyze any APIs (or implementation code) declared inside that anonymous class could behave differently based on whether it operated on source code or bytecode.
Fortunately again, this feels like a theoretical problem, unlikely to bite anyone for a very, very long time and unlikely to be a significant problem even when it does.
OK, so the other thought I had here, which is even less important, is that that bytecode for "pure implementation code" doesn't offer us a way to know whether it comes from source code inside a constructor or source code inside an initializer (whether a field initializer or an instance initializer).
Again, this seems much, much, much less likely to matter. Like, is a tool that consumes bytecode really going to differentiate between a Foo[] local variable declared inside a @NullMarked constructor ("an array of non-nullable Foo") a Foo[] local variable declared inside a non-@NullMarked instance initializer ("an array of unspecified-nullness Foo")?
So I'm noting this for completeness and to get it out of my head.
As another data point in support of allowing @NullUnmarked at the method / constructor level, the NullAway Annotator tool automatically inserts @NullUnmarked at the narrowest scope that removes errors it cannot automatically resolve. We chose to insert @NullUnmarked at the method / constructor level whenever possible, so that the rest of the code in the containing class still gets checked by NullAway (which makes future changes to that other code safer).
The current, working decision, as of 2022-05-16, is that @NullUnmarked and @NullMarked are applicable to methods and constructors.
This issue must be finalized before the release of version 1.0 of the annotation JAR.
None of the discussion above has made a strong case for changing that decision, as far as I can tell.
I propose this decision be finalized for 1.0. If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.
Results: Six 👍; no other votemoji.
Reacted by Chris Povirk, Manu Sridharan, David P. Baker, Kevin Bourrillion, Werner Dietl and Lázaro Clapp
changed the title [-]Allow annotating null-markedness at method/constructor level? [working decision: yes for both directions][/-][+]Allow annotating null-markedness at method/constructor level?[/+]on May 21, 2024
Activity
donnerpeter commentedon Jul 2, 2019
AFAIU signatures in one class may not differ by nullability only, not even in Kotlin. Or do you mean signatures in different classes? Then those can be different due to different class-level defaults.
kevinb9n commentedon Jul 2, 2019
By "similar" I don't mean "exactly the same" -- suppose they have different names. Suppose I see two methods listed in my IDE index like
When I see that, I think "Probably this is a @DefaultNotNull class, so a and c are @NotNull", or something like that, but I probably don't think about the possibility that the two methods are operating under different defaults.
[EDIT: this may not really constitute an argument against the feature; just part of our advice to users why the feature shouldn't be overused.]
donnerpeter commentedon Jul 3, 2019
Thanks for the clarification! Those signatures can still reside in different classes with the same effect, although probably that wouldn't happen often.
I wouldn't add method-level defaults until we have a demand for that.
wmdietlGC commentedon Jul 12, 2019
I think the use-case we had in mind for method/constructor-level defaults is classes that can be mostly migrated, but have a few methods that need to remain
@NullnessUnknown.Having method/constructor-level defaults requires only a single annotation on those method declarations, instead of having to make sure all parameters/return types (and all type arguments, etc.) are annotated as
@NullnessUnknown.Regarding IDE representations: I would imagine settings to highlight what defaults have been applied and what the effective nullness annotations are. So hopefully this isn't a big concern.
But if we're no longer concerned with this migration use case, I'm fine with leaving out method-level defaults until users request them.
cpovirk commentedon Jul 15, 2019
I think I'm the one that got Kevin to file this bug. I think I'm pretty well convinced by the arguments here. Probably much of my concern was that people would apply
@DefaultNullableas a "convenience," which I think would be misguided. But@DefaultNullnessUnknownmakes more sense, and my concerns about@DefaultNullablearen't specific to per-method usage, anyway.amaembo commentedon Jul 23, 2019
Here's the case where such annotation could be desired (though, again, not necessary). Consider the following
java.util.Mapmethod:All args and return value are not-nullable. We can annotate it either
Or simply
Again, this is an extreme case and adding 21 explicit NotNulls is not a really big problem.
If we have method-level
@DefaultNullable, will it affect only the method itself or the overriding methods in subclasses as well?By the way, I may have two methods defined in different classes within the hierarchy with different nullability defaults. E.g.:
Now having an object
subof typeSubI see completion options in my IDE likesub.foo(Object)andsub.bar(Object). I can quickly check method JavaDoc or definition, but unless it's explicitly mentioned in the JavaDoc this doesn't give me a clue about an effective nullability. On the other hand, this could be solved on the IDE level: IDE authors may add new features to display somehow an effective nullability.kevinb9n commentedon Aug 19, 2019
It is probably easier to not allow this for now and consider it later (as evidence demands) than vice-versa.
kevinb9n commentedon May 14, 2020
I consider this question to be back on the table. After we get a revised/improved requirement about incrementality/adoptability I will come argue why I think we might need method/constructor-level defaults at least. We would still persuade users to really try not to leave things that way but use it as a temporary stepping stone only (in full knowledge that the advice won't always be heeded).
cpovirk commentedon May 14, 2020
Random point that shouldn't weigh too heavily here (and which I may have made previously somewhere?):
In domains other than nullness, we are likely to have annotations that apply at both the class scope and the method scope. So there could be a tiny argument for supporting that here for "consistency."
One example is
@MustUseResult. However, that example is somewhat different:@MustUseResultis (arguably?) an intrinsically per-method concept, not a per-type concept. At the very least, there's no other annotation that it goes along with. (Contrast with@NullExplicit, which goes along with@Nullable.) So maybe consistency between@MustUseResultand@NullExplicitwould actually be misleading.Very minor point in either case -- just trying to get it out of my head.
kevinb9n commentedon May 28, 2020
I should point out that, our adoptability requirements notwithstanding, supporting partially annotated files is out of scope for 0.1, so we shouldn't worry about this issue right now.
cpovirk commentedon Sep 28, 2020
By coincidence, I just learned about annotations on Java's forthcoming "records." The impact on our defaulting annotations looks "interesting"....
It sounds like records will let you write:
Then Java will effectively "paste"
@DefaultNonNullonto the field, getter method, and parameter of the constructor it generates -- or rather, all of those locations where it is permitted. So:Suppose that we forbid defaults on methods. Then surely we'll forbid them on fields and parameters, too. That would make
@DefaultNonNulluseless on records. (Hopefully javac would outright forbid it, but I haven't confirmed.) But it's consistent (which is good), in contrast to...Suppose that we allow defaults on methods but not fields or parameters. Then Java will definitely allow the annotation on components in the record header, and it will:
privatefields, and there is not any source code that directly accesses those fields, so checkers aren't likely to care about the annotations. (I'm not even sure yet if javac generates getter-implementation bytecode at compile time (which a bytecode-analyzing tool could theoretically look at -- though it could easily exclude such generated code) or if it's all done at runtime withinvokedynamicor similar. [edit: It'sinvokedynamic.])Barnon-nullable in my example above, I turn out to be wrong. Worse, the getter says that it's non-nullable, but it's a lie!Suppose that we allow defaults on methods and parameters (Even smaller scopes for defaulting annotations: PARAMETER and TYPE_PARAMETER #128) -- and let's set aside fields, which are less interesting, as discussed above. Then Java will copy the annotation to the constructor parameter, as well. This makes the getter and the constructor parameter consistent, but it opens up the potential confusion discussed in Even smaller scopes for defaulting annotations: PARAMETER and TYPE_PARAMETER #128.
I would be sad to leave off method-level defaults, but records now have me thinking twice....
[edit: I was probably overreacting. See next post.]
cpovirk commentedon Sep 28, 2020
(Note that record authors can manually declare the getters or constructors themselves, specifying the appropriate annotations. And they can probably just annotate the whole record at once already -- especially since records will appear only in newer code, which we can hope is more likely to get annotated for nullness than legacy code is. So I am probably making too much of a minor issue that arises only if users do something highly weird.)
cpovirk commentedon Oct 5, 2020
I still think it's reasonable for this not to be our top priority, but another quick thought:
Even if we wanted to tell users "Don't expose a half-annotated class to users," I think that method-level defaults could be useful: When I go to annotate a legacy type, it could be nice to be able to annotate a single method or two, deal with the fallout, and then repeat until the whole class is done. Then I would switch to a class-level annotation before submitting my change. This iterative process is probably less intimidating -- and maybe even easier, since I can easily pick out all errors related to a given
getFoo()method to address together.16 remaining items
cpovirk commentedon Jul 11, 2022
I had observed in #50 (comment) that bytecode doesn't always fully distinguish between what's done by a field initializer and what's done by a constructor. We avoided the important part of that problem by rejecting
@NullMarkedon fields, but we're still theoretically vulnerable to part of it by permitting@NullMarkedon constructors [edit: and methods].Fortunately, constructors [and methods] present much less of a problem: Basically any class defined inside a constructor [or method] produces bytecode that identifies it as "enclosed by" that constructor [or method]. Thus, tools that are looking at that class will know to consult the annotations on the constructor [or method]. (Presumably the same would hold true if Java were to permit methods defined directly inside constructors/methods in the future.)
(This is different than the situation with fields: If we see an anonymous class with no enclosing method/constructor, then we probably(?) know that it's defined either in a
static(clinit) block or in the initializer of some field, but we don't know which of those it is, and we certainly don't know which field. Thus, we wouldn't know how to react if a class had aclinitmethod or if only some fields in a class were null-marked. [edit: Oh, and Java offers instance initializers{ ... }, too. I forgot about them.])But wait, not every class defined inside a constructor [or method] produces the bytecode we want:
new Object() {}is quite clearly enclosed by theEnclosingInLambdaconstructor as far as the syntax tree goes. But its bytecode (and thus thejava.lang.reflectAPI) disagrees. [edit: Granted, you could guess that it's enclosed by the constructor on account of the$newin the name... I think? Still, that's only a guess, and it wouldn't help in case of classes with multiple constructors or multiple methods of the same name (i.e., overloads).] So, in theory, a tool that tried to analyze any APIs (or implementation code) declared inside that anonymous class could behave differently based on whether it operated on source code or bytecode.Fortunately again, this feels like a theoretical problem, unlikely to bite anyone for a very, very long time and unlikely to be a significant problem even when it does.
cpovirk commentedon Jul 12, 2022
Oh, cool, that got fixed:
See JDK-8215470.
cpovirk commentedon Jul 12, 2022
OK, so the other thought I had here, which is even less important, is that that bytecode for "pure implementation code" doesn't offer us a way to know whether it comes from source code inside a constructor or source code inside an initializer (whether a field initializer or an instance initializer).
Again, this seems much, much, much less likely to matter. Like, is a tool that consumes bytecode really going to differentiate between a
Foo[]local variable declared inside a@NullMarkedconstructor ("an array of non-nullableFoo") aFoo[]local variable declared inside a non-@NullMarkedinstance initializer ("an array of unspecified-nullnessFoo")?So I'm noting this for completeness and to get it out of my head.
Add `METHOD` and `CONSTRUCTOR` targets to `@NullMarked`.
Add new potential annotations and update existing ones (#256)
msridhar commentedon Sep 28, 2022
As another data point in support of allowing
@NullUnmarkedat the method / constructor level, the NullAway Annotator tool automatically inserts@NullUnmarkedat the narrowest scope that removes errors it cannot automatically resolve. We chose to insert@NullUnmarkedat the method / constructor level whenever possible, so that the rest of the code in the containing class still gets checked by NullAway (which makes future changes to that other code safer).kevinb9n commentedon Sep 28, 2022
Very good to know that this looks like a valuable escape valve during adoption.
netdpb commentedon Apr 8, 2024
The current, working decision, as of 2022-05-16, is that
@NullUnmarkedand@NullMarkedare applicable to methods and constructors.This issue must be finalized before the release of version 1.0 of the annotation JAR.
None of the discussion above has made a strong case for changing that decision, as far as I can tell.
I propose this decision be finalized for 1.0. If you agree, please add a thumbs-up emoji (👍) to this comment. If you disagree, please add a thumbs-down emoji (👎) to this comment and briefly explain your disagreement. Please only add a thumbs-down if you feel you can make a strong case why this decision will be materially worse for users or tool providers than an alternative.
Results: Six 👍; no other votemoji.
netdpb commentedon May 21, 2024
Decision:
@NullUnmarkedand@NullMarkedare applicable to methods and constructors.[-]Allow annotating null-markedness at method/constructor level? [working decision: yes for both directions][/-][+]Allow annotating null-markedness at method/constructor level?[/+]