From 8c40e57a621481f6f027824af1ae036bc9b2db06 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Mon, 16 Nov 2026 18:54:23 -0800 Subject: [PATCH 01/27] Infer inline generic method references from their argument targets Infer omitted type-argument nullability before checking a generic method reference passed to a method or constructor. Cache the result on the reference, preserve joint enclosing-call inference, and reuse it when resolving the referenced method type. Fix both publisher reproducers in #2063, including parenthesized references and explicit enclosing-call type arguments. Include direct-argument coverage for static, bound, unbound, and varargs references, incompatible targets, and explicit reference type arguments. Validation: the two extracted regression tests fail on master and pass with this change; :nullaway:test and :nullaway:buildWithNullAway pass. Diff-scoped PIT kills all 7 mutants. Assisted-by: Codex (gpt-6) --- .../nullaway/generics/GenericsChecks.java | 96 +++++++----- ...enericMethodLambdaOrMethodRefArgTests.java | 144 ++++++++++++++++++ 2 files changed, 206 insertions(+), 34 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 067b676734..a93e358f1c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -138,9 +138,9 @@ private InferenceFailure(@Nullable String errorMessage) { } /** - * Maps a Tree representing a call to a generic method or constructor to the result of inferring - * its type argument nullability. The call must not have any explicit type arguments. If a tree is - * not present as a key in this map, it means inference has not yet been attempted for that call. + * Maps each call or method reference that took part in a generic inference run to that run's + * result. Only omitted type arguments are inferred; explicit arguments can still constrain an + * enclosing call. If a tree is absent, no inference result has been cached for that site. */ private final Map inferredTypeVarNullabilityForGenericCalls = new LinkedHashMap<>(); @@ -1490,7 +1490,8 @@ private CallInferenceResult runInferenceForCall( boolean assignedToLocal, boolean calledFromDataflow) { ConstraintSolver solver = makeSolver(state, analysis); - // allCalls tracks the top-level call and any nested calls that also require inference + // allCalls tracks the top-level call, nested calls requiring inference, and every method + // reference whose functional-interface type constrains the run. Set allCalls = new LinkedHashSet<>(); allCalls.add(callTree); IdentityHashMap polyNullContexts = @@ -1669,8 +1670,9 @@ private Symbol.MethodSymbol getMethodSymbolForCall(ExpressionTree callTree) { * @param callTree the call tree representing the generic method call or diamond constructor call * @param methodType the executable type of {@code callTree}, as computed by {@link * #getExecutableTypeForInference} - * @param allCalls a set of all calls that require inference, including nested ones. This is an - * output parameter that gets mutated while generating the constraints to add nested calls. + * @param allCalls the top-level call, nested calls requiring inference, and every method + * reference whose functional-interface type constrains the run. This is an output parameter + * that gets mutated while generating the constraints to add nested sites. * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This * is an output parameter mutated during constraint generation to add contexts for modeled * calls. @@ -1776,8 +1778,9 @@ private void generateConstraintsForCall( * * @param state the visitor state * @param solver the constraint solver - * @param allCalls a set of all calls that require inference, including nested ones. This is an - * output parameter that gets mutated while generating the constraints to add nested calls. + * @param allCalls the top-level call, nested calls requiring inference, and every method + * reference whose functional-interface type constrains the run. This is an output parameter + * that gets mutated while generating the constraints to add nested sites. * @param rhsExpr the right-hand side expression of the pseudo-assignment * @param lhsType the left-hand side type of the pseudo-assignment * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This @@ -1846,6 +1849,7 @@ private void generateConstraintsForPseudoAssignment( polyNullContexts, calledFromDataflow); } else if (rhsExpr instanceof MemberReferenceTree memberReferenceTree) { + allCalls.add(memberReferenceTree); handleMethodRefInGenericMethodInference(state, solver, lhsType, memberReferenceTree); } else { // all other cases Type argumentType = getTreeType(rhsExpr, state, calledFromDataflow); @@ -1874,8 +1878,9 @@ private void generateConstraintsForPseudoAssignment( * @param path the tree path to the enclosing call if available and possibly distinct from {@code * state.getPath()} * @param solver the constraint solver - * @param allCalls a set of all calls that require inference, including nested ones. This is an - * output parameter that gets mutated while generating the constraints to add nested calls. + * @param allCalls the top-level call, nested calls requiring inference, and every method + * reference whose functional-interface type constrains the run. This is an output parameter + * that gets mutated while generating the constraints to add nested sites. * @param lhsType the type to which the lambda is being assigned * @param lambda The lambda argument * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This @@ -3004,6 +3009,8 @@ public void compareGenericTypeParameterNullabilityForCall( handler)) { Type groundFormalParameter = GenericsUtils.groundTargetType(formalParameter, state, config, handler); + inferMethodReferenceTypeArguments( + memberReferenceTree, groundFormalParameter, actualParameterAndState.state()); GenericsUtils.processMethodRefTypeRelations( this, groundFormalParameter, @@ -3072,37 +3079,58 @@ public void compareGenericTypeParameterNullabilityForCall( } /** - * For a generic method reference, if it is being called in a context that requires type argument - * nullability inference, return the method type with inferred nullability for type parameters. - * Otherwise, return the original method type. + * Infers a generic method reference's type argument nullability from its known target type before + * checking argument compatibility. References already handled by enclosing generic call inference + * retain that joint solution. Resolving a reference while generating constraints only reads + * cached solutions, so it cannot recursively start this inference. + * + *

Called only during invocation checking, after dataflow and speculative inference, so the + * result can be cached for subsequent method-reference checks. + */ + private void inferMethodReferenceTypeArguments( + MemberReferenceTree tree, Type targetType, VisitorState state) { + Symbol.MethodSymbol referencedMethod = castToNonNull(ASTHelpers.getSymbol(tree)); + // javac represents omitted method-reference type arguments with null, not an empty list. + if (!(referencedMethod.type instanceof Type.ForAll) + || tree.getTypeArguments() != null + || inferredTypeVarNullabilityForGenericCalls.containsKey(tree)) { + return; + } + ConstraintSolver solver = makeSolver(state, analysis); + CallInferenceResult result; + try { + handleMethodRefInGenericMethodInference(state, solver, targetType, tree); + result = new InferenceSuccess(solver.solve(), new IdentityHashMap<>()); + } catch (UnsatisfiableConstraintsException e) { + String message = inferenceFailureMessage(e, new IdentityHashMap<>()); + reportInferenceFailure(tree, message, state); + result = new InferenceFailure(message); + } + inferredTypeVarNullabilityForGenericCalls.put(tree, result); + } + + /** + * Returns a generic method reference's method type with type parameter nullability from a cached + * successful inference result, or the original method type when no successful result is cached. * * @param methodType the original method type * @param state the visitor state (generic method reference should be leaf of {@code * state.getPath()}) - * @return the method type with inferred nullability for type parameters if inference was - * performed, or the original method type otherwise + * @return the method type with type parameter nullability from a cached successful inference + * result, or {@code methodType} when no successful result is cached */ private Type.MethodType getInferredMethodTypeForGenericMethodReference( Type.MethodType methodType, VisitorState state) { - TreePath parentPath = state.getPath().getParentPath(); - while (parentPath != null && parentPath.getLeaf() instanceof ParenthesizedTree) { - parentPath = parentPath.getParentPath(); - } - Tree parentTree = parentPath != null ? parentPath.getLeaf() : null; - if (parentTree instanceof MethodInvocationTree methodInvocationTree - && isCallNeedingInference(methodInvocationTree)) { - CallInferenceResult inferenceResult = - inferredTypeVarNullabilityForGenericCalls.get(methodInvocationTree); - if (inferenceResult instanceof InferenceSuccess successResult) { - // the referenced method's type variables are inferred at the method reference itself - Tree memberReferenceTree = state.getPath().getLeaf(); - return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability( - methodType, - methodType, - successResult.typeVarNullabilityForSite(memberReferenceTree), - state, - config); - } + Tree memberReferenceTree = state.getPath().getLeaf(); + CallInferenceResult inferenceResult = + inferredTypeVarNullabilityForGenericCalls.get(memberReferenceTree); + if (inferenceResult instanceof InferenceSuccess successResult) { + return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability( + methodType, + methodType, + successResult.typeVarNullabilityForSite(memberReferenceTree), + state, + config); } return methodType; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 1db7695fa4..f11b1794a2 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -79,6 +79,150 @@ static void nonNullCapturedElementRead(Both value) { .doTest(); } + /** + * Regression for issue 2063: generic method references accepting marked or unmarked publishers + * with wildcard type arguments infer successfully both inline and when assigned first. + */ + @Test + public void issue2063InlineGenericMethodReference() { + makeHelper() + .addSourceLines( + "com/uber/marked/MarkedPublisherRepro.java", + """ + package com.uber.marked; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class MarkedPublisherRepro { + interface Publisher {} + static class Mono implements Publisher { + static Mono from(Publisher source) { + return new Mono<>(); + } + } + Function, Object> assigned = Mono::from; + static void register(Function, Object> adapter) {} + static void registerGeneric(Function, Object> adapter) {} + static class Adapter { + Adapter(Function, Object> adapter) {} + } + void inlineReference() { register(Mono::from); } + void parenthesizedReference() { register((Mono::from)); } + void constructorArgument() { new Adapter(Mono::from); } + void explicitTypeArgument() { register(Mono::<@Nullable Object>from); } + void lambda() { register(source -> Mono.from(source)); } + void assignedReference() { + Function, Object> adapter = Mono::from; + register(adapter); + } + void genericEnclosingCall() { registerGeneric(Mono::from); } + void explicitEnclosingTypeArgument() { MarkedPublisherRepro.registerGeneric(Mono::from); } + } + """) + .addSourceLines( + "com/uber/unmarked/UnmarkedPublisherRepro.java", + """ + package com.uber.unmarked; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class UnmarkedPublisherRepro { + @NullUnmarked interface Publisher {} + static class Mono implements Publisher { + static Mono from(Publisher source) { + return new Mono<>(); + } + } + Function, Object> assigned = Mono::from; + static void register(Function, Object> adapter) {} + static void registerGeneric(Function, Object> adapter) {} + static class Adapter { + Adapter(Function, Object> adapter) {} + } + void inlineReference() { register(Mono::from); } + void parenthesizedReference() { register((Mono::from)); } + void constructorArgument() { new Adapter(Mono::from); } + void explicitTypeArgument() { register(Mono::<@Nullable Object>from); } + void lambda() { register(source -> Mono.from(source)); } + void assignedReference() { + Function, Object> adapter = Mono::from; + register(adapter); + } + void genericEnclosingCall() { registerGeneric(Mono::from); } + void explicitEnclosingTypeArgument() { UnmarkedPublisherRepro.registerGeneric(Mono::from); } + } + """) + .doTest(); + } + + /** + * Generic method references infer nullability from known functional interface targets for static, + * bound, unbound, and varargs methods, rejecting conflicting constraints and preserving explicit + * type arguments. + */ + @Test + public void genericMethodReferenceInferenceAgainstKnownTarget() { + makeHelper() + .addSourceLines( + "Test.java", + """ + package com.uber; + import java.util.function.BiFunction; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class Factory { + Box box(T value) { return new Box<>(); } + } + static Box box(T value) { return new Box<>(); } + static Box nonNullBox(T value) { return new Box<>(); } + @SafeVarargs + static Box varargsBox(T... values) { + return new Box<>(); + } + static void acceptsNonNull(Function> function) {} + static void acceptsNullable( + Function<@Nullable String, Box<@Nullable String>> function) {} + static void acceptsBoth(Function> first, + Function<@Nullable String, Box<@Nullable String>> second) {} + static void acceptsUnbound( + BiFunction> function) {} + static void acceptsArray( + Function<@Nullable String[], Box<@Nullable String>> function) {} + static void acceptsIncompatible(Function<@Nullable String, Box> function) {} + void nonNullInputAndReturn() { acceptsNonNull(Test::box); } + void nullableInputAndReturn() { acceptsNullable(Test::box); } + void nonNullBoundWithNonNullInput() { acceptsNonNull(Test::nonNullBox); } + void boundReference(Factory factory) { acceptsNullable(factory::box); } + void unboundReference() { acceptsUnbound(Factory::box); } + void variableArityReference() { acceptsNullable(Test::varargsBox); } + void fixedArityReference() { acceptsArray(Test::varargsBox); } + void referencesAreInferredSeparately() { + acceptsBoth(Test::box, Test::box); + } + void incompatibleInputAndReturn() { + // BUG: Diagnostic contains: inference failure: type variable T constrained to be both + acceptsIncompatible(Test::box); + } + void nonNullBoundWithNullableInput() { + // BUG: Diagnostic contains: inference failure: type variable T is constrained to be @Nullable + acceptsNullable(Test::nonNullBox); + } + void explicitTypeArgumentIsPreserved() { + // BUG: Diagnostic contains: parameter value of referenced method is @NonNull + acceptsNullable(Test::box); + } + } + """) + .doTest(); + } + @Test public void voidCompatibleLambdaDiscardsNullableGenericResult() { makeHelper() From 04a6cb24d3079fc5319d85f9cb16df88cd03c5bc Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Wed, 18 Nov 2026 13:18:50 -0800 Subject: [PATCH 02/27] Suppress method reference compatibility errors after inference failure An unsatisfiable method-reference target reports an inference failure and then checks the uninferred signature, producing additional compatibility diagnostics such as "parameter value of referenced method is @NonNull". Give the inference diagnostic precedence over all parameter and return compatibility checks for the reference. A failed joint inference run suppresses these checks for every participating reference, including positions and references with independent mismatches. This deliberately avoids tracking inference dependencies for individual comparisons. Keep compatibility checks enabled when inference warnings are disabled. Assisted-by: Codex (gpt-6) --- .../main/java/com/uber/nullaway/NullAway.java | 3 + .../nullaway/generics/GenericsChecks.java | 48 +++++-- ...enericMethodLambdaOrMethodRefArgTests.java | 130 ++++++++++++++++-- 3 files changed, 151 insertions(+), 30 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java index 88be8aa7f3..524a098d4d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java @@ -1592,6 +1592,9 @@ private Description checkOverriding( VisitorState state) { ResolvedMethodReference resolvedReference = null; if (memberReferenceTree != null) { + if (genericsChecks.hasReportedInferenceFailure(memberReferenceTree)) { + return Description.NO_MATCH; + } Type functionalInterfaceType = genericsChecks.getPolyExpressionType(memberReferenceTree); if (functionalInterfaceType != null) { // diff-coverage: ignore -- Unattributed javac tree. resolvedReference = diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index a93e358f1c..8e4e6d3426 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -3011,22 +3011,24 @@ public void compareGenericTypeParameterNullabilityForCall( GenericsUtils.groundTargetType(formalParameter, state, config, handler); inferMethodReferenceTypeArguments( memberReferenceTree, groundFormalParameter, actualParameterAndState.state()); - GenericsUtils.processMethodRefTypeRelations( - this, - groundFormalParameter, - memberReferenceTree, - actualParameterAndState.state(), - (subtype, supertype, relationKind) -> { - if (!subtypeParameterNullability(supertype, subtype, state)) { - if (relationKind == MethodRefTypeRelationKind.RETURN) { - reportInvalidMethodReferenceReturnTypeError( - memberReferenceTree, supertype, subtype, state); - } else { - reportInvalidMethodReferenceParameterTypeError( - memberReferenceTree, subtype, supertype, state); + if (!hasReportedInferenceFailure(memberReferenceTree)) { + GenericsUtils.processMethodRefTypeRelations( + this, + groundFormalParameter, + memberReferenceTree, + actualParameterAndState.state(), + (subtype, supertype, relationKind) -> { + if (!subtypeParameterNullability(supertype, subtype, state)) { + if (relationKind == MethodRefTypeRelationKind.RETURN) { + reportInvalidMethodReferenceReturnTypeError( + memberReferenceTree, supertype, subtype, state); + } else { + reportInvalidMethodReferenceParameterTypeError( + memberReferenceTree, subtype, supertype, state); + } } - } - }); + }); + } } maybeStorePolyExpressionTypeFromTarget( actualParameterWithoutParentheses, formalParameter, state); @@ -3109,6 +3111,22 @@ private void inferMethodReferenceTypeArguments( inferredTypeVarNullabilityForGenericCalls.put(tree, result); } + /** + * Returns whether inference for this reference failed with a reported diagnostic, possibly from + * an enclosing joint inference run. + * + *

Callers deliberately skip all parameter and return compatibility checks for such a + * reference, including positions unrelated to inferred type variables. A failed joint inference + * run applies this policy to every participating reference, even one with an independent + * mismatch. The inference diagnostic takes precedence, avoiding misleading errors from uninferred + * types without tracking inference dependencies for individual comparisons. When inference + * warnings are disabled, compatibility checks remain enabled. + */ + public boolean hasReportedInferenceFailure(MemberReferenceTree tree) { + return config.warnOnGenericInferenceFailure() + && inferredTypeVarNullabilityForGenericCalls.get(tree) instanceof InferenceFailure; + } + /** * Returns a generic method reference's method type with type parameter nullability from a cached * successful inference result, or the original method type when no successful result is cached. diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index f11b1794a2..3306b2ba43 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -1,9 +1,14 @@ package com.uber.nullaway.jspecify; +import static com.google.common.truth.Truth.assertThat; + import com.google.errorprone.CompilationTestHelper; +import com.google.errorprone.FileObjects; import com.uber.nullaway.NullAwayTestsBase; import com.uber.nullaway.generics.JSpecifyJavacConfig; import java.util.Arrays; +import java.util.List; +import javax.tools.JavaFileObject; import org.junit.Ignore; import org.junit.Test; @@ -158,15 +163,49 @@ void assignedReference() { .doTest(); } - /** - * Generic method references infer nullability from known functional interface targets for static, - * bound, unbound, and varargs methods, rejecting conflicting constraints and preserving explicit - * type arguments. - */ @Test - public void genericMethodReferenceInferenceAgainstKnownTarget() { - makeHelper() - .addSourceLines( + public void genericMethodReferenceInferenceFailureReportsNoCompatibilityErrors() { + assertThat(compileGenericMethodReferenceDiagnostics(true)) + .containsExactly( + "Test.java:43: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", + "Test.java:47: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", + "Test.java:51: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:55: [NullAway] referenced method returns Box, but functional interface method returns Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:55: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:61: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:79: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", + "Test.java:83: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.BiFunction.apply(@Nullable String,@Nullable String) is @Nullable", + "Test.java:87: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", + "Test.java:91: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:98: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); + } + + @Test + public void genericMethodReferenceCompatibilityCheckedWhenInferenceWarningsDisabled() { + assertThat(compileGenericMethodReferenceDiagnostics(false)) + .containsExactly( + "Test.java:43: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:47: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:51: [NullAway] referenced method returns Box, but functional interface method returns Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:51: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:55: [NullAway] referenced method returns Box, but functional interface method returns Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:55: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:61: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:79: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.BiFunction.apply(@Nullable String,@Nullable String) is @Nullable", + "Test.java:83: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.BiFunction.apply(@Nullable String,@Nullable String) is @Nullable", + "Test.java:87: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:87: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.BiFunction.apply(Box<@Nullable String>,@Nullable String) is @Nullable", + "Test.java:91: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:98: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:98: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); + } + + /** Compiles references against known targets with the requested inference-warning setting. */ + private List compileGenericMethodReferenceDiagnostics(boolean warnOnInferenceFailure) { + JavaFileObject source = + FileObjects.forSourceLines( "Test.java", """ package com.uber; @@ -181,6 +220,7 @@ static class Factory { Box box(T value) { return new Box<>(); } } static Box box(T value) { return new Box<>(); } + static Box copyBox(Box value) { return value; } static Box nonNullBox(T value) { return new Box<>(); } @SafeVarargs static Box varargsBox(T... values) { @@ -196,6 +236,8 @@ static void acceptsUnbound( static void acceptsArray( Function<@Nullable String[], Box<@Nullable String>> function) {} static void acceptsIncompatible(Function<@Nullable String, Box> function) {} + static void acceptsIncompatibleBox( + Function, Box> function) {} void nonNullInputAndReturn() { acceptsNonNull(Test::box); } void nullableInputAndReturn() { acceptsNullable(Test::box); } void nonNullBoundWithNonNullInput() { acceptsNonNull(Test::nonNullBox); } @@ -207,20 +249,78 @@ void referencesAreInferredSeparately() { acceptsBoth(Test::box, Test::box); } void incompatibleInputAndReturn() { - // BUG: Diagnostic contains: inference failure: type variable T constrained to be both + // Expect inference failure; with inference warnings disabled, a parameter mismatch. acceptsIncompatible(Test::box); } + void incompatibleNestedInputAndReturn() { + // Expect inference failure; with inference warnings disabled, a nested parameter mismatch. + acceptsIncompatibleBox(Test::copyBox); + } void nonNullBoundWithNullableInput() { - // BUG: Diagnostic contains: inference failure: type variable T is constrained to be @Nullable + // Expect inference failure; with inference warnings disabled, return and parameter mismatches. acceptsNullable(Test::nonNullBox); } void explicitTypeArgumentIsPreserved() { - // BUG: Diagnostic contains: parameter value of referenced method is @NonNull + // Expect return and parameter mismatches; the explicit type argument skips inference. acceptsNullable(Test::box); } - } - """) - .doTest(); + static @Nullable String nullableValue() { return null; } + static void acceptsNonNullResult(java.util.function.Supplier supplier) {} + void incompatibleEnclosingCall() { + // Expect inference failure; with inference warnings disabled, a nullable return mismatch. + acceptsNonNullResult(Test::nullableValue); + } + static Box boxWithFixedParameter(String fixed, T value) { + return new Box<>(); + } + static Box boxWithFixedNestedParameter(Box fixed, T value) { + return new Box<>(); + } + static void acceptsFixedParameter( + BiFunction<@Nullable String, @Nullable String, Box> function) {} + static void acceptsFixedParameterWithNullableResult( + BiFunction<@Nullable String, @Nullable String, Box<@Nullable String>> function) {} + static void acceptsFixedNestedParameter( + BiFunction, @Nullable String, Box> function) {} + static void acceptsFixedNestedParameterWithNullableResult( + BiFunction, @Nullable String, Box<@Nullable String>> function) {} + void inferenceFailureSuppressesUnrelatedParameterMismatch() { + // Expect only inference failure; with inference warnings disabled, a mismatch for fixed. + acceptsFixedParameter(Test::boxWithFixedParameter); + } + void successfulInferenceReportsUnrelatedParameterMismatch() { + // Expect a parameter mismatch: fixed requires non-null, but the interface allows null. + acceptsFixedParameterWithNullableResult(Test::boxWithFixedParameter); + } + void inferenceFailureSuppressesUnrelatedNestedParameterMismatch() { + // Expect only inference failure; with inference warnings disabled, nested and value parameter mismatches. + acceptsFixedNestedParameter(Test::boxWithFixedNestedParameter); + } + void successfulInferenceReportsUnrelatedNestedParameterMismatch() { + // Expect a nested parameter mismatch: fixed requires Box, but the interface supplies Box<@Nullable String>. + acceptsFixedNestedParameterWithNullableResult(Test::boxWithFixedNestedParameter); + } + static String nonNullString(String fixed) { return fixed; } + static void acceptsPair(Function<@Nullable String, String> function, + java.util.function.Supplier supplier) {} + void failedJointInferenceSuppressesUnrelatedReferenceMismatch() { + // Expect only joint inference failure; with inference warnings disabled, parameter and return mismatches. + acceptsPair(Test::nonNullString, Test::nullableValue); + } + void successfulJointInferenceReportsUnrelatedReferenceMismatch() { + // Expect a parameter mismatch: nonNullString requires non-null, but the interface allows null. + acceptsPair(Test::nonNullString, () -> ""); + } + } + """); + return compileAndReportDiagnostics( + List.of(source), + JSpecifyJavacConfig.withJSpecifyModeArgs( + Arrays.asList( + "-d", + temporaryFolder.getRoot().getAbsolutePath(), + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=" + warnOnInferenceFailure))); } @Test @@ -1443,7 +1543,7 @@ private T createNonNull(Function factory) { return factory.apply(new Foo() {}); } String testPositive() { - // BUG: Diagnostic contains: referenced method returns @Nullable, but functional interface method + // BUG: Diagnostic contains: inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull return createNonNull(Foo::getNullable); } @Nullable String testNegative() { From bb3f707ae1d4494b368c00aa465bd57d8a3a8474 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Wed, 18 Nov 2026 13:27:33 -0800 Subject: [PATCH 03/27] Cover generic method references in diamond constructor calls Generic method references passed to diamond constructor calls need the enclosing constructor's inferred nullability, just as references passed to generic methods do. Exercise new Holder<>(Test::box, null) so falling back to the reference's declared method type is caught. Assisted-by: Codex (gpt-6) --- .../jspecify/GenericMethodLambdaOrMethodRefArgTests.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 3306b2ba43..070b5f1f75 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -311,6 +311,12 @@ void successfulJointInferenceReportsUnrelatedReferenceMismatch() { // Expect a parameter mismatch: nonNullString requires non-null, but the interface allows null. acceptsPair(Test::nonNullString, () -> ""); } + static class Holder { + Holder(Function> function, T value) {} + } + void diamondConstructorInfersReferenceWithEnclosingCall() { + new Holder<>(Test::box, null); + } } """); return compileAndReportDiagnostics( From fb989b75a494492164d1fd9262abe1f48875b6b2 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Wed, 18 Nov 2026 13:29:58 -0800 Subject: [PATCH 04/27] Cover parameter-driven inference failures for method reference shapes Successful bound, unbound, and varargs references can infer nullability from their return targets even when parameter constraints are missing. Exercise nullable inputs against non-null type-variable bounds with Object return targets, so only the parameter relations can trigger inference failures, and retain non-null input counterparts. Assisted-by: Codex (gpt-6) --- ...enericMethodLambdaOrMethodRefArgTests.java | 42 ++++++++++++++++++- 1 file changed, 40 insertions(+), 2 deletions(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 070b5f1f75..e388beba10 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -178,7 +178,10 @@ public void genericMethodReferenceInferenceFailureReportsNoCompatibilityErrors() "Test.java:87: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", "Test.java:91: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", "Test.java:98: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", - "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); + "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:123: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:130: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:137: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull"); } @Test @@ -199,7 +202,10 @@ public void genericMethodReferenceCompatibilityCheckedWhenInferenceWarningsDisab "Test.java:91: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", "Test.java:98: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:98: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", - "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); + "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:123: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:130: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.BiFunction.apply(NonNullFactory,@Nullable String) is @Nullable", + "Test.java:137: [NullAway] parameter values of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); } /** Compiles references against known targets with the requested inference-warning setting. */ @@ -317,6 +323,38 @@ static class Holder { void diamondConstructorInfersReferenceWithEnclosingCall() { new Holder<>(Test::box, null); } + static class NonNullFactory { + Box box(T value) { return new Box<>(); } + } + @SafeVarargs + static Box nonNullVarargsBox(T... values) { return new Box<>(); } + static void acceptsNullableInput(Function<@Nullable String, Object> function) {} + static void acceptsNonNullInput(Function function) {} + static void acceptsUnboundNullableInput( + BiFunction function) {} + static void acceptsUnboundNonNullInput( + BiFunction function) {} + void boundNonNullBoundRejectsNullableInput(NonNullFactory factory) { + // Expect inference failure; with inference warnings disabled, a parameter mismatch. + acceptsNullableInput(factory::box); + } + void boundNonNullBoundAcceptsNonNullInput(NonNullFactory factory) { + acceptsNonNullInput(factory::box); + } + void unboundNonNullBoundRejectsNullableInput() { + // Expect inference failure; with inference warnings disabled, a parameter mismatch. + acceptsUnboundNullableInput(NonNullFactory::box); + } + void unboundNonNullBoundAcceptsNonNullInput() { + acceptsUnboundNonNullInput(NonNullFactory::box); + } + void varargsNonNullBoundRejectsNullableInput() { + // Expect inference failure; with inference warnings disabled, a parameter mismatch. + acceptsNullableInput(Test::nonNullVarargsBox); + } + void varargsNonNullBoundAcceptsNonNullInput() { + acceptsNonNullInput(Test::nonNullVarargsBox); + } } """); return compileAndReportDiagnostics( From 85ea7a8407a2db4943ef618710449a230894ed26 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Wed, 18 Nov 2026 13:30:17 -0800 Subject: [PATCH 05/27] Document method reference inference outcomes and no-op cases The method-reference inference contract omitted its early exits and failure reporting. Describe inference from the functional-interface target, cached results from enclosing calls, and failure diagnostics without relying on assumptions about its caller. Assisted-by: Codex (gpt-6) --- .../com/uber/nullaway/generics/GenericsChecks.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 8e4e6d3426..a69eeb3892 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -3081,13 +3081,13 @@ public void compareGenericTypeParameterNullabilityForCall( } /** - * Infers a generic method reference's type argument nullability from its known target type before - * checking argument compatibility. References already handled by enclosing generic call inference - * retain that joint solution. Resolving a reference while generating constraints only reads - * cached solutions, so it cannot recursively start this inference. - * - *

Called only during invocation checking, after dataflow and speculative inference, so the - * result can be cached for subsequent method-reference checks. + * Infers the nullability of the omitted type arguments of a generic method reference from its + * functional-interface target type, and caches the result for the reference. Does nothing for a + * reference to a non-generic method, a reference with explicit type arguments, or a reference + * that already has a cached result, such as one inferred together with an enclosing generic call. + * When the target's constraints cannot be satisfied, caches the failure and reports it at the + * reference if inference warnings are enabled. Constraint generation only reads cached results, + * so it never starts this inference. */ private void inferMethodReferenceTypeArguments( MemberReferenceTree tree, Type targetType, VisitorState state) { From 3d65086ce2f401ad64c0da47290f537c81c53d06 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Wed, 18 Nov 2026 13:34:04 -0800 Subject: [PATCH 06/27] Guard method reference inference cache writes Method-reference inference currently runs without provisional lambda parameter types, but its cache write should honor the same policy as other inference paths. Guard success and failure writes with okToCacheInferenceResult(false) so a future caller using provisional parameter types cannot persist its result. The path that skips caching is defensive and unreachable from the current invocation-checking caller. Assisted-by: Codex (gpt-6) --- .../uber/nullaway/generics/GenericsChecks.java | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index a69eeb3892..9ea0b66e9b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -3082,12 +3082,13 @@ public void compareGenericTypeParameterNullabilityForCall( /** * Infers the nullability of the omitted type arguments of a generic method reference from its - * functional-interface target type, and caches the result for the reference. Does nothing for a - * reference to a non-generic method, a reference with explicit type arguments, or a reference - * that already has a cached result, such as one inferred together with an enclosing generic call. - * When the target's constraints cannot be satisfied, caches the failure and reports it at the - * reference if inference warnings are enabled. Constraint generation only reads cached results, - * so it never starts this inference. + * functional-interface target type, and caches the result for the reference when {@link + * #okToCacheInferenceResult(boolean)} permits it. Does nothing for a reference to a non-generic + * method, a reference with explicit type arguments, or a reference that already has a cached + * result, such as one inferred together with an enclosing generic call. When the target's + * constraints cannot be satisfied, reports an inference failure at the reference if inference + * warnings are enabled and caches the failure under the same policy. Constraint generation only + * reads cached results, so it never starts this inference. */ private void inferMethodReferenceTypeArguments( MemberReferenceTree tree, Type targetType, VisitorState state) { @@ -3108,7 +3109,9 @@ private void inferMethodReferenceTypeArguments( reportInferenceFailure(tree, message, state); result = new InferenceFailure(message); } - inferredTypeVarNullabilityForGenericCalls.put(tree, result); + if (okToCacheInferenceResult(false)) { // diff-coverage: ignore -- No provisional types here. + inferredTypeVarNullabilityForGenericCalls.put(tree, result); + } } /** From 9211c9f7adeb12dc31e8eabd0b2659d05298b823 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Wed, 18 Nov 2026 13:34:38 -0800 Subject: [PATCH 07/27] Clarify caching of method references with explicit type arguments The cache contract did not identify whose explicit type arguments constrain an enclosing call or whether the corresponding reference is a key. State that method references with explicit type arguments remain keys when their types constrain an enclosing generic call. Assisted-by: Codex (gpt-6) --- .../main/java/com/uber/nullaway/generics/GenericsChecks.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 9ea0b66e9b..058aa3d822 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -139,8 +139,9 @@ private InferenceFailure(@Nullable String errorMessage) { /** * Maps each call or method reference that took part in a generic inference run to that run's - * result. Only omitted type arguments are inferred; explicit arguments can still constrain an - * enclosing call. If a tree is absent, no inference result has been cached for that site. + * result. Only omitted type arguments are inferred, but a method reference with explicit type + * arguments is still a key when its types constrain an enclosing generic call. If a tree is + * absent, no inference result has been cached for that site. */ private final Map inferredTypeVarNullabilityForGenericCalls = new LinkedHashMap<>(); From 1496fce63cea4084a4f5e3d29a43a22db3f7754c Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Fri, 20 Nov 2026 16:07:54 -0800 Subject: [PATCH 08/27] Preserve independent method reference errors after inference failure When WarnOnGenericInferenceFailure is enabled, a failed joint inference run suppresses override diagnostics for every method reference argument, including references whose checks do not depend on the run. An error in another argument can therefore hide a valid WRONG_OVERRIDE_PARAM or WRONG_OVERRIDE_RETURN diagnostic. Share the cached inference result only with references that infer omitted generic method type arguments or whose ground target type mentions an inference variable registered with the solver. Independent references retain their parameter and return compatibility checks. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4645819263 Assisted-by: Codex (gpt-6) --- .../nullaway/generics/ConstraintSolver.java | 7 +++ .../generics/ConstraintSolverImpl.java | 8 ++++ .../nullaway/generics/GenericsChecks.java | 46 +++++++++++-------- .../generics/TypeVarWithSymbolCollector.java | 14 ++++-- ...enericMethodLambdaOrMethodRefArgTests.java | 43 +++++++++++++++-- 5 files changed, 91 insertions(+), 27 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index 22c3965821..94151a0a07 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -48,6 +48,13 @@ record InferenceVariable(Element typeVariable, Tree site) {} Map registerInferenceVariables( Tree site, List typeVariables); + /** + * Returns whether {@code type}, including its nested types and bounds, mentions a fresh type + * variable registered with this solver. Fresh variables from other inference runs are fixed types + * for this query. + */ + boolean containsInferenceVariable(Type type); + /** * Exception thrown when the constraints added to the solver are determined to be unsatisfiable. * diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java index bc0f890944..667c0c070b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -123,6 +123,14 @@ public Map registerInferenceVariables( return fresh; } + @Override + public boolean containsInferenceVariable(Type type) { + TypeVarWithSymbolCollector collector = + new TypeVarWithSymbolCollector(inferenceVariables::containsKey); + type.accept(collector, null); + return !collector.getMatches().isEmpty(); + } + @Override public void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType) throws UnsatisfiableConstraintsException { diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 058aa3d822..e59733d79a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1491,8 +1491,8 @@ private CallInferenceResult runInferenceForCall( boolean assignedToLocal, boolean calledFromDataflow) { ConstraintSolver solver = makeSolver(state, analysis); - // allCalls tracks the top-level call, nested calls requiring inference, and every method - // reference whose functional-interface type constrains the run. + // allCalls tracks the top-level call, nested calls requiring inference, and method + // references whose checks depend on variables solved by this run. Set allCalls = new LinkedHashSet<>(); allCalls.add(callTree); IdentityHashMap polyNullContexts = @@ -1671,9 +1671,9 @@ private Symbol.MethodSymbol getMethodSymbolForCall(ExpressionTree callTree) { * @param callTree the call tree representing the generic method call or diamond constructor call * @param methodType the executable type of {@code callTree}, as computed by {@link * #getExecutableTypeForInference} - * @param allCalls the top-level call, nested calls requiring inference, and every method - * reference whose functional-interface type constrains the run. This is an output parameter - * that gets mutated while generating the constraints to add nested sites. + * @param allCalls the top-level call, nested calls requiring inference, and method references + * whose checks depend on variables solved by this run. This is an output parameter that gets + * mutated while generating the constraints to add nested sites. * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This * is an output parameter mutated during constraint generation to add contexts for modeled * calls. @@ -1779,9 +1779,9 @@ private void generateConstraintsForCall( * * @param state the visitor state * @param solver the constraint solver - * @param allCalls the top-level call, nested calls requiring inference, and every method - * reference whose functional-interface type constrains the run. This is an output parameter - * that gets mutated while generating the constraints to add nested sites. + * @param allCalls the top-level call, nested calls requiring inference, and method references + * whose checks depend on variables solved by this run. This is an output parameter that gets + * mutated while generating the constraints to add nested sites. * @param rhsExpr the right-hand side expression of the pseudo-assignment * @param lhsType the left-hand side type of the pseudo-assignment * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This @@ -1850,8 +1850,8 @@ private void generateConstraintsForPseudoAssignment( polyNullContexts, calledFromDataflow); } else if (rhsExpr instanceof MemberReferenceTree memberReferenceTree) { - allCalls.add(memberReferenceTree); - handleMethodRefInGenericMethodInference(state, solver, lhsType, memberReferenceTree); + handleMethodRefInGenericMethodInference( + state, solver, lhsType, memberReferenceTree, allCalls); } else { // all other cases Type argumentType = getTreeType(rhsExpr, state, calledFromDataflow); if (argumentType == null) { @@ -1879,9 +1879,9 @@ private void generateConstraintsForPseudoAssignment( * @param path the tree path to the enclosing call if available and possibly distinct from {@code * state.getPath()} * @param solver the constraint solver - * @param allCalls the top-level call, nested calls requiring inference, and every method - * reference whose functional-interface type constrains the run. This is an output parameter - * that gets mutated while generating the constraints to add nested sites. + * @param allCalls the top-level call, nested calls requiring inference, and method references + * whose checks depend on variables solved by this run. This is an output parameter that gets + * mutated while generating the constraints to add nested sites. * @param lhsType the type to which the lambda is being assigned * @param lambda The lambda argument * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This @@ -1988,12 +1988,15 @@ private void handleLambdaInGenericMethodInference( * @param solver the constraint solver * @param lhsType the type to which the method reference is being assigned * @param memberReferenceTree the method reference argument + * @param allCalls output parameter for sites sharing this run's inference result, or {@code null} + * for standalone method reference inference */ private void handleMethodRefInGenericMethodInference( VisitorState state, ConstraintSolver solver, Type lhsType, - MemberReferenceTree memberReferenceTree) { + MemberReferenceTree memberReferenceTree, + @Nullable Set allCalls) { // if we have a reference to a generic method, and the call site does not pass explicit type // arguments, register the referenced method's type variables as inference variables Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(memberReferenceTree); @@ -2009,6 +2012,10 @@ private void handleMethodRefInGenericMethodInference( inferenceVariables = Map.of(); } Type groundTargetType = GenericsUtils.groundTargetType(lhsType, state, config, handler); + if (allCalls != null + && (!inferenceVariables.isEmpty() || solver.containsInferenceVariable(groundTargetType))) { + allCalls.add(memberReferenceTree); + } GenericsUtils.processMethodRefTypeRelations( this, groundTargetType, @@ -3103,7 +3110,7 @@ private void inferMethodReferenceTypeArguments( ConstraintSolver solver = makeSolver(state, analysis); CallInferenceResult result; try { - handleMethodRefInGenericMethodInference(state, solver, targetType, tree); + handleMethodRefInGenericMethodInference(state, solver, targetType, tree, null); result = new InferenceSuccess(solver.solve(), new IdentityHashMap<>()); } catch (UnsatisfiableConstraintsException e) { String message = inferenceFailureMessage(e, new IdentityHashMap<>()); @@ -3121,10 +3128,11 @@ private void inferMethodReferenceTypeArguments( * *

Callers deliberately skip all parameter and return compatibility checks for such a * reference, including positions unrelated to inferred type variables. A failed joint inference - * run applies this policy to every participating reference, even one with an independent - * mismatch. The inference diagnostic takes precedence, avoiding misleading errors from uninferred - * types without tracking inference dependencies for individual comparisons. When inference - * warnings are disabled, compatibility checks remain enabled. + * run applies this policy only to references with omitted generic method type arguments or a + * ground target type mentioning a variable solved by that run. Independent references keep their + * compatibility checks. The inference diagnostic takes precedence for dependent references, + * avoiding misleading errors from uninferred types without tracking dependencies for individual + * comparisons. When inference warnings are disabled, compatibility checks remain enabled. */ public boolean hasReportedInferenceFailure(MemberReferenceTree tree) { return config.warnOnGenericInferenceFailure() diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/TypeVarWithSymbolCollector.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypeVarWithSymbolCollector.java index ee995e7941..3f2361463c 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeVarWithSymbolCollector.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeVarWithSymbolCollector.java @@ -14,11 +14,12 @@ import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; +import java.util.function.Predicate; import javax.lang.model.element.Element; import org.jspecify.annotations.Nullable; /** - * Visitor that collects every TypeVar whose symbol is the given Element. + * Visitor that collects every TypeVar whose symbol matches a given Element or predicate. * *

Usage: * @@ -33,11 +34,16 @@ public final class TypeVarWithSymbolCollector extends Types.DefaultTypeVisitor<@Nullable Void, @Nullable Void> { - private final Element symbol; + private final Predicate symbolPredicate; private final Set matches = new LinkedHashSet<>(); public TypeVarWithSymbolCollector(Element symbol) { - this.symbol = symbol; + this(candidate -> Objects.equals(candidate, symbol)); + } + + /** Collects type variables whose symbols satisfy {@code symbolPredicate}. */ + TypeVarWithSymbolCollector(Predicate symbolPredicate) { + this.symbolPredicate = symbolPredicate; } private final Set seen = java.util.Collections.newSetFromMap(new IdentityHashMap<>()); @@ -57,7 +63,7 @@ public Set getMatches() { // ---- Core matching logic ---- @Override public @Nullable Void visitTypeVar(TypeVar t, @Nullable Void p) { - if (Objects.equals(t.tsym, symbol)) { + if (symbolPredicate.test(t.tsym)) { matches.add(t); } scan(t.getUpperBound()); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index e388beba10..ff960d5c5b 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -178,10 +178,18 @@ public void genericMethodReferenceInferenceFailureReportsNoCompatibilityErrors() "Test.java:87: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", "Test.java:91: [NullAway] parameter type of referenced method is Box, but parameter in functional interface method has type Box<@Nullable String>, which has mismatched type parameter nullability", "Test.java:98: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:98: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:123: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", "Test.java:130: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", - "Test.java:137: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull"); + "Test.java:137: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:146: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:146: [NullAway] incompatible types: Box<@Nullable String> cannot be converted to Box", + "Test.java:146: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:150: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:150: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:153: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:159: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull"); } @Test @@ -205,7 +213,15 @@ public void genericMethodReferenceCompatibilityCheckedWhenInferenceWarningsDisab "Test.java:102: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:123: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:130: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.BiFunction.apply(NonNullFactory,@Nullable String) is @Nullable", - "Test.java:137: [NullAway] parameter values of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); + "Test.java:137: [NullAway] parameter values of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:146: [NullAway] incompatible types: Box<@Nullable String> cannot be converted to Box", + "Test.java:146: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:150: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:150: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:153: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:153: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:159: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:159: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull"); } /** Compiles references against known targets with the requested inference-warning setting. */ @@ -309,8 +325,8 @@ void successfulInferenceReportsUnrelatedNestedParameterMismatch() { static String nonNullString(String fixed) { return fixed; } static void acceptsPair(Function<@Nullable String, String> function, java.util.function.Supplier supplier) {} - void failedJointInferenceSuppressesUnrelatedReferenceMismatch() { - // Expect only joint inference failure; with inference warnings disabled, parameter and return mismatches. + void failedJointInferenceReportsIndependentReferenceMismatch() { + // Expect a parameter mismatch and joint inference failure; without inference warnings, a return mismatch too. acceptsPair(Test::nonNullString, Test::nullableValue); } void successfulJointInferenceReportsUnrelatedReferenceMismatch() { @@ -355,6 +371,25 @@ void varargsNonNullBoundRejectsNullableInput() { void varargsNonNullBoundAcceptsNonNullInput() { acceptsNonNullInput(Test::nonNullVarargsBox); } + static void unrelated(java.util.function.Supplier supplier, + Box first, Box second) {} + void failedJointInferenceReportsIndependentReturnMismatch( + Box<@Nullable String> nullable, Box nonNull) { + unrelated(Test::nullableValue, nullable, nonNull); + } + static String genericString(String fixed) { return fixed; } + void failedJointInferenceReportsExplicitReferenceMismatch() { + acceptsPair(Test::genericString, Test::nullableValue); + } + void failedJointInferenceSuppressesGenericReferenceMismatch() { + acceptsPair(Test::genericString, Test::nullableValue); + } + static Box fixedBox(String fixed) { return new Box<>(); } + static void acceptsNestedPair(Function<@Nullable String, Box> function, + java.util.function.Supplier supplier) {} + void failedJointInferenceSuppressesNestedDependentReferenceMismatch() { + acceptsNestedPair(Test::fixedBox, Test::nullableValue); + } } """); return compileAndReportDiagnostics( From 4a4238b5ffc24f2937f8499e4c793cb6ad96f480 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Fri, 20 Nov 2026 16:09:03 -0800 Subject: [PATCH 09/27] Document override suppression after method reference inference failure The checkOverriding return contract says NO_MATCH means no error, but a method reference with a reported inference failure also skips override diagnostics. Describe that exception and link GenericsChecks.hasReportedInferenceFailure for the suppression policy. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4645819269 Assisted-by: Codex (gpt-6) --- nullaway/src/main/java/com/uber/nullaway/NullAway.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java index 524a098d4d..3432f1f095 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java @@ -1582,7 +1582,9 @@ public Description matchMemberReference(MemberReferenceTree tree, VisitorState s * @param memberReferenceTree if override is via a method reference, the relevant {@link * MemberReferenceTree}; otherwise {@code null} * @param state visitor state. - * @return discovered error, or {@link Description#NO_MATCH} if no error + * @return discovered error, or {@link Description#NO_MATCH} if no error is found or a method + * reference's inference failure has already been reported, as determined by {@link + * GenericsChecks#hasReportedInferenceFailure(MemberReferenceTree)} */ private Description checkOverriding( Symbol.MethodSymbol overriddenMethod, From d6fe2b2cff43e65c502961514da42c24fb8921c8 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Fri, 20 Nov 2026 16:11:11 -0800 Subject: [PATCH 10/27] Pin inference diagnostics to the failing method reference Existing diagnostic cases put each call and its method references on one line, so a failure reported at the enclosing call or a different argument goes undetected. Add a call with two references on separate lines and require the inference diagnostic on the failing reference's line. Check the compatibility diagnostics at that reference when inference warnings are disabled. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4645819284 Assisted-by: Codex (gpt-6) --- .../GenericMethodLambdaOrMethodRefArgTests.java | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index ff960d5c5b..12b07f7c99 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -189,7 +189,8 @@ public void genericMethodReferenceInferenceFailureReportsNoCompatibilityErrors() "Test.java:150: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", "Test.java:150: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:153: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", - "Test.java:159: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull"); + "Test.java:159: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:164: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull"); } @Test @@ -221,7 +222,9 @@ public void genericMethodReferenceCompatibilityCheckedWhenInferenceWarningsDisab "Test.java:153: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:153: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", "Test.java:159: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", - "Test.java:159: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull"); + "Test.java:159: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:164: [NullAway] referenced method returns Box, but functional interface method returns Box<@Nullable String>, which has mismatched type parameter nullability", + "Test.java:164: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); } /** Compiles references against known targets with the requested inference-warning setting. */ @@ -390,6 +393,11 @@ static void acceptsNestedPair(Function<@Nullable String, Box> function, void failedJointInferenceSuppressesNestedDependentReferenceMismatch() { acceptsNestedPair(Test::fixedBox, Test::nullableValue); } + void inferenceFailureIsReportedAtTheFailingReference() { + acceptsBoth( + Test::box, + Test::nonNullBox); + } } """); return compileAndReportDiagnostics( From ebdc5c9a857e4ed95d14e8492a59f1ef6a229a9f Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Tue, 24 Nov 2026 16:26:03 -0800 Subject: [PATCH 11/27] Defer nullness inference failures until constraint collection finishes A contradiction could stop constraint generation before a later method reference joined the enclosing call's inference run. The reference could then report a second `inference failure` from standalone inference or a compatibility warning that depended on the failed inference. Save the first contradiction in the solver and report it from solve(). This lets the remaining dependent references share the call's failure while preserving the original diagnostic for the call. Refs: https://github.com/uber/NullAway/pull/2175#discussion_r4679457905 Assisted-by: Codex (gpt-6) --- .../nullaway/generics/ConstraintSolver.java | 6 +- .../generics/ConstraintSolverImpl.java | 17 ++++- .../nullaway/generics/GenericsChecks.java | 4 +- ...enericMethodLambdaOrMethodRefArgTests.java | 73 +++++++++++++++++++ 4 files changed, 91 insertions(+), 9 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index 94151a0a07..cc60c58682 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -94,15 +94,15 @@ public boolean isCausedByNonNullUpperBound() { * must appear in the types as the fresh type variables returned by {@link * #registerInferenceVariables(Tree, List)}. * + *

Any contradiction detected while adding constraints is reported by {@link #solve()}. + * * @param subtype the subtype * @param supertype the supertype * @param localVariableType whether this constraint arises from assigning to a local variable. In * such a case, the top-level types are not constrained to be subtypes (as local variable * types are separately inferred), but the nested types are still constrained. - * @throws UnsatisfiableConstraintsException if the constraints are determined to be unsatisfiable */ - void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType) - throws UnsatisfiableConstraintsException; + void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType); enum InferredNullability { NONNULL, diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java index 667c0c070b..1157fde7d3 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -39,6 +39,7 @@ public final class ConstraintSolverImpl implements ConstraintSolver { private final Config config; private final Handler handler; private final VisitorState state; + private @Nullable UnsatisfiableConstraintsException deferredFailure; /** * Maps the symbol of each fresh type variable created by {@link #registerInferenceVariables(Tree, @@ -132,9 +133,16 @@ public boolean containsInferenceVariable(Type type) { } @Override - public void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType) - throws UnsatisfiableConstraintsException { - subtype.accept(new AddSubtypeConstraintsVisitor(localVariableType), supertype); + public void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType) { + if (deferredFailure != null) { + return; + } + try { + subtype.accept(new AddSubtypeConstraintsVisitor(localVariableType), supertype); + } catch (UnsatisfiableConstraintsException e) { + // Let constraint generation finish registering sites that share this inference result. + deferredFailure = e; + } } class AddSubtypeConstraintsVisitor extends Types.DefaultTypeVisitor<@Nullable Void, Type> { @@ -362,6 +370,9 @@ private void constrainWildcardToSupertype(WildcardType subtypeWildcard, Type sup @Override public Map solve() throws UnsatisfiableConstraintsException { + if (deferredFailure != null) { + throw deferredFailure; + } /* ---------- work-list propagation of nullability ---------- */ Deque work = new ArrayDeque<>(); vars.forEach( diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index e59733d79a..df23b2bce7 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1678,7 +1678,6 @@ private Symbol.MethodSymbol getMethodSymbolForCall(ExpressionTree callTree) { * is an output parameter mutated during constraint generation to add contexts for modeled * calls. * @param calledFromDataflow whether this method is being called from dataflow analysis - * @throws UnsatisfiableConstraintsException if the constraints are determined to be unsatisfiable */ private void generateConstraintsForCall( VisitorState state, @@ -1690,8 +1689,7 @@ private void generateConstraintsForCall( Type.MethodType methodType, Set allCalls, IdentityHashMap polyNullContexts, - boolean calledFromDataflow) - throws UnsatisfiableConstraintsException { + boolean calledFromDataflow) { PolyNullInferenceContext polyNullContext = null; ImmutableSet polyNullLocations = ImmutableSet.of(); if (callTree instanceof MethodInvocationTree invocationTree) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 12b07f7c99..855faee5c0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -410,6 +410,79 @@ void inferenceFailureIsReportedAtTheFailingReference() { "-XepOpt:NullAway:WarnOnGenericInferenceFailure=" + warnOnInferenceFailure))); } + @Test + public void failedJointInferenceSuppressesDependentReferenceDiagnosticsInEitherOrder() { + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true"))) + .addSourceLines( + "Test.java", + """ + import java.util.function.Function; + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + static class Box {} + static Box box(U value) { return new Box<>(); } + static Box fixedBox(String value) { return new Box<>(); } + static @Nullable String nullableValue() { return null; } + + static void refFirst(Function<@Nullable String, Box> f, Supplier s) {} + static void refLast(Supplier s, Function<@Nullable String, Box> f) {} + static void independentRefLast(Supplier s, Function<@Nullable String, Box> f) {} + static void boxLast(Supplier s, Box box) {} + static Box<@Nullable String> makeBox(Function<@Nullable String, Box> f) { + return new Box<>(); + } + + void genericReferenceFirst() { + // BUG: Diagnostic contains: inference failure + refFirst(Test::box, + Test::nullableValue); + } + + void genericReferenceLast() { + // BUG: Diagnostic contains: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull + refLast(Test::nullableValue, + Test::box); + } + + void dependentFixedReferenceFirst() { + // BUG: Diagnostic contains: inference failure + refFirst(Test::fixedBox, + Test::nullableValue); + } + + void dependentFixedReferenceLast() { + // BUG: Diagnostic contains: inference failure + refLast(Test::nullableValue, + Test::fixedBox); + } + + void independentFixedReferenceLast() { + // BUG: Diagnostic contains: inference failure + independentRefLast(Test::nullableValue, + // BUG: Diagnostic contains: parameter value of referenced method is @NonNull + Test::fixedBox); + } + + void referenceInNestedCallLast() { + // BUG: Diagnostic contains: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull + boxLast(Test::nullableValue, + // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + makeBox( + Test::box)); + } + } + """) + .doTest(); + } + @Test public void voidCompatibleLambdaDiscardsNullableGenericResult() { makeHelper() From 2253529b7dbde06679dec5e7138f5967b7aae2f6 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Tue, 24 Nov 2026 16:51:16 -0800 Subject: [PATCH 12/27] Document which method references share cached inference results The inference cache Javadoc implied that every method-reference argument shared the enclosing result. Describe when a reference depends on an inference variable so readers can tell which references share a cached failure. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4679457914 Assisted-by: Codex (gpt-6) --- .../java/com/uber/nullaway/generics/GenericsChecks.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index df23b2bce7..5007cf2f62 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -138,10 +138,10 @@ private InferenceFailure(@Nullable String errorMessage) { } /** - * Maps each call or method reference that took part in a generic inference run to that run's - * result. Only omitted type arguments are inferred, but a method reference with explicit type - * arguments is still a key when its types constrain an enclosing generic call. If a tree is - * absent, no inference result has been cached for that site. + * Maps each call in an inference problem and each method reference whose checks depend on the + * problem's inference variables to the problem's result. A method reference depends on them when + * it has omitted type arguments to infer or when its ground target type mentions one of them. If + * a tree is absent, no inference result has been cached for that site. */ private final Map inferredTypeVarNullabilityForGenericCalls = new LinkedHashMap<>(); From c1ba885768f7e10130792d396558ad041cbfaae1 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Tue, 24 Nov 2026 16:51:46 -0800 Subject: [PATCH 13/27] Name the inference failure test for dependent compatibility errors The test expects independent compatibility errors alongside inference failures. Name it for the suppression rule that its assertions exercise. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4679457934 Assisted-by: Codex (gpt-6) --- .../jspecify/GenericMethodLambdaOrMethodRefArgTests.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 855faee5c0..329e52408c 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -164,7 +164,7 @@ void assignedReference() { } @Test - public void genericMethodReferenceInferenceFailureReportsNoCompatibilityErrors() { + public void genericMethodReferenceInferenceFailureSuppressesOnlyDependentCompatibilityErrors() { assertThat(compileGenericMethodReferenceDiagnostics(true)) .containsExactly( "Test.java:43: [NullAway] inference failure: type variable T constrained to be both @NonNull and @Nullable", From ad70eb7003ef79df9f82675a6bc32ac613b8b8a7 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Tue, 24 Nov 2026 16:53:07 -0800 Subject: [PATCH 14/27] Cover method reference diagnostics in nested generic calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The inference failure tests did not require recognizing a nested call’s type variable in a method reference’s target. Add nested calls in which a nullable supplier depends on the nested call’s inference variable and a function’s parameter check is independent. Check the diagnostic locations with inference warnings enabled and disabled. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4679457944 Assisted-by: Codex (gpt-6) --- ...enericMethodLambdaOrMethodRefArgTests.java | 30 +++++++++++++++++-- 1 file changed, 28 insertions(+), 2 deletions(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 329e52408c..fdc480ad46 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -190,7 +190,10 @@ public void genericMethodReferenceInferenceFailureSuppressesOnlyDependentCompati "Test.java:150: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:153: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", "Test.java:159: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", - "Test.java:164: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull"); + "Test.java:164: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:176: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:181: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:183: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); } @Test @@ -224,7 +227,10 @@ public void genericMethodReferenceCompatibilityCheckedWhenInferenceWarningsDisab "Test.java:159: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", "Test.java:159: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", "Test.java:164: [NullAway] referenced method returns Box, but functional interface method returns Box<@Nullable String>, which has mismatched type parameter nullability", - "Test.java:164: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable"); + "Test.java:164: [NullAway] parameter value of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:178: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull", + "Test.java:183: [NullAway] parameter fixed of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable String) is @Nullable", + "Test.java:184: [NullAway] referenced method returns @Nullable, but functional interface method java.util.function.Supplier.get() returns @NonNull"); } /** Compiles references against known targets with the requested inference-warning setting. */ @@ -398,6 +404,26 @@ void inferenceFailureIsReportedAtTheFailingReference() { Test::box, Test::nonNullBox); } + static Box wrapSupplier( + java.util.function.Supplier supplier) { + return new Box<>(); + } + static Box wrapWithFunction( + Function<@Nullable String, String> function, java.util.function.Supplier supplier) { + return new Box<>(); + } + static void needsNonNullBox(Box box) {} + void failedJointInferenceSuppressesReferenceDependingOnNestedCall() { + needsNonNullBox( + wrapSupplier( + Test::nullableValue)); + } + void failedJointInferenceReportsIndependentReferenceInNestedCall() { + needsNonNullBox( + wrapWithFunction( + Test::nonNullString, + Test::nullableValue)); + } } """); return compileAndReportDiagnostics( From 187042840bfcdd20aeaeafd368c7d18fd0bf00e6 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Tue, 24 Nov 2026 16:53:44 -0800 Subject: [PATCH 15/27] Use consistent terminology for joint inference The method-reference comments used several names for sites whose constraints are solved together. Use inference problem and inference variables to match the solver terminology. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4679457964 Assisted-by: Codex (gpt-6) --- .../nullaway/generics/ConstraintSolver.java | 4 +- .../nullaway/generics/GenericsChecks.java | 39 ++++++++++--------- 2 files changed, 22 insertions(+), 21 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index cc60c58682..4af308c241 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -50,8 +50,8 @@ Map registerInferenceVariables( /** * Returns whether {@code type}, including its nested types and bounds, mentions a fresh type - * variable registered with this solver. Fresh variables from other inference runs are fixed types - * for this query. + * variable registered with this solver. Fresh variables from other inference problems are fixed + * types for this query. */ boolean containsInferenceVariable(Type type); diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 5007cf2f62..8c4e023eaf 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1492,7 +1492,7 @@ private CallInferenceResult runInferenceForCall( boolean calledFromDataflow) { ConstraintSolver solver = makeSolver(state, analysis); // allCalls tracks the top-level call, nested calls requiring inference, and method - // references whose checks depend on variables solved by this run. + // references whose checks depend on this problem's inference variables. Set allCalls = new LinkedHashSet<>(); allCalls.add(callTree); IdentityHashMap polyNullContexts = @@ -1672,9 +1672,9 @@ private Symbol.MethodSymbol getMethodSymbolForCall(ExpressionTree callTree) { * @param methodType the executable type of {@code callTree}, as computed by {@link * #getExecutableTypeForInference} * @param allCalls the top-level call, nested calls requiring inference, and method references - * whose checks depend on variables solved by this run. This is an output parameter that gets - * mutated while generating the constraints to add nested sites. - * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This + * whose checks depend on this problem's inference variables. This is an output parameter + * mutated during constraint generation to add nested sites. + * @param polyNullContexts PolyNull inference contexts for calls in this inference problem. This * is an output parameter mutated during constraint generation to add contexts for modeled * calls. * @param calledFromDataflow whether this method is being called from dataflow analysis @@ -1778,11 +1778,11 @@ private void generateConstraintsForCall( * @param state the visitor state * @param solver the constraint solver * @param allCalls the top-level call, nested calls requiring inference, and method references - * whose checks depend on variables solved by this run. This is an output parameter that gets - * mutated while generating the constraints to add nested sites. + * whose checks depend on this problem's inference variables. This is an output parameter + * mutated during constraint generation to add nested sites. * @param rhsExpr the right-hand side expression of the pseudo-assignment * @param lhsType the left-hand side type of the pseudo-assignment - * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This + * @param polyNullContexts PolyNull inference contexts for calls in this inference problem. This * is an output parameter mutated during constraint generation to add contexts for modeled * calls. * @param calledFromDataflow whether this method is being called from dataflow analysis @@ -1878,11 +1878,11 @@ private void generateConstraintsForPseudoAssignment( * state.getPath()} * @param solver the constraint solver * @param allCalls the top-level call, nested calls requiring inference, and method references - * whose checks depend on variables solved by this run. This is an output parameter that gets - * mutated while generating the constraints to add nested sites. + * whose checks depend on this problem's inference variables. This is an output parameter + * mutated during constraint generation to add nested sites. * @param lhsType the type to which the lambda is being assigned * @param lambda The lambda argument - * @param polyNullContexts PolyNull inference contexts for calls in this inference session. This + * @param polyNullContexts PolyNull inference contexts for calls in this inference problem. This * is an output parameter mutated during constraint generation to add contexts for modeled * calls. * @param calledFromDataflow whether this method is being called from dataflow analysis @@ -1986,8 +1986,8 @@ private void handleLambdaInGenericMethodInference( * @param solver the constraint solver * @param lhsType the type to which the method reference is being assigned * @param memberReferenceTree the method reference argument - * @param allCalls output parameter for sites sharing this run's inference result, or {@code null} - * for standalone method reference inference + * @param allCalls output parameter for sites sharing this inference problem's result, or {@code + * null} for standalone method reference inference */ private void handleMethodRefInGenericMethodInference( VisitorState state, @@ -3122,15 +3122,16 @@ private void inferMethodReferenceTypeArguments( /** * Returns whether inference for this reference failed with a reported diagnostic, possibly from - * an enclosing joint inference run. + * an enclosing inference problem. * *

Callers deliberately skip all parameter and return compatibility checks for such a - * reference, including positions unrelated to inferred type variables. A failed joint inference - * run applies this policy only to references with omitted generic method type arguments or a - * ground target type mentioning a variable solved by that run. Independent references keep their - * compatibility checks. The inference diagnostic takes precedence for dependent references, - * avoiding misleading errors from uninferred types without tracking dependencies for individual - * comparisons. When inference warnings are disabled, compatibility checks remain enabled. + * reference, including positions unrelated to inferred type variables. When joint inference + * fails, this policy applies only to references with omitted generic method type arguments or a + * ground target type mentioning one of the problem's inference variables. Independent references + * keep their compatibility checks. The inference diagnostic takes precedence for dependent + * references, avoiding misleading errors from uninferred types without tracking dependencies for + * individual comparisons. When inference warnings are disabled, compatibility checks remain + * enabled. */ public boolean hasReportedInferenceFailure(MemberReferenceTree tree) { return config.warnOnGenericInferenceFailure() From 0058c3b2d049b97e06d509c3119c4d14986e9b61 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Thu, 26 Nov 2026 15:48:52 -0800 Subject: [PATCH 16/27] fix compile error --- .../main/java/com/uber/nullaway/generics/GenericsChecks.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index a960c96014..f1bb4be2f2 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -3131,7 +3131,7 @@ private void inferMethodReferenceTypeArguments( result = new InferenceSuccess(solver.solve(), new IdentityHashMap<>()); } catch (UnsatisfiableConstraintsException e) { String message = inferenceFailureMessage(e, new IdentityHashMap<>()); - reportInferenceFailure(tree, message, state); + reportInferenceFailure(tree, message, state, false); result = new InferenceFailure(message); } if (okToCacheInferenceResult(false)) { // diff-coverage: ignore -- No provisional types here. From 83554de52c39d965093fb5aa636089ac0505aaa4 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Thu, 26 Nov 2026 16:03:23 -0800 Subject: [PATCH 17/27] Infer later nested calls separately after a contradiction Deferring a constraint contradiction lets collection visit later nested calls. Caching the enclosing failure for those calls made a valid `box(null)` report `passing @Nullable parameter 'null' where @NonNull is required`. Keep ordinary nested calls reached after a deferred contradiction eligible for separate inference. Continue registering method references so their diagnostics can depend on the enclosing inference result. Assisted-by: Codex (gpt-6) --- .../nullaway/generics/ConstraintSolver.java | 5 +++ .../generics/ConstraintSolverImpl.java | 7 +++- .../nullaway/generics/GenericsChecks.java | 9 +++-- ...enericMethodLambdaOrMethodRefArgTests.java | 39 +++++++++++++++++++ 4 files changed, 56 insertions(+), 4 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index 4af308c241..c5a257614a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -104,6 +104,11 @@ public boolean isCausedByNonNullUpperBound() { */ void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType); + /** + * Returns whether adding a constraint detected a contradiction that {@link #solve()} will report. + */ + boolean hasDeferredFailure(); + enum InferredNullability { NONNULL, NULLABLE diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java index 1157fde7d3..54d263f405 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -140,11 +140,16 @@ public void addSubtypeConstraint(Type subtype, Type supertype, boolean localVari try { subtype.accept(new AddSubtypeConstraintsVisitor(localVariableType), supertype); } catch (UnsatisfiableConstraintsException e) { - // Let constraint generation finish registering sites that share this inference result. + // Let constraint generation finish registering method references that share this result. deferredFailure = e; } } + @Override + public boolean hasDeferredFailure() { + return deferredFailure != null; + } + class AddSubtypeConstraintsVisitor extends Types.DefaultTypeVisitor<@Nullable Void, Type> { private boolean localVariableType; diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index f1bb4be2f2..b06b9e0c4d 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1492,8 +1492,8 @@ private CallInferenceResult runInferenceForCall( boolean assignedToLocal, boolean calledFromDataflow) { ConstraintSolver solver = makeSolver(state, analysis); - // allCalls tracks the top-level call, nested calls requiring inference, and method - // references whose checks depend on this problem's inference variables. + // allCalls tracks the top-level call, nested calls reached before a deferred failure, and + // method references whose checks depend on this problem's inference variables. Set allCalls = new LinkedHashSet<>(); allCalls.add(callTree); IdentityHashMap polyNullContexts = @@ -1803,7 +1803,10 @@ private void generateConstraintsForPseudoAssignment( // if the parameter is itself a generic call requiring inference, generate constraints for // that call if (isCallNeedingInference(rhsExpr)) { - allCalls.add(rhsExpr); + // Leave nested calls reached after a contradiction eligible for separate inference. + if (!solver.hasDeferredFailure()) { + allCalls.add(rhsExpr); + } generateConstraintsForCall( state, state.getPath(), diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index fdc480ad46..e1aaee2613 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -436,6 +436,45 @@ void failedJointInferenceReportsIndependentReferenceInNestedCall() { "-XepOpt:NullAway:WarnOnGenericInferenceFailure=" + warnOnInferenceFailure))); } + @Test + public void nestedCallsAfterEnclosingConstraintFailureAreInferredSeparately() { + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=false"))) + .addSourceLines( + "Test.java", + """ + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + static class Box {} + static Box box(U value) { return new Box<>(); } + static void takeBox(Box first, Box second) {} + static void takeSupplier(Box first, Supplier second) {} + + void nestedArgumentAcceptsNull(Box<@Nullable String> first) { + // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + takeBox(first, + box( + box(null))); + } + + void lambdaReturnAcceptsNull(Box<@Nullable String> first) { + // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + takeSupplier(first, () -> { + return box(null); + }); + } + } + """) + .doTest(); + } + @Test public void failedJointInferenceSuppressesDependentReferenceDiagnosticsInEitherOrder() { makeTestHelperWithArgs( From 56b63e17562493b13322a0c3e847d479c174f68e Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Thu, 26 Nov 2026 16:05:07 -0800 Subject: [PATCH 18/27] Pin diagnostics for nested calls after an inference failure An expectation for a diagnostic on a marked line can still pass when NullAway emits an extra diagnostic on that line. Check the full diagnostic set for two plain nested calls after an outer contradiction. A valid `box(null)` produces no nested diagnostic. An invalid `nn(null)` still reports its own inference failure. Assisted-by: Codex (gpt-6) --- ...enericMethodLambdaOrMethodRefArgTests.java | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index e1aaee2613..08b59daab8 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -475,6 +475,53 @@ void lambdaReturnAcceptsNull(Box<@Nullable String> first) { .doTest(); } + @Test + public void nestedCallsAfterEnclosingConstraintFailureReportTheirOwnInferenceErrors() { + JavaFileObject source = + FileObjects.forSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + static void take(T first, T second) {} + static U nn(U value) { return value; } + + void nestedCallRejectsNull(@Nullable String first) { + take(first, + nn(null)); + } + + static class Box {} + static Box box(S value) { return new Box<>(); } + static void takeBox(Box first, Box<@Nullable String> second) {} + + void nestedCallAcceptsNull(Box<@Nullable String> first) { + takeBox(first, + box(null)); + } + } + """); + assertThat( + compileAndReportDiagnostics( + List.of(source), + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-d", + temporaryFolder.getRoot().getAbsolutePath(), + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true")))) + .containsExactly( + "Test.java:10: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:10: [NullAway] passing @Nullable parameter 'first' where @NonNull is required", + "Test.java:11: [NullAway] inference failure: type variable U is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:11: [NullAway] passing @Nullable parameter 'null' where @NonNull is required", + "Test.java:19: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:19: [NullAway] incompatible types: Box<@Nullable String> cannot be converted to Box"); + } + @Test public void failedJointInferenceSuppressesDependentReferenceDiagnosticsInEitherOrder() { makeTestHelperWithArgs( From fca3a91938938cb5a603efab650be7f81a6b5a7c Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Thu, 26 Nov 2026 16:05:19 -0800 Subject: [PATCH 19/27] Document which constraint contradiction the solver reports The contract for adding constraints could be read as promising to report every contradiction. State that the solver records the first, discards later constraints, and throws the recorded failure from `solve()`. Assisted-by: Codex (gpt-6) --- .../main/java/com/uber/nullaway/generics/ConstraintSolver.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index c5a257614a..9426ffcd18 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -94,7 +94,8 @@ public boolean isCausedByNonNullUpperBound() { * must appear in the types as the fresh type variables returned by {@link * #registerInferenceVariables(Tree, List)}. * - *

Any contradiction detected while adding constraints is reported by {@link #solve()}. + *

The solver records the first contradiction detected while adding constraints and ignores + * subsequent constraints. {@link #solve()} throws the recorded contradiction. * * @param subtype the subtype * @param supertype the supertype From ae2610c4bc95d8fee812c3dbfdca5df8222899d3 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Thu, 26 Nov 2026 16:06:53 -0800 Subject: [PATCH 20/27] Share the omitted type argument check for method references Standalone and joint inference made the same decision with different checks. Use one predicate for both paths and for applying inferred nullness in the resolver. Document javac's representation of omitted type arguments at the predicate. Assisted-by: Codex (gpt-6) --- .../nullaway/generics/GenericsChecks.java | 21 +++++++++---------- 1 file changed, 10 insertions(+), 11 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index b06b9e0c4d..8209a54578 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1983,6 +1983,13 @@ private void handleLambdaInGenericMethodInference( } } + /** Returns whether a reference to a generic method leaves its type arguments to be inferred. */ + private static boolean hasOmittedMethodReferenceTypeArguments( + MemberReferenceTree tree, Symbol.MethodSymbol referencedMethod) { + // javac uses null when a method reference omits its type arguments. + return referencedMethod.asType() instanceof Type.ForAll && tree.getTypeArguments() == null; + } + /** * Generate constraints for a method reference argument by comparing functional interface method * parameter and return types against the referenced method. @@ -2000,14 +2007,10 @@ private void handleMethodRefInGenericMethodInference( Type lhsType, MemberReferenceTree memberReferenceTree, @Nullable Set allCalls) { - // if we have a reference to a generic method, and the call site does not pass explicit type - // arguments, register the referenced method's type variables as inference variables Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(memberReferenceTree); - List explicitTypeArguments = memberReferenceTree.getTypeArguments(); Map inferenceVariables; if (referencedMethod != null - && !referencedMethod.getTypeParameters().isEmpty() - && (explicitTypeArguments == null || explicitTypeArguments.isEmpty())) { + && hasOmittedMethodReferenceTypeArguments(memberReferenceTree, referencedMethod)) { inferenceVariables = solver.registerInferenceVariables( memberReferenceTree, referencedMethod.getTypeParameters()); @@ -2248,9 +2251,7 @@ private Type.MethodType getFunctionalInterfaceMethodType( convertTreesToTypes(typeArgumentTrees), config) .asMethodType(); - } else if (overridingMethod.asType() instanceof Type.ForAll) { - // the referenced method is a generic method and there are no explicit type arguments - // we need to substitute inferred nullability for type arguments if it was inferred + } else if (hasOmittedMethodReferenceTypeArguments(memberReferenceTree, overridingMethod)) { result = getInferredMethodTypeForGenericMethodReference(result, state); } // finally, run any handlers @@ -3121,9 +3122,7 @@ public void compareGenericTypeParameterNullabilityForCall( private void inferMethodReferenceTypeArguments( MemberReferenceTree tree, Type targetType, VisitorState state) { Symbol.MethodSymbol referencedMethod = castToNonNull(ASTHelpers.getSymbol(tree)); - // javac represents omitted method-reference type arguments with null, not an empty list. - if (!(referencedMethod.type instanceof Type.ForAll) - || tree.getTypeArguments() != null + if (!hasOmittedMethodReferenceTypeArguments(tree, referencedMethod) || inferredTypeVarNullabilityForGenericCalls.containsKey(tree)) { return; } From ae85b85cdec0c2626e0252e007fea7a366d73455 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Fri, 27 Nov 2026 09:07:02 -0800 Subject: [PATCH 21/27] Skip nested constraint generation after a contradiction A failed inference problem still descended into later nested generic calls even though those calls were inferred separately. Repeating that work at each level produced 2,016 executable-type lookups for a chain of 63 failing calls. Leave later nested generic calls to their own inference once the solver records a contradiction. Continue processing direct lambda and method-reference arguments of the failing call. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4717586781 Assisted-by: Codex (gpt-6) --- .../nullaway/generics/GenericsChecks.java | 30 +++++++++---------- .../GenericInferencePerformanceTests.java | 16 ++++++++-- 2 files changed, 27 insertions(+), 19 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 8209a54578..2449cd5c34 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1672,9 +1672,9 @@ private Symbol.MethodSymbol getMethodSymbolForCall(ExpressionTree callTree) { * @param callTree the call tree representing the generic method call or diamond constructor call * @param methodType the executable type of {@code callTree}, as computed by {@link * #getExecutableTypeForInference} - * @param allCalls the top-level call, nested calls requiring inference, and method references - * whose checks depend on this problem's inference variables. This is an output parameter - * mutated during constraint generation to add nested sites. + * @param allCalls the sites that share this inference result. Constraint generation adds nested + * calls that require inference and are reached before a contradiction, and method references + * whose checks depend on this problem's inference variables. * @param polyNullContexts PolyNull inference contexts for calls in this inference problem. This * is an output parameter mutated during constraint generation to add contexts for modeled * calls. @@ -1778,9 +1778,9 @@ private void generateConstraintsForCall( * * @param state the visitor state * @param solver the constraint solver - * @param allCalls the top-level call, nested calls requiring inference, and method references - * whose checks depend on this problem's inference variables. This is an output parameter - * mutated during constraint generation to add nested sites. + * @param allCalls the sites that share this inference result. Constraint generation adds nested + * calls that require inference and are reached before a contradiction, and method references + * whose checks depend on this problem's inference variables. * @param rhsExpr the right-hand side expression of the pseudo-assignment * @param lhsType the left-hand side type of the pseudo-assignment * @param polyNullContexts PolyNull inference contexts for calls in this inference problem. This @@ -1800,13 +1800,12 @@ private void generateConstraintsForPseudoAssignment( NullabilityUtil.stripParensAndUpdateTreePath(rhsExpr, state); rhsExpr = exprTreeAndState.expr(); state = exprTreeAndState.state(); - // if the parameter is itself a generic call requiring inference, generate constraints for - // that call if (isCallNeedingInference(rhsExpr)) { - // Leave nested calls reached after a contradiction eligible for separate inference. - if (!solver.hasDeferredFailure()) { - allCalls.add(rhsExpr); + if (solver.hasDeferredFailure()) { + // Leave this subtree to the nested call's own inference. + return; } + allCalls.add(rhsExpr); generateConstraintsForCall( state, state.getPath(), @@ -1867,8 +1866,7 @@ private void generateConstraintsForPseudoAssignment( } /** - * Generate constraints for any return expression inside lambda argument. If the return expression - * is a method invocation then recursively call generateConstraintsForCall + * Generates constraints for the parameter types and return expressions of a lambda argument. * *

Implicit parameter types come from the ground target's descriptor while generating body * constraints. Keep them separate from cached inference results, and restore the enclosing @@ -1881,9 +1879,9 @@ private void generateConstraintsForPseudoAssignment( * @param path the tree path to the enclosing call if available and possibly distinct from {@code * state.getPath()} * @param solver the constraint solver - * @param allCalls the top-level call, nested calls requiring inference, and method references - * whose checks depend on this problem's inference variables. This is an output parameter - * mutated during constraint generation to add nested sites. + * @param allCalls the sites that share this inference result. Constraint generation adds nested + * calls that require inference and are reached before a contradiction, and method references + * whose checks depend on this problem's inference variables. * @param lhsType the type to which the lambda is being assigned * @param lambda The lambda argument * @param polyNullContexts PolyNull inference contexts for calls in this inference problem. This diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java index 99360a6e5f..20918220fb 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java @@ -32,6 +32,16 @@ public void nestedDataflowQueriesAvoidRepeatedEnclosingInference() { for (int level = 0; level < 6; level++) { expression = "join(" + expression + ", " + expression + ")"; } + checkNestedCallInferenceWork(expression); + } + + @Test + public void nestedDataflowQueriesAfterContradictionsAvoidRepeatedConstraintGeneration() { + checkNestedCallInferenceWork("join(null, ".repeat(63) + "\"leaf\"" + ")".repeat(63)); + } + + /** Checks the inference work for an expression containing 63 calls to {@code join}. */ + private void checkNestedCallInferenceWork(String expression) { CompilationTestHelper.newInstance(InferenceWorkChecker.class, getClass()) .setArgs( JSpecifyJavacConfig.withJSpecifyModeArgs( @@ -84,9 +94,9 @@ public Type.MethodType onOverrideMethodType( DataflowQueryScanner scanner = new DataflowQueryScanner(checks, state); scanner.scan(state.getPath(), null); assertThat(scanner.calls).isEqualTo(63); - // Allow implementation overhead while rejecting joint inference of the outermost call for - // every nested call. - assertThat(executableTypes.get()).isAtMost(32 * scanner.calls); + // Allow joint inference of each call's own subtree in the balanced expression. In the + // failing chain, each contradiction leaves the remaining calls to their own inference. + assertThat(executableTypes.get()).isAtMost(24 * scanner.calls); assertThat(executableTypes.get()).isAtLeast(scanner.calls); return NO_MATCH; } From 8631d4c451b42b528305b10bb7c427f9750cdef8 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Fri, 27 Nov 2026 09:19:44 -0800 Subject: [PATCH 22/27] Pin diagnostics for nested calls visited before a contradiction A nested call visited before its enclosing inference fails can inherit that failure. This hides a parameter mismatch on a method reference and produces false positives on a valid box(null) call. Assert the full diagnostic set for both cases and link the guard to the follow-up issue for diagnosing independent calls separately. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4717586795 Link: https://github.com/uber/NullAway/issues/2198 Assisted-by: Codex (gpt-6) --- .../nullaway/generics/GenericsChecks.java | 1 + ...enericMethodLambdaOrMethodRefArgTests.java | 52 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 2449cd5c34..907ed04f6f 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1803,6 +1803,7 @@ private void generateConstraintsForPseudoAssignment( if (isCallNeedingInference(rhsExpr)) { if (solver.hasDeferredFailure()) { // Leave this subtree to the nested call's own inference. + // Nested calls reached before the contradiction still share the enclosing failure (#2198). return; } allCalls.add(rhsExpr); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index 08b59daab8..edacbcbb79 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -1,6 +1,7 @@ package com.uber.nullaway.jspecify; import static com.google.common.truth.Truth.assertThat; +import static com.google.common.truth.Truth.assertWithMessage; import com.google.errorprone.CompilationTestHelper; import com.google.errorprone.FileObjects; @@ -522,6 +523,57 @@ void nestedCallAcceptsNull(Box<@Nullable String> first) { "Test.java:19: [NullAway] incompatible types: Box<@Nullable String> cannot be converted to Box"); } + @Test + public void nestedCallsBeforeEnclosingConstraintFailureShareItsResult() { + JavaFileObject source = + FileObjects.forSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + interface Fn { B apply(A a); } + static class Box {} + static Box wrapF(Fn<@Nullable String, U> f) { return new Box<>(); } + static String needsNonNull(String s) { return s; } + static void takeTwoRev(Box first, Box second) {} + static Box box(U value) { return new Box<>(); } + static void takeBoxRev(Box<@Nullable String> first, Box second) {} + + void independentReferenceMismatch(Box<@Nullable String> first) { + takeTwoRev( + wrapF(Test::needsNonNull), + first); + } + + void validNestedCall(Box<@Nullable String> first) { + takeBoxRev( + box(null), + first); + } + } + """); + assertWithMessage("Missing reference error and false positives on box(null) (#2198)") + .that( + compileAndReportDiagnostics( + List.of(source), + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-d", + temporaryFolder.getRoot().getAbsolutePath(), + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true")))) + .containsExactly( + "Test.java:15: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:17: [NullAway] incompatible types: Box<@Nullable String> cannot be converted to Box", + "Test.java:21: [NullAway] inference failure: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull", + "Test.java:22: [NullAway] incompatible types: Box cannot be converted to Box<@Nullable String>", + "Test.java:22: [NullAway] passing @Nullable parameter 'null' where @NonNull is required", + "Test.java:23: [NullAway] incompatible types: Box<@Nullable String> cannot be converted to Box"); + } + @Test public void failedJointInferenceSuppressesDependentReferenceDiagnosticsInEitherOrder() { makeTestHelperWithArgs( From 05c7d8d94601d0c806d2f85515bd67f6bc4638f4 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Sat, 28 Nov 2026 14:12:26 -0800 Subject: [PATCH 23/27] Check which contradiction generic inference reports Two incompatible arguments can constrain different type variables. Assert the exact warning names the first variable. A method reference with incompatible return and parameter types exercises the same rule within a single argument. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4728891607 Assisted-by: Codex (gpt-6) --- .../GenericInferenceErrorReportingTests.java | 56 +++++++++++++++++++ 1 file changed, 56 insertions(+) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java index 349c3b3200..bd0af83af7 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java @@ -16,6 +16,62 @@ */ public class GenericInferenceErrorReportingTests extends NullAwayTestsBase { + @Test + public void inferenceFailureNamesTheFirstContradictoryTypeVariable() { + JavaFileObject source = + FileObjects.forSourceLines( + "Test.java", + """ + package com.uber; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void take(Box first, Box second) {} + static void apply(Function, Box> function) {} + static Box<@Nullable String> nullableBox(Box<@Nullable String> input) { return input; } + static Box nonNullBox(Box<@Nullable String> input) { return new Box<>(); } + + void conflictingArguments(Box<@Nullable String> box) { + take(box, box); + } + void conflictingReferenceReturnAndParameter() { + apply(Test::nullableBox); + } + void conflictingSecondArgument(Box first, Box<@Nullable String> second) { + take(first, second); + } + void conflictingReferenceParameter() { + apply(Test::nonNullBox); + } + } + """); + + assertThat( + compileAndReportDiagnostics( + List.of(source), + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-d", + temporaryFolder.getRoot().getAbsolutePath(), + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true"))) + .stream() + .filter(diagnostic -> diagnostic.contains("inference failure:")) + .toList()) + .containsExactly( + "Test.java:14: [NullAway] inference failure: type variable T is constrained to be @Nullable, " + + "but its upper bound requires it to be @NonNull", + "Test.java:17: [NullAway] inference failure: type variable T is constrained to be @Nullable, " + + "but its upper bound requires it to be @NonNull", + "Test.java:20: [NullAway] inference failure: type variable S is constrained to be @Nullable, " + + "but its upper bound requires it to be @NonNull", + "Test.java:23: [NullAway] inference failure: type variable S is constrained to be @Nullable, " + + "but its upper bound requires it to be @NonNull"); + } + @Test public void inferenceUsesCompletedArgumentDataflowWithoutLibraryModels() { makeHelper() From 5200272d034cda51a12fca6004aa186317abbbd8 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Sat, 28 Nov 2026 14:14:38 -0800 Subject: [PATCH 24/27] Skip argument type refinement after an inference contradiction Refining a later lambda return can rerun dataflow under a new path and re-enter inference for the next failing call. Nested lambda chains can then trigger quadratic work and a StackOverflowError. Once the solver records a contradiction, follow conditional branches and lambda returns to register dependent method references. Skip argument type refinement and lambda parameter constraints. **User-visible changes.** Failing calls nested in lambdas can report their own inference failures without repeated lambda dataflow runs. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4728891603 Assisted-by: Codex (gpt-6) --- .../nullaway/generics/GenericsChecks.java | 66 ++++++----- .../dataflow/DataflowRunCountTests.java | 112 +++++++++++++++++- ...enericMethodLambdaOrMethodRefArgTests.java | 14 +++ 3 files changed, 156 insertions(+), 36 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 907ed04f6f..38074f439b 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1776,6 +1776,9 @@ private void generateConstraintsForCall( * In the context of generic method inference, generate constraints for a pseudo-assignment * (parameter passing or return). * + *

After a contradiction, follow conditional branches and lambda return expressions to register + * method references that share the failed inference result. + * * @param state the visitor state * @param solver the constraint solver * @param allCalls the sites that share this inference result. Constraint generation adds nested @@ -1800,25 +1803,7 @@ private void generateConstraintsForPseudoAssignment( NullabilityUtil.stripParensAndUpdateTreePath(rhsExpr, state); rhsExpr = exprTreeAndState.expr(); state = exprTreeAndState.state(); - if (isCallNeedingInference(rhsExpr)) { - if (solver.hasDeferredFailure()) { - // Leave this subtree to the nested call's own inference. - // Nested calls reached before the contradiction still share the enclosing failure (#2198). - return; - } - allCalls.add(rhsExpr); - generateConstraintsForCall( - state, - state.getPath(), - lhsType, - false, - solver, - rhsExpr, - getExecutableTypeForInference(rhsExpr, state.getPath(), state, calledFromDataflow), - allCalls, - polyNullContexts, - calledFromDataflow); - } else if (rhsExpr instanceof ConditionalExpressionTree conditionalExpressionTree) { + if (rhsExpr instanceof ConditionalExpressionTree conditionalExpressionTree) { // generate constraints for both the true and false sub-expressions of the conditional // expression ExpressionTree trueExpression = conditionalExpressionTree.getTrueExpression(); @@ -1854,6 +1839,23 @@ private void generateConstraintsForPseudoAssignment( } else if (rhsExpr instanceof MemberReferenceTree memberReferenceTree) { handleMethodRefInGenericMethodInference( state, solver, lhsType, memberReferenceTree, allCalls); + } else if (solver.hasDeferredFailure()) { + // Type refinement here can run dataflow again for each enclosing lambda. Leave nested calls + // to their own inference. Calls already registered still share the enclosing failure (#2198). + return; + } else if (isCallNeedingInference(rhsExpr)) { + allCalls.add(rhsExpr); + generateConstraintsForCall( + state, + state.getPath(), + lhsType, + false, + solver, + rhsExpr, + getExecutableTypeForInference(rhsExpr, state.getPath(), state, calledFromDataflow), + allCalls, + polyNullContexts, + calledFromDataflow); } else { // all other cases Type argumentType = getTreeType(rhsExpr, state, calledFromDataflow); if (argumentType == null) { @@ -1869,6 +1871,8 @@ private void generateConstraintsForPseudoAssignment( /** * Generates constraints for the parameter types and return expressions of a lambda argument. * + *

After a contradiction, looks only for dependent method references in the return expressions. + * *

Implicit parameter types come from the ground target's descriptor while generating body * constraints. Keep them separate from cached inference results, and restore the enclosing * parameter context on both success and failure. @@ -1915,17 +1919,16 @@ private void handleLambdaInGenericMethodInference( Map previousParameterTypes = lambdaParameterTypesForInference; try { if (((JCTree.JCLambda) lambda).paramKind == JCTree.JCLambda.ParameterKind.IMPLICIT) { - // If we have implicitly-typed lambda parameters, update the - // lambdaParameterTypesForInference map to have entries for these parameters, with types - // based on the parameter types in fiMethodTypeAsMember - Map parameterTypes = new LinkedHashMap<>(previousParameterTypes); - var params = lambda.getParameters(); - var fiParameterTypes = fiMethodTypeAsMember.getParameterTypes(); - for (int i = 0; i < params.size(); i++) { - parameterTypes.put( - castToNonNull(ASTHelpers.getSymbol(params.get(i))), fiParameterTypes.get(i)); + if (!solver.hasDeferredFailure()) { + Map parameterTypes = new LinkedHashMap<>(previousParameterTypes); + var params = lambda.getParameters(); + var fiParameterTypes = fiMethodTypeAsMember.getParameterTypes(); + for (int i = 0; i < params.size(); i++) { + parameterTypes.put( + castToNonNull(ASTHelpers.getSymbol(params.get(i))), fiParameterTypes.get(i)); + } + lambdaParameterTypesForInference = parameterTypes; } - lambdaParameterTypesForInference = parameterTypes; } else { // An explicitly typed parameter must accept every argument of the functional interface // method, as a referenced method's parameter must in @@ -1934,7 +1937,7 @@ private void handleLambdaInGenericMethodInference( // the parameter itself. var params = lambda.getParameters(); var fiParameterTypes = fiMethodTypeAsMember.getParameterTypes(); - for (int i = 0; i < params.size(); i++) { + for (int i = 0; i < params.size() && !solver.hasDeferredFailure(); i++) { Type parameterType = getTreeType(params.get(i), state); if (parameterType != null) { solver.addSubtypeConstraint( @@ -2021,6 +2024,9 @@ && hasOmittedMethodReferenceTypeArguments(memberReferenceTree, referencedMethod) && (!inferenceVariables.isEmpty() || solver.containsInferenceVariable(groundTargetType))) { allCalls.add(memberReferenceTree); } + if (solver.hasDeferredFailure()) { + return; + } GenericsUtils.processMethodRefTypeRelations( this, groundTargetType, diff --git a/nullaway/src/test/java/com/uber/nullaway/dataflow/DataflowRunCountTests.java b/nullaway/src/test/java/com/uber/nullaway/dataflow/DataflowRunCountTests.java index 27348e698e..916c45760d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/dataflow/DataflowRunCountTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/dataflow/DataflowRunCountTests.java @@ -2,7 +2,9 @@ import static com.google.common.truth.Truth.assertWithMessage; +import com.google.errorprone.CompilationTestHelper; import com.uber.nullaway.NullAwayTestsBase; +import com.uber.nullaway.generics.JSpecifyJavacConfig; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -152,17 +154,114 @@ public boolean test(Foo p) { .isEqualTo(1); } + @Test + public void failingCallsNestedInBlockLambdasAvoidRepeatedDataflowRuns() { + checkFailingLambdaChain(true); + } + + @Test + public void failingCallsNestedInExpressionLambdasAvoidRepeatedDataflowRuns() { + checkFailingLambdaChain(false); + } + + @Test + public void dependentReferenceQualifierDoesNotRepeatLambdaDataflowAfterContradiction() { + List runs = + runsWhileCompiling( + inferenceWarningsHelper(), + """ + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Foo { + record Box(T value) {} + static Box box(T value) { return new Box<>(value); } + static void rejectNull(T value, Supplier> reference) {} + void boundReference() { + // BUG: Diagnostic contains: inference failure: type variable T is constrained to be @Nullable + rejectNull(null, () -> { + String value = "leaf"; + return box(value)::value; + }); + } + } + """); + assertWithMessage("dataflow runs for the lambda returning box(value)::value") + .that(Collections.frequency(runs, "lambda")) + .isEqualTo(1); + } + /** - * Compiles {@code source} as {@code Foo.java}, expecting the diagnostics its {@code // BUG: - * Diagnostic contains:} comments mark and no others, and returns one entry per dataflow run: the - * method name for a method, {@code lambda } for a lambda, and {@code - * initializer} for an initializer. + * Checks that every failing call is diagnosed and lambda dataflow runs grow with chain length. + */ + private void checkFailingLambdaChain(boolean blockBody) { + int depth = 20; + String call = "\"leaf\""; + for (int level = 0; level < depth; level++) { + String body = + blockBody + ? "{\n" + + (level == 0 ? "" : call + ";\n") + + "String value = \"leaf\";\nreturn value;\n}" + : "identity(\n" + call + "\n)"; + call = + "// BUG: Diagnostic contains: inference failure: type variable T is constrained to be @Nullable\n" + + "rejectNull(null, () -> " + + body + + ")"; + } + List runs = + runsWhileCompiling( + inferenceWarningsHelper(), + """ + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Foo { + static T rejectNull(T value, Supplier supplier) { return value; } + static String identity(String value) { return value; } + void nestedCalls() { + %s; + } + } + """ + .formatted(call)); + int lambdaRuns = Collections.frequency(runs, "lambda"); + assertWithMessage("lambda dataflow runs for %s nested failing calls", depth) + .that(lambdaRuns) + .isAtLeast(depth - 1); + // Allow two runs per lambda. Refining returns after every contradiction took over 400 runs. + assertWithMessage("lambda dataflow runs for %s nested failing calls", depth) + .that(lambdaRuns) + .isAtMost(2 * depth); + } + + /** Creates a JSpecify test helper that reports generic inference failures. */ + private CompilationTestHelper inferenceWarningsHelper() { + return makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true"))); + } + + /** + * Compiles {@code source} with the default test arguments and returns the dataflow run labels. */ private List runsWhileCompiling(String source) { + return runsWhileCompiling(defaultCompilationHelper, source); + } + + /** + * Compiles {@code source} as {@code Foo.java}, checks its diagnostic markers, and returns one + * entry per dataflow run: the method name for a method, {@code lambda} followed by the first + * parameter name if present for a lambda, and {@code initializer} for an initializer. + */ + private List runsWhileCompiling(CompilationTestHelper helper, String source) { List runs = Collections.synchronizedList(new ArrayList<>()); RunOnceForwardAnalysisImpl.runListener = ast -> runs.add(label(ast)); try { - defaultCompilationHelper.addSourceLines("Foo.java", source).doTest(); + helper.addSourceLines("Foo.java", source).doTest(); } finally { RunOnceForwardAnalysisImpl.runListener = null; } @@ -174,7 +273,8 @@ private static String label(UnderlyingAST ast) { return method.getMethod().getName().toString(); } if (ast instanceof UnderlyingAST.CFGLambda lambda) { - return "lambda " + lambda.getLambdaTree().getParameters().get(0).getName(); + var parameters = lambda.getLambdaTree().getParameters(); + return parameters.isEmpty() ? "lambda" : "lambda " + parameters.get(0).getName(); } return "initializer"; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java index edacbcbb79..dc00010bb0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -599,6 +599,8 @@ static class Box {} static void refFirst(Function<@Nullable String, Box> f, Supplier s) {} static void refLast(Supplier s, Function<@Nullable String, Box> f) {} static void independentRefLast(Supplier s, Function<@Nullable String, Box> f) {} + static void returnedRefLast(Supplier s, + Function>> f) {} static void boxLast(Supplier s, Box box) {} static Box<@Nullable String> makeBox(Function<@Nullable String, Box> f) { return new Box<>(); @@ -635,6 +637,18 @@ void independentFixedReferenceLast() { Test::fixedBox); } + void dependentReferenceReturnedByBlockLambda() { + // BUG: Diagnostic contains: inference failure + returnedRefLast(Test::nullableValue, + (String unused) -> { return (Test::fixedBox); }); + } + + void dependentReferencesReturnedByConditionalLambda(boolean condition) { + // BUG: Diagnostic contains: inference failure + returnedRefLast(Test::nullableValue, + unused -> condition ? (Test::fixedBox) : (Test::box)); + } + void referenceInNestedCallLast() { // BUG: Diagnostic contains: type variable T is constrained to be @Nullable, but its upper bound requires it to be @NonNull boxLast(Test::nullableValue, From 180fb6995b01b29c6658deae6516eba372e1f76d Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Sat, 28 Nov 2026 14:15:09 -0800 Subject: [PATCH 25/27] Tighten the inference work limit for failing call chains A failing chain needs one lookup per call. The balanced expression's limit allowed 1,512 lookups for 63 calls, enough for some repeated constraint generation to pass. Bound the chain at two lookups per call. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4728891610 Assisted-by: Codex (gpt-6) --- .../GenericInferencePerformanceTests.java | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java index 20918220fb..7c4d7b2822 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java @@ -32,20 +32,28 @@ public void nestedDataflowQueriesAvoidRepeatedEnclosingInference() { for (int level = 0; level < 6; level++) { expression = "join(" + expression + ", " + expression + ")"; } - checkNestedCallInferenceWork(expression); + // Allow joint inference of each call's own subtree while rejecting repeated inference of the + // entire balanced expression for each call. + checkNestedCallInferenceWork(expression, 24); } @Test public void nestedDataflowQueriesAfterContradictionsAvoidRepeatedConstraintGeneration() { - checkNestedCallInferenceWork("join(null, ".repeat(63) + "\"leaf\"" + ")".repeat(63)); + // Each call needs one lookup. Generating constraints again for every later call took 2,016 + // lookups for a chain of 63 calls. + checkNestedCallInferenceWork("join(null, ".repeat(63) + "\"leaf\"" + ")".repeat(63), 2); } - /** Checks the inference work for an expression containing 63 calls to {@code join}. */ - private void checkNestedCallInferenceWork(String expression) { + /** + * Checks the bound on executable-type lookups for an expression with 63 calls to {@code join}. + */ + private void checkNestedCallInferenceWork(String expression, int maxLookupsPerCall) { CompilationTestHelper.newInstance(InferenceWorkChecker.class, getClass()) .setArgs( JSpecifyJavacConfig.withJSpecifyModeArgs( - List.of("-XepOpt:NullAway:OnlyNullMarked=true"))) + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:InferenceWorkChecker:MaxLookupsPerCall=" + maxLookupsPerCall))) .addSourceLines( "Test.java", """ @@ -94,9 +102,13 @@ public Type.MethodType onOverrideMethodType( DataflowQueryScanner scanner = new DataflowQueryScanner(checks, state); scanner.scan(state.getPath(), null); assertThat(scanner.calls).isEqualTo(63); - // Allow joint inference of each call's own subtree in the balanced expression. In the - // failing chain, each contradiction leaves the remaining calls to their own inference. - assertThat(executableTypes.get()).isAtMost(24 * scanner.calls); + int maxLookupsPerCall = + state + .errorProneOptions() + .getFlags() + .getInteger("InferenceWorkChecker:MaxLookupsPerCall") + .orElseThrow(); + assertThat(executableTypes.get()).isAtMost(maxLookupsPerCall * scanner.calls); assertThat(executableTypes.get()).isAtLeast(scanner.calls); return NO_MATCH; } From 6acb8a096025e74b9d8a881942d7d6344553afb9 Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Sat, 28 Nov 2026 14:15:25 -0800 Subject: [PATCH 26/27] Document when a method reference shares the inference result The allCalls parameter description omitted the conditions for adding a reference. Document omitted generic method type arguments, inference variables in the ground target type, and null for standalone inference. Link: https://github.com/uber/NullAway/pull/2175#discussion_r4728891611 Assisted-by: Codex (gpt-6) --- .../main/java/com/uber/nullaway/generics/GenericsChecks.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 38074f439b..16758fd211 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -2000,8 +2000,9 @@ private static boolean hasOmittedMethodReferenceTypeArguments( * @param solver the constraint solver * @param lhsType the type to which the method reference is being assigned * @param memberReferenceTree the method reference argument - * @param allCalls output parameter for sites sharing this inference problem's result, or {@code - * null} for standalone method reference inference + * @param allCalls the sites that share this inference result, or {@code null} for standalone + * method reference inference. A reference is added if it omits generic method type arguments + * or its ground target type contains one of this problem's inference variables. */ private void handleMethodRefInGenericMethodInference( VisitorState state, From 899008c74a4274a7e06fdcc8f309863e8fb0cd7e Mon Sep 17 00:00:00 2001 From: Manu Sridharan Date: Sat, 28 Nov 2026 15:00:39 -0800 Subject: [PATCH 27/27] restore comment --- .../main/java/com/uber/nullaway/generics/GenericsChecks.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java index 16758fd211..7bf773cbc9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -1920,6 +1920,9 @@ private void handleLambdaInGenericMethodInference( try { if (((JCTree.JCLambda) lambda).paramKind == JCTree.JCLambda.ParameterKind.IMPLICIT) { if (!solver.hasDeferredFailure()) { + // If we have implicitly-typed lambda parameters, update the + // lambdaParameterTypesForInference map to have entries for these parameters, with types + // based on the parameter types in fiMethodTypeAsMember Map parameterTypes = new LinkedHashMap<>(previousParameterTypes); var params = lambda.getParameters(); var fiParameterTypes = fiMethodTypeAsMember.getParameterTypes();