Skip to content

Introduce method contracts #757

Open

Description

@sdeleuze

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

  1. wakingrufus commented on Aug 13, 2025

    @wakingrufus

    Is this meant to also conver contracts like -> new and -> this ? Or just null-related contracts?

  2. agentgt commented on Aug 13, 2025

    @agentgt

    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 @PolyNull and 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.

    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,

    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 String and is it really a good idea to flow type change based on the return of a boolean? For example in the case of hasLength you would favor Guava's String utilities emptyToNull and nullToEmpty. 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:

    var result = switch(emptyToNull(s)) {
      case s -> s; // or some giant imperative block
      case null -> "default"
    }

    Now let me give you an example how embracing or encouraging PolyNull or similar can be a problem:

    Optional<T> opt;
    var x = opt.orElse(null); // could fail here
    // or y is not null
    var x = opt.orElse(y); 
    x.toString() // or could fail here because the compiler still says x could be nullable

    You see in the plain Java world with type orElse definition is supposed to return T except that T can be nullable regardless of the nullability of T (replace T with int where null is not possible).

    That is at the moment till we see what happens with Valhalla.

    Optional<T!> opt;
    var x = opt.orElse(null);
    

    Could possible be a compiler failure or not. Or it is assumed nullable where 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 Condition stuff I think needs to wait and it begs the question... maybe that one annotation is doing too much?

  3. sdeleuze commented on Aug 13, 2025

    @sdeleuze
    CollaboratorAuthor

    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.

    For the record, this ask originates mostly from smaller OSS projects concerned about having to introduce their own @Contract that I relay, that's not a big player specific ask.

  4. agentgt commented on Aug 13, 2025

    @agentgt

    For the record, this ask originates mostly from smaller OSS projects concerned about having to introduce their own @Contract that I relay, that's not a big player specific ask.

    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.requireNonNull which 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 the x to be NonNull on input unless you change the astub.

    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.

  5. sdeleuze commented on Aug 13, 2025

    @sdeleuze
    CollaboratorAuthor

    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 @PolyNull constraints 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.

  6. agentgt commented on Aug 13, 2025

    @agentgt

    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

    if (hasLength(x)) {
      // x is not null here
    }
    else {
      // x is nullable here
    }

    Is inherently more difficult to follow than normal non flow Java types. Like in that if block 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:

    if (hasLength(x)) {
      if (x == null) { // should this be legal?
      }
    }
    else {
      // x is nullable here
    }

    That varies by tool and only Checkerframework and Eclipse at the moment will or can actually complain (replace x as int to 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.

  7. sdeleuze commented on Aug 13, 2025

    @sdeleuze
    CollaboratorAuthor

    Is this meant to also conver contracts like -> new and -> this ? Or just null-related contracts?

    @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.

  8. cpovirk commented on Aug 13, 2025

    @cpovirk
    Collaborator

    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:

    • I agree that tool support is a big question. If we could get Kotlin, IntelliJ, NullAway, and EISOP on board, I'd feel a lot better. (Sorry, Eclipse. Obviously I'd be happy to see them, too. What other projects are I forgetting?)
      • [update: Kotlin added experimental support for their conditional returnsNotNull() contract.]
    • I would also love to think more about the Valhalla issue raised. I am under the impression that Valhalla nullness markers would likely produce only warnings at first in javac (maybe forever?), so we may well see users who disable all those warnings and turn things over to another nullness checker like the ones they use today.
    • For @PolyNull, I should someday clean up my speech about how @PolyNull is complicated when used on type variables. If we are to support that here, I'd want to be clear on what it means.
    • Some of the historical concerns about an expression language (such as those here) are concerns about using any single annotation for a variety of use cases. Those would apply to a general @ParameterContract annotation.
    • Another concern about an expression language is that it's less discoverable and autocompletable than alternatives. The proposed @ParameterContract annotation would avoid that.
    • Annotations that have enum elements (like Condition and Effect here) 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.
  9. cpovirk commented on Aug 13, 2025

    @cpovirk
    Collaborator

    (I forgot to invoke @kevinb9n for any Valhalla thoughts (or other thoughts :)).)

  10. agentgt commented on Aug 13, 2025

    @agentgt

    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 @SuppressWarnings is the best option for backward compat.

    For my own parsing and perhaps others:

    32x @Contract("null -> false") -> @ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_FALSE)

    Which is equivalent to:

    boolean func(@Nullable X x);

    And what is supposed to be inferred is that if func is passed null it will return false and thus x maybe null if the return is false and thus if true x can be inferred as @NonNull going forward in that block of code (e.g. method).

    I'm fairly sure most of these are hasLength which I'm going to be frank should be replaced with a better method as I mentioned earlier. Like imagine expecting boolean func(Optional<X> x) to have guarantees that it is Optional.empty() if false. It is confusing and I bet a lot of its usage is cargo culting copy and paste.

    13x @Contract("null -> null") -> @ParameterContract(when = Condition.IS_NULL, then = Effect.RETURN_NULL)
    

    Roughly equal to:

    @Nullable R func(@Nullable X x);

    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 null type. That is because if I pass in null that I know is null like the literal null I always get null.

    That is you need @Null X x = null; and @Null R would 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 X is not null you could still get a null (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 Contract usage?

    12x @Contract("null, _ -> fail") ->  @ParameterContract(when = Condition.IS_NULL, then = Effect.FAIL)
    
    void func(@Nullable X x, String description); 
    // or
    @NonNull X func(@Nullable X x, String description);

    This is the classic assertNotNull or Objects.requireNonNull where 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.requireNonNull guarantees 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.

    8x @Contract("null -> null; !null -> !null") -> @ParameterContract(when = Condition.NONE, then = Effect.RETURN_SAME_NULLNESS)
    

    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.

  11. kevinb9n commented on Aug 13, 2025

    @kevinb9n
    Collaborator

    (Valhalla plans subject to change!)

    Just confirming that in Valhalla we are planning "merely" to make Foo? and Foo! 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 @PolyNull and 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 like T! 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.

  12. sdeleuze commented on Aug 14, 2025

    @sdeleuze
    CollaboratorAuthor

    @agentgt BTW I appreciate your detailed feedback, I will take the type to digest it and answer, likely next week.

  13. sdeleuze commented on Sep 12, 2025

    @sdeleuze
    CollaboratorAuthor

    @agentgt Sorry for the delay, busy times.

    To me, @PolyNull looks 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 the jspecify artifact 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.

  14. agentgt commented on Sep 12, 2025

    @agentgt

    @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.

    some additional contracts that provide hints for checkers.

    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.

    To me, @polynull looks like a special case of what is described here.

    I mentioned @PolyNull because 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 does hasLength logic (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 @Contract that can be single annotation for the various use cases can largely be inspired from Checkerframework and I will use their parlance:

    • @EnsureNonNull aka Assert.notNull where there is no reassignment but the type is NonNull after the assert call
    • @EnsureNonNullIf aka Assert.hasLenth

    The multiple annotation approach would avoid the enum problem @cpovirk mentioned.

    However even if @Contract or 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:

    // some member variable set by setter or wherever
    @Nullable String x = null;
    
    void someMethod() {
      if (Assert.hasLength(this.x)) {
        this.x.toString(); // analysis failure here for many tools.
      }
    }

    It fails because this.x may 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:

    // some member variable set by setter or wherever
    @Nullable String x = null;
    
    void someMethod() {
      var _x = this.x;
      if (Assert.hasLength(_x)) {
        _x.toString(); // _x has been copied atomically so we are ok
      }
    }

    Another annotation would have to be added (MonotonicNonNull on the x member variable) to avoid rewriting code. Your bar will still not be green.

    PolyNull does not have this problem because you are reassigning. Ditto for validations that return such as Guava's string methods (emptyToNull, nullToEmpty) or the JDK's Objects.requireNonNull.

    If the code used better utility methods such as Guava:

    // some member variable set by setter or wherever
    @Nullable String x = null;
    
    void someMethod() {
      var _x = Strings.emptyToNull(this.x);
      if (_x != null) {
        _x.toString(); // analysis failure here for many tools.
      }
    }

    No annotations need to be added.

    So in my book PolyNull has the strongest case because Optional.orElse or getOrDefault is actually present other code besides Springs. Then maybe @EnsureNonNull since all the tools are already doing it but a full on @Contract I 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.

  15. sdeleuze commented on Sep 13, 2025

    @sdeleuze
    CollaboratorAuthor

    prior to JSpecify which tools are/were using to validate the original @Contract?

    NullAway for example.

    The multiple annotation approach would avoid the enum problem @cpovirk mentioned.

    Indeed. Slighly less eleguant from my POV but that’s a constraint we will have to accept I guess.

    And adding annotations should not be taken lightly.

    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.

    Then maybe @EnsureNonNull since all the tools are already doing it but a full on @Contract I think is overkill.

    I think we all agree on @Contract beeing overkill, hence the effort to find a smaller acceptable subset.

    Spring has a giant code base

    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.

    I feel your pain but in the meantime there is @SuppressWarnings

    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.

  16. 7 remaining items

  17. sbrannen commented on Sep 17, 2025

    @sbrannen
    Collaborator

    I think the following is more clear and would work with current JSpecify although I'm not sure if assertj supports it:

    var newFoo = assertThat(foo).isNotNull();
    newFoo.bar();

    A recent version of AssertJ introduced actual() which allows one to retrieve the "object currently under test". So one can write code like this:

    @Test
    void test() {
    	var nonNullFoo = assertThat(foo).isNotNull().actual();
    	assertThat(nonNullFoo.bar()).isEqualTo("test");
    }

    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.

  18. agentgt commented on Sep 17, 2025

    @agentgt

    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.

    And I get that but how are we going to specify that? Not only does @Contract here require the generic to be followed and flow analysis inference it is borderline doing things that can lead to bugs. That is unlike stream.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 @Contract is only on parameters will not even fix the above since isNotNull does 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.

    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.

    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.isNotNull needs). 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 everyones a 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:

    if (x != null) {
    // x is no longer null here.
    }

    Is how you turn x nonnull which currently is not specd as the current annotations do not require it. Then we may need to spec is it required that x be a local variable (as in not a member variable that could change) or is that an option. Does x need to be effectively final?

    There is also whether you allow x == null or x != null on 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 -> @NonNull in 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 EnsureNonNull and friends work mostly the same. That is what specs are about. Consensus.

  19. wmdietl commented on Sep 22, 2025

    @wmdietl
    Collaborator

    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 @AssertMethod and @TerminatesExecution - together with @PolyNull - allow a precise specification of the nullness behavior of code.

    Let's leave the @PolyNull discussion 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.

    @Contract is 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 @ParameterContract proposal 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 @Contract usage 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.

    • 32x @Contract("null -> false") -> @EnsuresNonNullIf(result=true, expression="#1")
    • 13x @Contract("null -> null") -> @PolyNull? If the arg is non-null, is the return non-null? Or the @Contract doesn't specify?
    • 12x @Contract("null, _ -> fail") -> would require an extension of @AssertMethod or @TerminatesExecution
    • 8x @Contract("null -> null; !null -> !null") -> @PolyNull
    • 6x @Contract("null, _ -> false; _, null -> false") -> @EnsuresNonNullIf(result=true, expression="#1") @EnsuresNonNullIf(result=true, expression="#2")
    • 5x @Contract("_, null -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 5x @Contract("null -> true") -> @EnsuresNonNullIf(result=false, expression="#1")
    • 5x @Contract("null, _ -> false") -> @EnsuresNonNullIf(result=true, expression="#1")
    • 4x @Contract("_, null -> false") -> @EnsuresNonNullIf(result=true, expression="#1")
    • 4x @Contract("_, null, _ -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 4x @Contract("false, _ -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 3x @Contract("_ -> fail") -> @TerminatesExecution
    • 2x @Contract("!null, _ -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 2x @Contract("null -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 2x @Contract("null, _ -> param2; _, null -> param1") -> Not sure how to interpret this
    • 1x @Contract("_, !null -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 1x @Contract("_, false -> fail") -> @AssertMethod(parameter=2)
    • 1x @Contract("_, null -> true") -> @EnsuresNonNullIf(result=false, expression="#2")
    • 1x @Contract("_, null -> true; null, _ -> false") -> @EnsuresNonNullIf(result=true, expression="#1") @EnsuresNonNullIf(result=false, expression="#2")
    • 1x @Contract("_, null, _ -> fail; _, _, null -> fail") -> same extension of @AssertMethod/@TerminatesExecution as above
    • 1x @Contract("_, null, null -> fail") -> Not sure how to interpret this
    • 1x @Contract("_, true -> fail") -> @AssertMethod(isAssertFalse=true, parameter=2)
    • 1x @Contract("null, _ -> false; _, null -> false;") -> @EnsuresNonNullIf(result=true, expression="#1") @EnsuresNonNullIf(result=true, expression="#2")
    • 1x @Contract("null, _ -> null") -> @PolyNull possibly
    • 1x @Contract("null, _ -> null; _, null -> null") -> @PolyNull possibly
    • 1x @Contract("null, _ -> true") -> @EnsuresNonNullIf(result=false, expression="#1")
    • 1x @Contract("null, _, _ -> null") -> @PolyNull

    The Checker Framework annotations focus more on when something @Nullable can be refined to something @NonNull, which I find much easier to read than the @Contract version.

    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:

    • EnsuresNonNullIf for methods that return booleans
    • @PolyNull to express dependencies
    • some extension of @AssertMethod/@TerminatesExecution that 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:

    Is it that the reference implementation aka EISOP not working and you are comparing it?

    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).

  20. changed the title [-]Introduce parameter contracts[/-] [+]Introduce method contracts[/+] on Sep 23, 2025
  21. sdeleuze commented on Sep 23, 2025

    @sdeleuze
    CollaboratorAuthor

    Thanks for your feedback @wmdietl, I have renamed the issue title to be less specific and match with your interesting alternative proposal.

  22. added
    nullness
    design
    new-feature
    on Oct 8, 2025
  23. cpovirk commented on Nov 19, 2025

    @cpovirk
    Collaborator

    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:

    • In addition to how contracts obviously affect callers (in "implementation code," which is something we haven't actually covered a ton in the spec yet (Cover elements in implementation code in "Augmented type of a type usage appearing in code" #661, Rules for type inference #705)), they also affect overrides.
      • To a large extent, checking of overrides could be an extra step: If a supermethod says "returns true if the parameter is null," then the override should, too.
      • But other cases may be more complex: A @PolyNull-style contract is kind of magic, I think? So maybe @PolyNull String x(@PolyNull Object o) (or however we'd spell it) could override String x(Object x), for example?
    • Some combinations are at least suspicious, if not bogus: If a parameter can't be null, then it's suspicious for a contract to refer to what would happen if it is null.
      • It's possible that this connects back to the previous point: Consider a supermethod that returns a @Nullable type 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 @Nullable return type.
  24. agentgt commented on Nov 19, 2025

    @agentgt

    @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 PolyNull over Nullable (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 @Nullable on and added the @PolyNull then 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.0 there is a new jar/module org.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..

  25. cpovirk commented on Nov 19, 2025

    @cpovirk
    Collaborator

    Good questions around compatibility. Some of it is about whether we actually introduce a new annotation @PolyNull as 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 @Implies and widespread support for it, then we could probably get mileage out of having @PolyNull imply @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 @PolyNull style of contract. Maybe we'd see something different with a @ThrowsIfNull contract 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?

  26. agentgt commented on Nov 19, 2025

    @agentgt

    Am I overlooking other ways in which contracts could introduce errors in code that didn't previously have them?

    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; //fails

    /* Nullable as of 1.0 */ var x = somePolyNull(y);
    
    // some checkers will fail here if x is no longer nullable as the annotation is missing.
    if (x == null) { 
    }

    The idea to use other languages is that you have changed the shape and thus it should fail .

    That is in other languages if:

    switch(x) {
     case String s -> ..;
     case null -> ...; // If x can never be null than x is no longer String | null
    }

    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 @Nullable annotation is striped from the somePolyNull and replaced with PolyNull but 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

    @Nullable String somePolyNull(@PolyNull @Nullable String y) {
    }

    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.

  27. netdpb commented on Nov 20, 2025

    @netdpb
    Collaborator

    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`.

  28. xak2000 commented on Dec 7, 2025

    @xak2000

    @wmdietl I would like to comment on a few of your statements in the hopes of somehow influencing the discussion.

    The @ParameterContract proposal also improves on the readability and discoverability, by using enums.

    I think it is a matter of personal preference. To me @Contract expressions 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.

    The Checker Framework annotations focus more on when something @Nullable can be refined to something @NonNull, which I find much easier to read than the @Contract version.

    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.

    @Contract("null -> false") -> @EnsuresNonNullIf(result=true, expression="#1")
    

    The @Contract version is crystal clear to me: if parameter is null, return false, otherwise return true/false (behaviour is not specified).

    The @EnsuresNonNullIf meaning is very unclear. What result=true means? What expression="#1" means? Does it mean it will check the parameter #1 or something else #1? Very cryptic syntax. And what 1 means? 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 returns boolean, how can it return null?

    I have answers to most of these questions but only because I see the equal @Contract expression on the left. Otherwise I would not understand what @EnsuresNonNullIf is 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 @EnsuresNonNullIf and was very surprised because this annotation does... an opposite to what @Contract does. It checks the method's result and depending on the result asserts the expression is not null. @Contract annotation 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 -> false means: if the 1st argument is null, then the method will always return false. But it doesn't mean that if the method returns false, then the 1st argument is null. For an expression like this null -> false; !null -> true this 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:

    @Contract("null -> false") -> @EnsuresNonNullIf(result=true, expression="#1")
    

    But, if I would need a functionality provided by @EnsuresNonNullIf using @Contract, I would prefer to see it like this:

    @Contract("!null <- true")
    

    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 @EnsuresNonNullIf is more powerful as you can specify not only arguments as expression. By "I would prefer" I just mean readability. Not the functionality.


    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.

    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-contract or something. :)

  29. toolforger commented on May 9, 2026

    @toolforger

    The challenging part is that this a lot of this basically an extension of @PolyNull and 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).

    Please let me add my 5 cents and adjust this statement:

    1. 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.

    2. 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, record are type constructors (with a funny syntax), and a type annotation like String foo is a shorthand for assert 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 :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    designnew-featurenullness

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions