diff --git a/nullaway/src/main/java/com/uber/nullaway/NullAway.java b/nullaway/src/main/java/com/uber/nullaway/NullAway.java index 671295b26f..3d14539462 100644 --- a/nullaway/src/main/java/com/uber/nullaway/NullAway.java +++ b/nullaway/src/main/java/com/uber/nullaway/NullAway.java @@ -1580,7 +1580,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, @@ -1590,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/ConstraintSolver.java b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java index 22c3965821..9426ffcd18 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 problems are fixed + * types for this query. + */ + boolean containsInferenceVariable(Type type); + /** * Exception thrown when the constraints added to the solver are determined to be unsatisfiable. * @@ -87,15 +94,21 @@ public boolean isCausedByNonNullUpperBound() { * must appear in the types as the fresh type variables returned by {@link * #registerInferenceVariables(Tree, List)}. * + *

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 * @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); + + /** + * Returns whether adding a constraint detected a contradiction that {@link #solve()} will report. + */ + boolean hasDeferredFailure(); 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 bc0f890944..54d263f405 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, @@ -124,9 +125,29 @@ public Map registerInferenceVariables( } @Override - public void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType) - throws UnsatisfiableConstraintsException { - subtype.accept(new AddSubtypeConstraintsVisitor(localVariableType), supertype); + 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) { + if (deferredFailure != null) { + return; + } + try { + subtype.accept(new AddSubtypeConstraintsVisitor(localVariableType), supertype); + } catch (UnsatisfiableConstraintsException e) { + // 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> { @@ -354,6 +375,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 de436682aa..7bf773cbc9 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -139,9 +139,10 @@ 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 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<>(); @@ -1491,7 +1492,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 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 = @@ -1670,13 +1672,13 @@ 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 polyNullContexts PolyNull inference contexts for calls in this inference session. This + * @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. * @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, @@ -1688,8 +1690,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) { @@ -1775,13 +1776,17 @@ 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 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 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 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 @@ -1798,22 +1803,7 @@ 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)) { - 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(); @@ -1847,7 +1837,25 @@ private void generateConstraintsForPseudoAssignment( polyNullContexts, calledFromDataflow); } else if (rhsExpr instanceof MemberReferenceTree memberReferenceTree) { - handleMethodRefInGenericMethodInference(state, solver, lhsType, 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) { @@ -1861,8 +1869,9 @@ 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. + * + *

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 @@ -1875,11 +1884,12 @@ 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 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 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 @@ -1909,17 +1919,19 @@ 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()) { + // 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)); + } + 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 @@ -1928,7 +1940,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( @@ -1976,6 +1988,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. @@ -1984,20 +2003,20 @@ 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 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, ConstraintSolver solver, Type lhsType, - MemberReferenceTree memberReferenceTree) { - // 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 + MemberReferenceTree memberReferenceTree, + @Nullable Set allCalls) { 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()); @@ -2005,6 +2024,13 @@ 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); + } + if (solver.hasDeferredFailure()) { + return; + } GenericsUtils.processMethodRefTypeRelations( this, groundTargetType, @@ -2234,9 +2260,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 @@ -3023,22 +3047,26 @@ public void compareGenericTypeParameterNullabilityForCall( handler)) { Type groundFormalParameter = GenericsUtils.groundTargetType(formalParameter, state, config, handler); - 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); + inferMethodReferenceTypeArguments( + memberReferenceTree, groundFormalParameter, actualParameterAndState.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); @@ -3091,37 +3119,77 @@ 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 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 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) { + Symbol.MethodSymbol referencedMethod = castToNonNull(ASTHelpers.getSymbol(tree)); + if (!hasOmittedMethodReferenceTypeArguments(tree, referencedMethod) + || inferredTypeVarNullabilityForGenericCalls.containsKey(tree)) { + return; + } + ConstraintSolver solver = makeSolver(state, analysis); + CallInferenceResult result; + try { + handleMethodRefInGenericMethodInference(state, solver, targetType, tree, null); + result = new InferenceSuccess(solver.solve(), new IdentityHashMap<>()); + } catch (UnsatisfiableConstraintsException e) { + String message = inferenceFailureMessage(e, new IdentityHashMap<>()); + reportInferenceFailure(tree, message, state, false); + result = new InferenceFailure(message); + } + if (okToCacheInferenceResult(false)) { // diff-coverage: ignore -- No provisional types here. + inferredTypeVarNullabilityForGenericCalls.put(tree, result); + } + } + + /** + * Returns whether inference for this reference failed with a reported diagnostic, possibly from + * an enclosing inference problem. + * + *

Callers deliberately skip all parameter and return compatibility checks for such a + * 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() + && 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. * * @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/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/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/generics/GenericInferencePerformanceTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/GenericInferencePerformanceTests.java index 99360a6e5f..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,10 +32,28 @@ public void nestedDataflowQueriesAvoidRepeatedEnclosingInference() { for (int level = 0; level < 6; level++) { expression = "join(" + expression + ", " + 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() { + // 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 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", """ @@ -84,9 +102,13 @@ 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); + 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; } 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() 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..dc00010bb0 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,15 @@ 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; 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; @@ -79,6 +85,582 @@ 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(); + } + + @Test + public void genericMethodReferenceInferenceFailureSuppressesOnlyDependentCompatibilityErrors() { + 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: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: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.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 + 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", + "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: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", + "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: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. */ + private List compileGenericMethodReferenceDiagnostics(boolean warnOnInferenceFailure) { + JavaFileObject source = + FileObjects.forSourceLines( + "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 copyBox(Box value) { return value; } + 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) {} + static void acceptsIncompatibleBox( + Function, 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() { + // 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() { + // Expect inference failure; with inference warnings disabled, return and parameter mismatches. + acceptsNullable(Test::nonNullBox); + } + void explicitTypeArgumentIsPreserved() { + // Expect return and parameter mismatches; the explicit type argument skips inference. + acceptsNullable(Test::box); + } + 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 failedJointInferenceReportsIndependentReferenceMismatch() { + // Expect a parameter mismatch and joint inference failure; without inference warnings, a return mismatch too. + acceptsPair(Test::nonNullString, Test::nullableValue); + } + 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); + } + 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); + } + 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); + } + void inferenceFailureIsReportedAtTheFailingReference() { + acceptsBoth( + 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( + List.of(source), + JSpecifyJavacConfig.withJSpecifyModeArgs( + Arrays.asList( + "-d", + temporaryFolder.getRoot().getAbsolutePath(), + "-XepOpt:NullAway:AnnotatedPackages=com.uber", + "-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 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 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( + 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 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<>(); + } + + 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 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, + // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + makeBox( + Test::box)); + } + } + """) + .doTest(); + } + @Test public void voidCompatibleLambdaDiscardsNullableGenericResult() { makeHelper() @@ -1299,7 +1881,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() {