NullAway icon indicating copy to clipboard operation
NullAway copied to clipboard

Add some kind of `@PolyNull`-like support within library models?

Open msridhar opened this issue 5 months ago • 10 comments

The JSpecify JDK model for Optional.orElseGet is (here):

    // We would use an annotation like @PolyNull here if JSpecify offered one.
    public @Nullable T orElseGet(Supplier<? extends @Nullable T> supplier) {

When working on #1613 I noticed that modeling orElseGet as returning @Nullable introduces many false positives, for cases where the provided supplier cannot return null. I think we probably need to find a way to model this one precisely in order to not cause too many FPs in practice.

msridhar avatar Jun 19 '26 21:06 msridhar

Extending @Contract (or whatever the library model equivalent is) to allow referring to type bounds within arguments and return values, maybe?

lazaroclapp avatar Jun 24 '26 02:06 lazaroclapp

Yeah, this is beyond the expressivity of @Contract and I'm hesitant to add NullAway's own interpretation of contract strings. So probably something special in library models is the right solution for now, letting you model that if a type argument of a parameter type is @NonNull, so is the return type.

msridhar avatar Jun 24 '26 23:06 msridhar

Another case like this is List.toArray, which is currently modeled in JSpecify JDK as always returning an array with @Nullable contents; the typetools jdk models it with @PolyNull.

To avoid excessive imprecision, we may need a way to override these cases once we are importing JSpecify JDK models.

msridhar avatar Jul 22 '26 23:07 msridhar

Hi! I'd like to pick this up if it's still available. I found two commented-out attempts already in LibraryModelsHandler.java (in ALWAYS_NULLABLE_RETURNS and NESTED_ANNOTATIONS_FOR_METHODS, both tagged with this issue) — the second one looks like the right approach, mirroring how Optional.map is already modeled. Planning to dig into why it wasn't completed and finish it. Will open a PR once the ignored test in JSpecifyLibraryModelsTests passes.

abdeltaehass avatar Aug 20 '26 06:08 abdeltaehass

I spent some time digging into this and hit a wall that I think is worth a scoping question before I go further.

The commented-out orElseGet entry in NESTED_ANNOTATIONS_FOR_METHODS doesn't work on its own. I uncommented it and un-ignored JSpecifyLibraryModelsTests.optionalOrElseGet; the test still fails with "There were no errors." The entry rewrites the parameter to Supplier<? extends @Nullable T>, which makes () -> null legal, but orElseGet's return type is still T, and T is pinned to non-null String by the receiver Optional<String>. Nothing flows from the argument back to the return. That's also why the Optional.map entry it mirrors isn't quite the precedent it looks like — map's model is false-positive avoidance for map(x -> null), not nullability propagation.

A separate gap I ran into along the way: java.util.function.Supplier isn't in NULLMARKED_CLASSES at all, and has no NULLABLE_VARIABLE_TYPE_UPPER_BOUNDS entry. So Supplier is currently invisible to JSpecify checking, independent of this issue:

void f(Supplier<@Nullable String> s) {
  s.get().hashCode();          // not flagged today
}
Supplier<String> g() {
  return () -> null;           // not flagged today
}

Both are flagged for Function, which is modeled. Adding .add("java.util.function.Supplier") and .put("java.util.function.Supplier", 0) fixes both, and is regression-free across :nullaway:test locally. Happy to send that as its own small PR if it's wanted — it seems like a prerequisite for anything here regardless.

Where that leaves orElseGet. With Supplier modeled but no return-type model:

call result
orElseGet(() -> "x") clean
orElseGet(() -> null) error, but on the lambda, not the dereference
orElseGet(nullableSupplier) silent
orElseGet(nonNullSupplier) silent

The design @msridhar sketched above — "if a type argument of a parameter type is @NonNull, so is the return type" — works cleanly for the variable and method-reference cases, since the argument's static type carries the nullability.

The lambda case is the part I can't see a way through. A lambda's type is its target type, so once the parameter is widened to Supplier<? extends @Nullable T>, () -> null and () -> "x" are indistinguishable at the signature level. Telling them apart means inferring nullability from the lambda body.

NullAway already does exactly that in handleLambdaInGenericMethodInference, which feeds a lambda's return expression into the constraint solver — but it's gated behind isGenericCallNeedingInference:

return methodSymbol != null
    && methodSymbol.type instanceof Type.ForAll
    && methodInvocation.getTypeArguments().isEmpty();

orElseGet is not a ForAll — its T belongs to Optional, not to the method — so the solver never runs for it. Reaching it would mean introducing a synthetic inference variable that doesn't exist on the method symbol and threading it through ConstraintSolver, updateTypeWithInferredNullability, the per-call inference cache, and the dataflow path. That felt like a bigger architectural change than I should make unilaterally.

So the question: is the intended scope of the poly-null library model meant to cover lambda arguments, or would you be happy with a version that only handles cases where the argument's declared type carries the nullability (variables, method refs, explicitly-typed lambdas) and leaves implicit lambdas conservative? The latter is a much more contained change and I'd be glad to take it on. If lambdas are in scope, I'd rather agree the approach with you first than guess at it.

abdeltaehass avatar Aug 20 '26 06:08 abdeltaehass

@abdeltaehass I think we should be able to handle lambda arguments? We can already use returns from lambdas for generating constraints in generic method call inference. I think the main high-level idea here would be to enhance inference so that we constrain the nullability of the return type at a call to orElseGet to be equal to the nullability of the Supplier type argument. I hope adding that would be a somewhat narrow change, but I'm not sure.

Regarding Supplier, it is modeled under the JSpecifyExperimental flag, which enables JSpecify JDK models. All our JSpecify mode regression tests now run with that flag enabled. And this new type of model only makes sense in JSpecify mode anyway.

msridhar avatar Aug 20 '26 23:08 msridhar

You were right that lambdas are handleable — I had that wrong. I spiked it and the four cases work, including orElseGet(() -> null) vs orElseGet(() -> "x"); the ignored optionalOrElseGet test passes with @Ignore removed, and the rest of the suite is unaffected.

Four things I hit, in case they're useful:

  1. The dataflow path is getGenericReturnNullnessAtInvocation, which only consults inference when the method has its own type parameters — so orElseGet fell through to receiver substitution and my first attempt was a no-op.
  2. The JSpecify JDK model gives the executable type as (Supplier<? extends @Nullable T>)T, and treatAsTypeVariableForInference excludes annotated type vars, so the parameter slot isn't an inference variable. The poly slots need the bare variable.
  3. Passing the assignment context into inference is circular here — the dereference constrains the return @NonNull while the lambda constrains it @Nullable.
  4. The real obstacle: VarState's nullableAllowed comes from upperBoundIsNullable, and Optional<T>'s bound is non-null, so the solver correctly refuses to infer T as @Nullable. Reusing the class type variable can't work. I confirmed this by overriding the bound to prove the rest of the mechanism — that makes all four cases pass but wrongly legalizes Optional<@Nullable String>, which no current test catches.

So I think this needs a fresh poly inference variable with a nullable-permitting bound rather than reusing T. Does that match what you had in mind, and is introducing a synthetic variable into the solver acceptable? If so I'll build it out properly with a real library model instead of the hardcoded check I used for the spike.

abdeltaehass avatar Aug 21 '26 00:08 abdeltaehass

@abdeltaehass it looks to me like you are copy-pasting AI responses here. If that's true, please don't do that; if I wanted to go back and forth with an AI to solve this task, I'd just do it myself.

If your comments reflect your own understanding of the code, and not just what an AI is telling you, then you should be able to figure out a good way to solve this problem cleanly on your own, and to explain your solution properly afterward. I don't have time to dig into the code and suggest a detailed approach right now. Again, if I had the time to do that, I would just use an AI and implement this myself.

msridhar avatar Aug 21 '26 00:08 msridhar

@msridhar Yes, I use AI as a tool, the same way I'd use a debugger or a profiler. It helps me get oriented in unfamiliar parts of the codebase faster than I could on my own. Your point is fair, though: The tool should help me build an understanding, not stand in for one. Thanks for the nudge on the inference side — that pointed me somewhere useful.

abdeltaehass avatar Aug 21 '26 00:08 abdeltaehass

I think it's probably best for me to take this on myself. Given the need to support scenarios like computeIfAbsent (jspecify/jdk#156) this will take some design thought and experimentation.

msridhar avatar Aug 23 '26 20:08 msridhar