Repository navigation
Description
With projects like Spring, Micrometer and many others starting to leverage JSpecify combined with a nullness checker, there is a very popular ask (both from Spring commiters and from community members) that we need parameter contracts to be able to achieve 0 checker errors (green build) without too much annotations like @SupressWarnings("NullAway"). The scope of JSpecify 1.0.0 does not allow to reach that IMO reasonable goal, leading to the proliferation of multiple variants of @Contract (JetBrains one, Spring one) annotation + requiring special support in the various checkers. This is not ideal.
Method level @Contract leverages its own expression language, and my understanding is that a majority of members of the JSpecify working group (including me) want to avoid such expression language. I tend to think we could replace the method level @Contract annotation with an expression language by a parameter level annotation with enums. It would cover the majority of the use cases, even if not 100%.
I am wondering if it could make sense for JSpecify to introduce a new annotation like @ParameterContract (name to be refined, hopefully with a shorter one), with no retention at runtime, defined as follow:
@Documented
@Target(ElementType.PARAMETER)
public @interface ParameterContract {
Condition when();
Effect then();
}
public enum Condition {
NONE,
IS_TRUE,
IS_FALSE,
IS_NULL,
IS_NON_NULL
}
public enum Effect {
RETURN_TRUE,
RETURN_FALSE,
RETURN_NULL,
RETURN_NON_NULL,
RETURN_SAME_NULLNESS,
FAIL
}So
@Contract("null -> false")
public static boolean hasLength(@Nullable String str) {
return (str != null && !str.isEmpty());
}Would translate to:
public static boolean hasLength(@Nullable @ParameterContract(when = IS_NULL, then = RETURN_FALSE) String str) {
return (str != null && !str.isEmpty());
}I made the exercise with https://github.com/spring-projects/spring-framework to see how far we could go with @ParameterContract, and it seems to cover 97.5% of our use cases which is IMO pretty good. We could live with a couple of remaining @SupressWarnings("NullAway") for the few remaining unsupported use case.
In details:
- 32x
@Contract("null -> false")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_FALSE) - 13x
@Contract("null -> null")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_NULL) - 12x
@Contract("null, _ -> fail") -> @ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL) - 8x
@Contract("null -> null; !null -> !null")->@ParameterContract(when = Condition.NONE, then = Effect.RETURN_SAME_NULLNESS) - 6x
@Contract("null, _ -> false; _, null -> false")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_FALSE) - 5x
@Contract("_, null -> fail")->@ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL) - 5x
@Contract("null -> true")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_TRUE) - 5x
@Contract("null, _ -> false")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_FALSE) - 4x
@Contract("_, null -> false")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_FALSE) - 4x
@Contract("_, null, _ -> fail")->@ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL) - 4x
@Contract("false, _ -> fail")->@ParameterContract(when = Condition.IS_FALSE, then = Effect.FAIL) - 3x
@Contract("_ -> fail")->@ParameterContract(when = Condition.NONE, then = Effect.FAIL) - 2x
@Contract("!null, _ -> fail")->@ParameterContract(when = Condition.IS_NON_NULL, then = Effect.FAIL) - 2x
@Contract("null -> fail")->@ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL) - 2x
@Contract("null, _ -> param2; _, null -> param1") -> Not covered (no support for returning parameter values) - 1x
@Contract("_, !null -> fail")->@ParameterContract(when = Condition.IS_NON_NULL, then = Effect.FAIL) - 1x
@Contract("_, false -> fail")->@ParameterContract(when = Condition.IS_FALSE, then = Effect.FAIL) - 1x
@Contract("_, null -> true")->@ParameterContract(when = Condition.IS_NULL, then = Effect.TRUE) - 1x
@Contract("_, null -> true; null, _ -> false")->@ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL) - 1x
@Contract("_, null, _ -> fail; _, _, null -> fail")->@ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL) - 1x
@Contract("_, null, null -> fail") -> Not covered (no support for contract with conditions involving multiple parameters) - 1x
@Contract("_, true -> fail")->@ParameterContract(when = Value.TRUE, then = Effect.FAIL) - 1x
@Contract("null, _ -> false; _, null -> false;")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_FALSE) - 1x
@Contract("null, _ -> null")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_NULL) - 1x
@Contract("null, _ -> null; _, null -> null")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_NULL) - 1x
@Contract("null, _ -> true")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_TRUE) - 1x
@Contract("null, _, _ -> null")->@ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_NULL)
Any thoughts?
Activity
wakingrufus commentedon Aug 13, 2025
Is this meant to also conver contracts like
-> newand-> this? Or just null-related contracts?agentgt commentedon Aug 13, 2025
The challenging part is not the DSL. It would be trivial to write such a parser and even have that as some stand alone library that everyone could use.
The challenging part is that this a lot of this basically an extension of
@PolyNulland at the moment despite the name JSpecify is mostly about "types" and not "contracts" aka extension of the type system instead of static design by contract (there is a subtle complicated difference). PolyNull is very difficult to represent in a type system without a bunch of weird rules and the rest of the rules are like a dependent type system.Now I'm not positive but I think it is going to be very difficult to have PolyNull methods in a Valhalla future that work like PolyNull. Solid chance they are nullable return always. That is my concern is the contracts could indeed conflict with Valhalla typing.
The question is should the scope be increased instead of say a new project? I realize Spring is a big player and so is IntelliJ but I get concerned based on a long history of working with Java where big players in a committee have sway for their needs while completely forgetting the little guys that need to implement. They also often create barrier such that they are the only ones to offer a solution. I'm sure you have seen this with the ancient JSRs. Are we going to end up with the case of IntelliJ being the only solution because of complexity? I think that would be sad.
Also I think we should see what Valhalla does because you might be creating more work for yourself. Like ask yourself the methods where you need these contracts can they be replaced with better modern ones that don't need contract and just deprecate the PolyNull like ones? For example many of Spring's utility methods already can be replaced with whats built into
Stringand is it really a good idea to flow type change based on the return of aboolean? For example in the case ofhasLengthyou would favor Guava's String utilitiesemptyToNullandnullToEmpty. Like ideally we use the type system that is builtin to Java as much as possible.Many of these things btw can be solved with pattern matching:
Now let me give you an example how embracing or encouraging PolyNull or similar can be a problem:
You see in the plain Java world with type
orElsedefinition is supposed to returnTexcept thatTcan benullableregardless of the nullability ofT(replaceTwithintwhere null is not possible).That is at the moment till we see what happens with Valhalla.
Could possible be a compiler failure or not. Or it is assumed
nullablewhere as your contract says it should not be and thus you will get compiler errors but the contract says you should not.So a lot of this
Conditionstuff I think needs to wait and it begs the question... maybe that one annotation is doing too much?sdeleuze commentedon Aug 13, 2025
For the record, this ask originates mostly from smaller OSS projects concerned about having to introduce their own
@Contractthat I relay, that's not a big player specific ask.agentgt commentedon Aug 13, 2025
Yes but it so happens the only implementation that is basically already done is IntelliJ and they are the only ones selling a tool. I admit I'm probably overly jaded but even now there is a lot of ... let us make sure we are compatible with Kotlin. That is probably a good thing and I assume mostly altruistic goals... Frankly I should probably just delete that comment as its kind of rude to assume.
Honestly my bigger concern is conflict with whatever Valhalla does. It seems like the easiest path is for Spring is just to replace or update its utility methods (and or not use them).
And I don't discount that this an incredibly annoying problem. For example most tools have some sort of pseudo hard coded white list of methods where the flow type changes. A classic case is
Objects.requireNonNullwhich hilariously would be fine if you use the return value but Error Prone has some weird rule where if you do:x = Objects.requireNonNull(x)it complains despite that being one of the safest way to flip/cast x to nonnull. Checkerframework will flat out not allow it since it requires thexto be NonNull on input unless you change theastub.So you can see there is already lots of conflicts between the tools and a lot of this is interpreting previous code of how it should be annotated and or you allow things like PolyNull.
Thats why I said it is almost a separate project. Like how does one interpret the current and potential future of the JDK without official annotations (I suppose it is sort of orthogonal but still what the JDK does is going to be the bigger influence).
The current set of annotations though are pretty future safe.
sdeleuze commentedon Aug 13, 2025
I will have a deeper look to your other concerns, links with
@PolyNull, and of course I expect a variety of opinions on that topic from the rest of the JSpecify working group who has more in mind than me@PolyNullconstraints and challenges. This can also be an opportunity for related discussion with the Valhalla working group.I don't want to rush anything, but there is a missing part in the JSpecify scope that I see in every OSS project leveraging checkers, I don't believe projects should modify APIs and break apps to make nullness checker happy, so I would like us to work on that topic and get that ball rolling, regardless of the outcome.
agentgt commentedon Aug 13, 2025
And my hope is you don't think I'm a debbie downer (or some sort of OSS over proprietary solution pusher) or just say no to any new feature. My explanation was to show just how complicated this can be and the potential risk.
I said PolyNull but what I really mean is the complexity of Flow analysis. That complexity is not just pushed on to the tools but the users themselves.
Like just doing
Is inherently more difficult to follow than normal non flow Java types. Like in that
ifblock you need a tool to show you that x is now flipped its type. You can't always easily infer it with code inspection on say github.Also flow analysis varies greatly in those tools.
For example:
That varies by tool and only Checkerframework and Eclipse at the moment will or can actually complain (replace x as
intto make the==failure easier to understand). JSpecify currently has no opinion on this but Valhalla very much could.So I'm just trying to show all the areas of issues to give feedback.
sdeleuze commentedon Aug 13, 2025
@wakingrufus Not sure, but I would begin by exploring if we can reach a consensus on only the nullness related use case initially, to not open too many doors at the same time.
cpovirk commentedon Aug 13, 2025
Thanks for the writeup and all the data! I have a lot of uncertainty in this area, so it's very helpful.
I have no answers, but here are a few thoughts:
returnsNotNull()contract.]@PolyNull, I should someday clean up my speech about how@PolyNullis complicated when used on type variables. If we are to support that here, I'd want to be clear on what it means.@ParameterContractannotation.@ParameterContractannotation would avoid that.ConditionandEffecthere) can cause trouble when people use them with incomplete classpaths. We have tried to avoid them in the past. We may end up wanting to avoid them here.cpovirk commentedon Aug 13, 2025
(I forgot to invoke @kevinb9n for any Valhalla thoughts (or other thoughts :)).)
agentgt commentedon Aug 13, 2025
In my mind I kind of equate a lot of this that people need to expect possible code changes and practices other than just adding annotations just like how when Java added generics there were still places you had to make changes instead of just adding the generic. In some cases
@SuppressWarningsis the best option for backward compat.For my own parsing and perhaps others:
Which is equivalent to:
And what is supposed to be inferred is that if func is passed
nullit will returnfalseand thus x maybe null if the return is false and thus if true x can be inferred as@NonNullgoing forward in that block of code (e.g. method).I'm fairly sure most of these are
hasLengthwhich I'm going to be frank should be replaced with a better method as I mentioned earlier. Like imagine expectingboolean func(Optional<X> x)to have guarantees that it isOptional.empty()if false. It is confusing and I bet a lot of its usage is cargo culting copy and paste.Roughly equal to:
This one should be already handled by JSpecify and you should mostly not be getting warnings. I say mostly because this one cannot be modeled exactly with out adding a
nulltype. That is because if I pass innullthat I know isnulllike the literalnullI always getnull.That is you need
@Null X x = null;and@Null Rwould be returned (as in guaranteed to be null). I'm not sure how that distinction is worthwhile other than I guess the IDE saying you will absolutely get a null pointer vs might get a null pointer.This is btw different from PolyNull because if
Xis not null you could still get anull(also PolyNull is usually used for the same base type but let us ignore that).I would be curious what warnings you get with these kinds methods with JSpecify checker @sdeleuze or was this just an example of the
Contractusage?This is the classic
assertNotNullorObjects.requireNonNullwhere you may or may not do reassignment. Some tools just have a giant list of methods they know that do this which I think is Eclipse and NullAway. Checker has annotations to do it with any method. (I assume the second variable is a description on the assert).This can be fixed with reassignment w/o flow analysis and indeed
Objects.requireNonNullguarantees NonNull return.I'm surprised this was not number one or number two. IMO this one is less of a problem because usually these are assertions, you can reassign, and most people use the same libraries or JDK for this stuff so the whitelist hack mostly works. In fact I think Eclipse has the Spring Assert methods hard coded in. I assume NullAway has some configuration somewhere.
Classic PolyNull. JSpecify cannot model this easily and people follow this pattern all over the place including the JDK. I'm surprised this was not the number one or number two.
This is why I was so concentrated on mentioning PolyNull because the first two which make up a huge amount of your count particularly hasLength can be fixed and may not even be a problem.
kevinb9n commentedon Aug 13, 2025
(Valhalla plans subject to change!)
Just confirming that in Valhalla we are planning "merely" to make
Foo?andFoo!types representable, with the type-checking you'd expect, and we'll have nothing fun addressing "polynull" use cases or more complex nullity contracts.But also, yes, we plan to only generate warnings, and probably in a handful of different nullity subcategories which the user can either silence or upgrade to errors selectively.
So for the user who wants smarter nullity contracts, they will want to keep using either
@PolyNulland similar things or this@Contract, and then probably they will just turn off the javac nullity warnings and rely on their tools instead.(It would be nice if javac could still do what it can and the tools just augment that behavior, but for that to work, we would need a way that a javac plugin can actually subtract warnings and not just add them. Or basically a very custom nullity-specific plugin API, all of which just feels weird.)
For our polynull methods like
T? cast(T? object), we might just introduce fauxverloads likeT! castNonNull(T! object)alongside them, which is not as good, but is something. Oh, but hopefully we will have a postfix cast-to-nonnull operator like Kotlin has, and maybe that's enough.Happy to answer other questions.
sdeleuze commentedon Aug 14, 2025
@agentgt BTW I appreciate your detailed feedback, I will take the type to digest it and answer, likely next week.
sdeleuze commentedon Sep 12, 2025
@agentgt Sorry for the delay, busy times.
To me,
@PolyNulllooks like a special case of what is described here. Also from a design perspective, since JSpecify 1.0 has shipped and the working group agreed on not introducing@Implies(aka meta annotation support), I think I prefer we don't attempt to refine the semantics of current annotations but rather add some additional contracts that provide hints for checkers.Given @kevinb9n feedback and what I hear from Project Valhalla, I have low concern that the contracts discussed here may introduce something incompatible with Project Valhalla. But does not hurt to wait for the first drafts to check.
I hear your perspective that we could refactor some code so avoid the need for some of those contracts. All the projects I have seen adopting JSpecify needs those kind of contracts to be able to get the checks green, some of those APIs are public or JDK APIs that we can't change, so I understand the hope but in practice that will not happen. And in some case, this is not desirable from an API design perspective.
About your ask for those potential annotations to be a different project, again to be discussed with the working group, but based on my understanding, JSpecify name and scope is IMO a good fit for such contract. I don't think JSpecify is current able to fulfil its core mission to provide a tooling neutral way to check your code base nullness without some kind of complementary contracts, so every projects introduce its own
@Contract, keeping the same duplication issue that we had pre-JSpecify with a proliferation of custom annotations. But I agree that extends the scope of thejspecifyartifact with something slightly more opinionated and that should be discussed in detail.That said, I think we don't have yet an API design strong enough to be evaluated for inclusion yet. @cpovirk has rightfully raised the IMO blocking issue that enums as annotation attributes generates compilation warnings when JSpecify is not on the classpath, so we are back to the drawing board. We will post an update once we get a refined API design to discuss.
agentgt commentedon Sep 12, 2025
@sdeleuze prior to JSpecify which tools are/were using to validate the original
@Contract? Is it IntelliJ headless? I confess while I have seen the annotations I have not used the headless tools that support them.Even if it was just hints the tools still may not have consensus and that can be annoying in itself. Remember part of the specification is to share across libraries that may use different tools.
I mentioned
@PolyNullbecause it has assignment guarantee and is more or less the only one that is unavoidable and the JDK has implied contractual logic of it everywhere. The JDK rarely doeshasLengthlogic (that is public). Ditto for Guava but I think it does have assertion logic (EnsureNonNull).I'm going to come back to assignment here in a second but the other flavors of
@Contractthat can be single annotation for the various use cases can largely be inspired from Checkerframework and I will use their parlance:@EnsureNonNullakaAssert.notNullwhere there is no reassignment but the type is NonNull after the assert call@EnsureNonNullIfakaAssert.hasLenthThe multiple annotation approach would avoid the enum problem @cpovirk mentioned.
However even if
@Contractor friends was added it quickly becomes a slippery slope.Let us go back to assignment and flow for this reason.
For the non assignment situations you will invariably use a mutable member variable.
That is if you did:
It fails because
this.xmay have flipped by another thread. I have seen lots of Spring code assume members are what is called@MonotonicNonNull.So now instead of changing what should be:
Another annotation would have to be added (MonotonicNonNull on the x member variable) to avoid rewriting code. Your bar will still not be green.
PolyNulldoes not have this problem because you are reassigning. Ditto for validations that return such as Guava's string methods (emptyToNull,nullToEmpty) or the JDK'sObjects.requireNonNull.If the code used better utility methods such as Guava:
No annotations need to be added.
So in my book PolyNull has the strongest case because
Optional.orElseorgetOrDefaultis actually present other code besides Springs. Then maybe@EnsureNonNullsince all the tools are already doing it but a full on@ContractI think is overkill.And adding annotations should not be taken lightly. I'm sort of unofficially working through Eclipse null analysis when I have time and yes Spring has a giant code base... so does Eclipse and adding another makes it hard for Eclipse (ECJ) (also VSCode RedHat extensions) to be JSpecify compliant difficult (as in an analysis tool).
I feel your pain but in the meantime there is
@SuppressWarnings.sdeleuze commentedon Sep 13, 2025
NullAway for example.
Indeed. Slighly less eleguant from my POV but that’s a constraint we will have to accept I guess.
I don’t, and I think I and the working group have understood your perspective.
That said, and even if I am not a tooling author, the semantics discussed in this issue should be pretty simple to implement. The attention should be on introducing as few as possible for a reasonable experience.
I think we all agree on
@Contractbeeing overkill, hence the effort to find a smaller acceptable subset.Again, I am not coming from a Spring only perspective, rather the opposite. Spring is big enough to have its own
@Contract, but for smaller projects, that’s a bummer to see each of them adding their own.After multiple years working on making code bases null-safe, I can confidently say that from my experience that does not work.
I am not a purist looking for 0
@SuppressWarnings, but the amount of methods you skip for the null check analysis is far too high.7 remaining items
sbrannen commentedon Sep 17, 2025
A recent version of AssertJ introduced
actual()which allows one to retrieve the "object currently under test". So one can write code like this:But... most developers don't want to do that, simply because it contradicts the DSL-style of assertions that developers have come to know and love.
Also, for an existing code base, it is likely not even an option to refactor an entire test suite (of potentially 100s of thousands of assertions) to make use of
actual(). Furthermore,actual()might not even work for certain use cases.agentgt commentedon Sep 17, 2025
And I get that but how are we going to specify that? Not only does
@Contracthere require the generic to be followed and flow analysis inference it is borderline doing things that can lead to bugs. That is unlikestream.filter(which is a way more common problem of this) you are not flipping the type downstream but impacting a type prior if that even makes sense.One of the reasons we run code analysis tools is to prevent bugs, improve code quality / communication etc. This requires opinions and "sound" opinions are better.
Furthermore @sdeleuze version of
@Contractis only on parameters will not even fix the above sinceisNotNulldoes not nave parameters. Again my concern that this is much bigger than NullAway already has it working. Some tools might have more false positive but have stronger guarantees.First they don't have to rewrite. Just like @kevinb9n mentioned once JDK the introduce nonnull types you will not have to rewrite (and I'm fairly sure future JDK is not going to be able do the magic required that
assertThat.isNotNullneeds). You simple configure.You see unit tests just like utility methods are pretty private. You the project owner have greater control of the tools and configuration. Your developers are probably using the same tools and configuration etc.
So you largely don't need a specification. The input from Spring is incredibly valuable but overall problem here from Spring is that the annotations requires another dependency for similar Spring ecosystem projects that does not have a rubber stamp of a spec.
And yes @sdeleuze right that I have a different perspective. I don't care about getting
everyonesa few large organizations toolbar green doing incredible inference. Some people value the tooling but I value the communication aspect and getting everyone to agree. That requires proper specification and not as much just "hints".Just having the current annotations is incredibly valuable and you can always layer on third party annotations just like Spring is doing.
EDIT while it sounds like I'm saying it cannot be done or should not be but rather we need to start not at an annotation perspective of parameter "constraints" or "contracts" of a single problem but like what flow analysis looks like. What operations do we allow on nullables and nonnulls. Then possibly how this travels through generics.
That is there is an implicit dependency of saying something like:
Is how you turn
xnonnull which currently is not specd as the current annotations do not require it. Then we may need to spec is it required thatxbe a local variable (as in not a member variable that could change) or is that an option. Doesxneed to be effectively final?There is also whether you allow
x == nullorx != nullon NonNulls which seems like it should but neither JSpecify or Java follow true subtyping. JSpecify for example does not allow covariant change of type of@Nullable->@NonNullin overridden methods and Java only allows you to perform those operations on identity types but int can be turned into Integer and you can do those operations.There maybe some leniency on the interpretation but I'm think we need to specify some of this so that
EnsureNonNulland friends work mostly the same. That is what specs are about. Consensus.wmdietl commentedon Sep 22, 2025
Lots of great points in this thread!
Thanks @sdeleuze for starting this discussion and for providing the statistics of how you've been using
@Contract!Also, thanks to @agentgt for the contrarian points.
I am not a fan of
@Contract- I find the contracts hard to read and decode.The Checker Framework and EISOP don't have support for that annotation.
I obviously like the contract annotations we have in the Checker Framework -
@RequiresNonNull,@EnsuresNonNull, and@EnsuresNonNullIf, plus@AssertMethodand@TerminatesExecution- together with@PolyNull- allow a precise specification of the nullness behavior of code.Let's leave the
@PolyNulldiscussion for #79. To me, adding a new type use annotation related to nullness is not objectionable and is easier than encoding the same in a contract.I would like to argue that JSpecify should work on standardizing method contracts.
I do see @agentgt 's point that such code should be rewritten in a clearer style - and everyone is free to do that!
However, there is a lot of code for which flow-sensitive refinement is the clearer option.
The behavior we want to specify is part of the API of these methods, so JSpecify should standardize this.
@Contractis already used very widely. We could try standardizing some subset of that contract language and allow better interoperability between different tools.It's harder to judge how widely the CF contract annotations are used. I find their focus on specific use cases and readability nicer.
The
@ParameterContractproposal also improves on the readability and discoverability, by using enums. However, using enums might not be good for our users.I would also not like to attach these contracts to parameters, as they usually combine information from parameters and the return of the method.
So, a specification on the method declaration seems easier to read and write to me.
Regarding the statistics about
@Contractusage in Spring, let me try to roughly re-write them with the CF annotations. I'm not doing this in an IDE, so there might be errors.@Contract("null -> false") -> @EnsuresNonNullIf(result=true, expression="#1")@Contract("null -> null") -> @PolyNull? If the arg is non-null, is the return non-null? Or the@Contractdoesn't specify?@Contract("null, _ -> fail") ->would require an extension of@AssertMethodor@TerminatesExecution@Contract("null -> null; !null -> !null") -> @PolyNull@Contract("null, _ -> false; _, null -> false") -> @EnsuresNonNullIf(result=true, expression="#1") @EnsuresNonNullIf(result=true, expression="#2")@Contract("_, null -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("null -> true") -> @EnsuresNonNullIf(result=false, expression="#1")@Contract("null, _ -> false") -> @EnsuresNonNullIf(result=true, expression="#1")@Contract("_, null -> false") -> @EnsuresNonNullIf(result=true, expression="#1")@Contract("_, null, _ -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("false, _ -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("_ -> fail") -> @TerminatesExecution@Contract("!null, _ -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("null -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("null, _ -> param2; _, null -> param1") ->Not sure how to interpret this@Contract("_, !null -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("_, false -> fail") -> @AssertMethod(parameter=2)@Contract("_, null -> true") -> @EnsuresNonNullIf(result=false, expression="#2")@Contract("_, null -> true; null, _ -> false") -> @EnsuresNonNullIf(result=true, expression="#1") @EnsuresNonNullIf(result=false, expression="#2")@Contract("_, null, _ -> fail; _, _, null -> fail") ->same extension of@AssertMethod/@TerminatesExecutionas above@Contract("_, null, null -> fail") ->Not sure how to interpret this@Contract("_, true -> fail") -> @AssertMethod(isAssertFalse=true, parameter=2)@Contract("null, _ -> false; _, null -> false;") -> @EnsuresNonNullIf(result=true, expression="#1") @EnsuresNonNullIf(result=true, expression="#2")@Contract("null, _ -> null") -> @PolyNullpossibly@Contract("null, _ -> null; _, null -> null") -> @PolyNullpossibly@Contract("null, _ -> true") -> @EnsuresNonNullIf(result=false, expression="#1")@Contract("null, _, _ -> null") -> @PolyNullThe Checker Framework annotations focus more on when something
@Nullablecan be refined to something@NonNull, which I find much easier to read than the@Contractversion.As @agentgt mentioned, the CF annotations allow more expressive specifications, e.g. that a particular field is non-null. As fields are usually not part of the API, that expressiveness is usually good when verifying the implementations of classes.
It is interesting that for the examples above, we only need three annotations:
EnsuresNonNullIffor methods that return booleans@PolyNullto express dependencies@AssertMethod/@TerminatesExecutionthat expresses that an exception is thrown if either a boolean is true/false or a parameter is null/non-null.I'm open to implementing something in EISOP, if we standardize it in JSpecify.
Related to this discussion of method contracts is whether we should have a small utility library, see #56.
CF/EISOP have one https://github.com/eisop/checker-framework/blob/master/checker-util/src/main/java/org/checkerframework/checker/nullness/util/NullnessUtil.java as does at least Eclipse https://github.com/eclipse-jdt/eclipse.jdt.core/blob/master/org.eclipse.jdt.annotation/src/org/eclipse/jdt/annotation/Checks.java.
I don't know whether IntelliJ or NullAway have something like that.
One correction to a comment from @agentgt:
EISOP is a fork of the Checker Framework, with many improvements across the board, but in particular for nullness (separate errors for nullness, initialization, and keyfor!).
The JSpecify Reference Checker is a separate type checker that uses EISOP (or an old fork of the CF).
[-]Introduce parameter contracts[/-][+]Introduce method contracts[/+]sdeleuze commentedon Sep 23, 2025
Thanks for your feedback @wmdietl, I have renamed the issue title to be less specific and match with your interesting alternative proposal.
cpovirk commentedon Nov 19, 2025
Our plan here is to iterate on a proposal document, not eternally append comments to a thread. But because @netdpb, @wmdietl, and I ended up discussing this in a recent meeting, I want to get some very abbreviated meeting notes down somewhere, focusing on points that I don't remember from earlier discussions:
trueif the parameter is null," then the override should, too.@PolyNull-style contract is kind of magic, I think? So maybe@PolyNull String x(@PolyNull Object o)(or however we'd spell it) could overrideString x(Object x), for example?@Nullabletype but with a contract that says it's non-null in certain situations. Now consider an override with that refines the return type to be@NonNull. In that case, we presumably shouldn't need to redeclare the contract, even though we would if we had kept the@Nullablereturn type.agentgt commentedon Nov 19, 2025
@cpovirk Your comments remind me of another issue and kind of my slight impetus to not wanting new contract annotations is the potential to hurt backward compatibility.
Assume we had something analogous to PolyNull (or whatever contract anno) in say version 2.0. A client library then upgrades to using
PolyNulloverNullable(assume the intent was polynull all along and custom annotation say checkers polynull or an intellij contract annotation was mixed in) what happens when the JSpecify 1.0 tools run on code base that uses that library?Probably things will fail to compile depending on tools flow analysis. Of course if they left the
@Nullableon and added the@PolyNullthen I would assume no problem. The 1.0 tool would continue to work.So I'm wondering if perhaps instead of adding annotations to the main JSpecify jar:
org.jspecify:jspecify:1.0.0there is a new jar/moduleorg.jspecify:jspecify-contracts:2.0.0(gav coordinates)?I just concerned with multiple versions we get you know the whole... xcd comments all over again..
cpovirk commentedon Nov 19, 2025
Good questions around compatibility. Some of it is about whether we actually introduce a new annotation
@PolyNullas opposed to supporting an equivalent with@ParameterContract, supporting@Nullable(onlyJointly = true), requiring@PolyNull @Nullable, or something else. (Obviously that's a bigger discussion.) Or, if we had@Impliesand widespread support for it, then we could probably get mileage out of having@PolyNullimply@Nullable.In the best case, I think that adding a contract should only reduce errors, not introduce them, maybe? At least that's what I'd expect for a
@PolyNullstyle of contract. Maybe we'd see something different with a@ThrowsIfNullcontract if tools were to use that to become stricter, but I wouldn't expect that to be the normal case. Am I overlooking other ways in which contracts could introduce errors in code that didn't previously have them?agentgt commentedon Nov 19, 2025
I kind of mention earlier that my overall problem with the contracts is that flow analysis (e.g. what happens inside a method body) is not really defined by the specification.
#757 (comment)
Basically it is the checking for null when you should not be as a failure. Analogous to how
int x = 0; boolean y = x == null; //failsThe idea to use other languages is that you have changed the shape and thus it should fail .
That is in other languages if:
I believe tools like Nullaway and IntelliJ don't care (or maybe it is configurable). Checkerframework and Eclipse can be configured to fail and I usually configure it so. I have probably said it way too many times but checking for null when you should not have to I find almost more useful to bug finding.
EDIT to be clear we are assuming the
@Nullableannotation is striped from thesomePolyNulland replaced withPolyNullbut I have feeling this is not what you were talking about?EDIT 2 What I'm proposing is if some library embraces a newer set of annotations they would do
That is they would leave the 1.0 annotations intact. Yes that verbose but my idea based on all the previous comments from Spring that these methods are kind of fringe.
netdpb commentedon Nov 20, 2025
I am leaning towards the simpler side, so that something polynullish would be a pure addition and would not imply other annotations.
So
@Nullable Foo someMethod(@ReturnsSameNullness @Nullable Bar bar)'. It would be incorrect to add@ReturnsSameNullnessto a parameter of a method whose return type isn't@Nullable`.xak2000 commentedon Dec 7, 2025
@wmdietl I would like to comment on a few of your statements in the hopes of somehow influencing the discussion.
I think it is a matter of personal preference. To me
@Contractexpressions reads much easier and naturally. Also it is much shorter, i.e. compact, which matters to prevent cluttering the code. If the code contains more meta-information than information, it reads much harder.Again, a matter of preference and experience with a particular library, I suppose. I didn't use contract-related Checker Framework annotations before, so I tried to understand your examples. I failed. :D
E.g.
The
@Contractversion is crystal clear to me: if parameter isnull, returnfalse, otherwise returntrue/false(behaviour is not specified).The
@EnsuresNonNullIfmeaning is very unclear. Whatresult=truemeans? Whatexpression="#1"means? Does it mean it will check the parameter#1or something else#1? Very cryptic syntax. And what1means? Is it 0-indexed or 1-indexed? Even the name of the annotation@EnsuresNonNullIf.. It ensures that the return value is non null, right? But the method returnsboolean, how can it returnnull?I have answers to most of these questions but only because I see the equal
@Contractexpression on the left. Otherwise I would not understand what@EnsuresNonNullIfis trying to represent without carefully reading the docs. The contract expression is very simple and readable even without the previous knowledge. Maybe it is because I already know the syntax. But I remember when I seen it the first time, and it was still very understandable, intuitive. E.g._is used to represent an argument that is unused and it is not something unexpected, because many other languages do the same. So, intuitive.Then I read the docs of
@EnsuresNonNullIfand was very surprised because this annotation does... an opposite to what@Contractdoes. It checks the method's result and depending on the result asserts the expression is not null.@Contractannotation doesn't do this. It checks the method's arguments and specifices the result the method will return in the case if the actual argument(s) is null/not-null. I.e.null -> falsemeans: if the 1st argument isnull, then the method will always returnfalse. But it doesn't mean that if the method returnsfalse, then the 1st argument isnull. For an expression like thisnull -> false; !null -> truethis could be assumed, but even then the intention of the contract is different. It is to assert the result based on arguments, not the other way around.So, it turns out that these are not equivalents:
But, if I would need a functionality provided by
@EnsuresNonNullIfusing@Contract, I would prefer to see it like this:Reads like "1st argument is not null if the return value is true".
Of course, it is hypothetical example. It is not supported. And I understand that
@EnsuresNonNullIfis more powerful as you can specify not only arguments asexpression. By "I would prefer" I just mean readability. Not the functionality.I fully agree on this. It is a method contract, not a parameter contract, so it should not be attached to any specific parameter.
I thought about this alot and while I also don't like the approach with arbitrary string expression of
@Contract, there is just no better alternative. All other solutions are either overcomplicated, very verbose (yes, it is big disadvantage if we are talking about meta-information), and/or do not allow you to be flexible enough to specify all the cases. At least all the common cases.The more I think about this the more I believe that maybe JSpecify is the wrong place to implement the method contracts..
In practice, though, it is very needed feature. Otherwise you are forced to suppress the warnings in many places where they should not be suppressed because by suppressing them you will hide an actual error in case somebody passes null and expect not-null as a return value from a method with a contract like this
null -> null; !null -> !null(a typical contract for a mapper/converter, just as an example).Maybe it should be implemented as a new library, a JSpecify extension.
jspecify-contractor something. :)toolforger commentedon May 9, 2026
Please let me add my 5 cents and adjust this statement:
From my time as a seasoned Eiffel programmer, I know we intensely wanted to have statically-checkable contracts. The language is not built for that and everybody knew it would never happen, but it was still a recurring theme on newsgroup, lists, and direct communication.
From my work with various runtime-typed languages, I know that a static type system is a set of contracts for the types of variables, carefully designed so that it is statically checkable.
From that view, things like
class,enum,recordare type constructors (with a funny syntax), and a type annotation likeString foois a shorthand forassert foo == null || foo instanceof String, the only difference being that one is checked by the compiler and the other at runtime.So, the distinction between types and contracts is just the difference between runtime and compile time checkability, and this distinction tends to shift as inference engines keep getting better.
In fact some Haskell people have fun with their type system and built types that could express quadratic matrices as a subtype of arbitrary matrices. I don't think it would be practical because the type language of Haskell wasn't built for that purpose, but it demonstrates how the boundary can change over time.
Personally, I think if somebody wants contracts, they should be seen as extensions of the type system or the type system as a subset of contracts.
YMMV :-)