diff --git a/.github/workflows/continuous-integration.yml b/.github/workflows/continuous-integration.yml index 4f14afd79a..8a2aede82b 100644 --- a/.github/workflows/continuous-integration.yml +++ b/.github/workflows/continuous-integration.yml @@ -179,7 +179,7 @@ jobs: - project: calcite url: https://github.com/apache/calcite.git branch: main - sha: 713faf069e246f3430ae23ead1f90430c672cc15 + sha: dde58eb5a30f245f975d55f88ce2e861a1e82668 build: JAVA_HOME="$JAVA_HOME_21_X64" ./gradlew --init-script use-snapshot.gradle.kts -PenableErrorprone classes jmhClasses permissions: contents: read diff --git a/nullaway/src/main/java/com/uber/nullaway/Config.java b/nullaway/src/main/java/com/uber/nullaway/Config.java index 5a3235e33c..2a7855d109 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Config.java +++ b/nullaway/src/main/java/com/uber/nullaway/Config.java @@ -315,6 +315,38 @@ public interface Config { /** Should PolyNull library models be enabled? */ boolean isPolyNullLibraryModelsEnabled(); + /** + * Should generic inference account for the nullness of an unannotated type variable, a capture + * included, whose bound admits null, and read a declared bound {@code U extends R} between two + * type variables of a call as {@code U <: R}? True where both JSpecifyMode and + * JSpecifyExperimental are set. Where it is false, every inference variable that no constraint + * fixes is {@code @NonNull}, and the checks of a generic constructor at a diamond and of a + * generic method reference use the declared types. + * + *

Where it is true, an inference variable that no constraint fixes and that such a type + * variable flows into is {@link + * com.uber.nullaway.generics.ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NULLABLE} + * where the bounds of both that type variable and the inference variable are explicitly nullable, + * and {@link + * com.uber.nullaway.generics.ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL} + * otherwise. {@code GenericsUtils.typeVariableWithNullableBound} decides which bounds are + * explicitly nullable. With HandleWildcardGenerics also set, inference fails where an uncaptured + * type variable whose bound is explicitly nullable is passed for {@code ? extends U} and the + * bound of {@code U} excludes null. A generic constructor at a diamond and a generic method + * reference are checked against the types javac inferred for them. + * + *

Where it is true, inference also reads a declared bound {@code U extends R} between two type + * variables of one call, where the use of {@code R} carries no nullness annotation, as {@code U + * <: R}, and follows a chain of such bounds. {@code @Nullable} and the flow of an unannotated + * type variable whose bound admits null pass from {@code U} to {@code R}, and {@code @NonNull} + * passes from {@code R} to {@code U}. So {@code viaBoundOne(null).hashCode()} with {@code R viaBoundOne(U u)} is reported, though no type variable + * whose bound admits null is passed. Inference reads no {@code U <: R} where the declaration of + * {@code U} makes its bound nullable: where a library model does so, or where {@code U} is + * declared in unannotated code. + */ + boolean isNullableBoundInferenceEnabled(); + /** * Should wildcard-aware generic nullability checks be enabled? These also compute {@link * Nullness#NO_CHANGE} for the values listed there, such as the result of {@code Box knownInitializers; @@ -311,6 +312,7 @@ final class ErrorProneCLIFlagsConfig implements Config { acknowledgeAndroidRecent = flags.getBoolean(FL_ACKNOWLEDGE_ANDROID_RECENT).orElse(false); jspecifyMode = flags.getBoolean(FL_JSPECIFY_MODE).orElse(false); polyNullLibraryModelsEnabled = jspecifyMode && jspecifyExperimental; + nullableBoundInferenceEnabled = jspecifyMode && jspecifyExperimental; handleWildcardGenerics = flags.getBoolean(FL_HANDLE_WILDCARD_GENERICS).orElse(jspecifyExperimental); assertsEnabled = flags.getBoolean(FL_ASSERTS_ENABLED).orElse(false); @@ -624,6 +626,11 @@ public boolean isPolyNullLibraryModelsEnabled() { return polyNullLibraryModelsEnabled; } + @Override + public boolean isNullableBoundInferenceEnabled() { + return nullableBoundInferenceEnabled; + } + @Override public boolean handleWildcardGenerics() { return handleWildcardGenerics; diff --git a/nullaway/src/main/java/com/uber/nullaway/Nullness.java b/nullaway/src/main/java/com/uber/nullaway/Nullness.java index de328912a3..90679ba9ee 100644 --- a/nullaway/src/main/java/com/uber/nullaway/Nullness.java +++ b/nullaway/src/main/java/com/uber/nullaway/Nullness.java @@ -67,8 +67,10 @@ public enum Nullness implements AbstractValue { * *

A dereference of the value is reported, since the value is not null-exclusive under every * parameterization. An assignment, an argument, a return, or an array store accepts the value - * where nullness subtyping holds: where the target's type is {@code T}, or a capture of {@code ? - * super T}, without {@code @NonNull}, as {@link + * where nullness subtyping holds: where the target's type carries no {@code @NonNull} and is the + * value's own type (for example the capture of {@code ? extends T} that javac infers for a + * generic parameter), a type variable that the value's type reaches through non-nullable bounds + * (for example {@code T}), or a capture of {@code ? super} either of those types, as {@link * com.uber.nullaway.generics.GenericsChecks#acceptsNoChangeValue} decides. At any other target * the value is {@link #NULLABLE}, and so is a variable of another type that dataflow assigns it * to. Generic method inference takes no nullness constraint from the value and infers {@code T}. diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java index a78c52467e..63cf98b455 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -3,12 +3,14 @@ import static com.uber.nullaway.NullabilityUtil.castToNonNull; import com.google.common.base.Equivalence; +import com.google.common.collect.ImmutableSet; import com.google.errorprone.VisitorState; import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; import com.uber.nullaway.Config; +import com.uber.nullaway.Nullness; import com.uber.nullaway.handlers.Handler; import java.util.Collections; import java.util.HashSet; @@ -31,6 +33,24 @@ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor uninferredTypeVariables, boolean actualFromCallInference) { + /** A context with no uninferred type variables and an actual type taken from the code. */ + static final ComparisonContext NONE = new ComparisonContext(ImmutableSet.of(), false); + } /** Successful containment checks, reusable for the lifetime of this visitor. */ private @Nullable Set successfulWildcardComparisons; @@ -101,11 +121,16 @@ private record ContainmentKey( } CheckIdenticalNullabilityVisitor( - VisitorState state, GenericsChecks genericsChecks, Config config, Handler handler) { + VisitorState state, + GenericsChecks genericsChecks, + Config config, + Handler handler, + ComparisonContext context) { this.state = state; this.genericsChecks = genericsChecks; this.config = config; this.handler = handler; + this.context = context; } /** @@ -177,6 +202,7 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { GenericsUtils.effectiveUpperBoundsForTypeArguments( (Type.ClassType) rhsTypeAsSuper, state, config, handler); } + List formalTypeVariables = lhsType.tsym.type.getTypeArguments(); for (int i = 0; i < lhsTypeArguments.size(); i++) { Type lhsTypeArgument = lhsTypeArguments.get(i); Type lhsUpperBound = lhsUpperBounds.get(i); @@ -189,7 +215,8 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { rhsUpperBound, i, lhsParameterization, - rhsParameterization)) { + rhsParameterization, + (Type.TypeVar) formalTypeVariables.get(i))) { return false; } } @@ -245,6 +272,8 @@ public Boolean visitType(Type t, Type type) { * type, and type arguments; {@code null} if wildcard handling is off * @param rhsParameterization the RHS parameterized type, identified by its declaration, enclosing * type, and type arguments; {@code null} if wildcard handling is off + * @param formalTypeVariable the type parameter of the generic class that both type arguments + * instantiate * @return whether {@code rhsTypeArgument} is contained by {@code lhsTypeArgument} */ private boolean typeArgumentContainedBy( @@ -254,7 +283,8 @@ private boolean typeArgumentContainedBy( Type rhsUpperBound, int argumentIndex, @Nullable ParameterizationKey lhsParameterization, - @Nullable ParameterizationKey rhsParameterization) { + @Nullable ParameterizationKey rhsParameterization, + Type.TypeVar formalTypeVariable) { if (!config.handleWildcardGenerics()) { if (lhsTypeArgument.getKind().equals(TypeKind.WILDCARD) || rhsTypeArgument.getKind().equals(TypeKind.WILDCARD)) { @@ -280,7 +310,8 @@ private boolean typeArgumentContainedBy( rhsTypeArgument, argumentIndex, castToNonNull(lhsParameterization), - castToNonNull(rhsParameterization))); + castToNonNull(rhsParameterization)), + formalTypeVariable); } if (rhsWildcard != null) { // This case should only arise when generic method invocation inference / capture conversion @@ -314,7 +345,8 @@ private boolean haveIdenticalNullability(Type lhsType, Type rhsType) { * ? extends S} contains actual arguments whose upper bound is a subtype of {@code S}; a formal * {@code ? super S} contains concrete actuals {@code T} and wildcard actuals {@code ? super T} * when {@code S <: T}; and a formal {@code ?} is treated as {@code ? extends B}, where {@code B} - * is the corresponding type variable's upper bound. + * is the corresponding type variable's upper bound. The top-level nullness of each subtype check + * is {@link #isNullnessSubtype}, which judges a type variable by its declared bounds. * * @param lhsWildcard the formal wildcard type argument on the left * @param lhsUpperBound the upper bound of {@code lhsWildcard} @@ -322,6 +354,7 @@ private boolean haveIdenticalNullability(Type lhsType, Type rhsType) { * @param rhsUpperBound the upper bound of {@code rhsTypeArgument} * @param key identifies this comparison: {@code lhsWildcard}, {@code rhsTypeArgument}, their * position, and the parameterized types that contain them, before their bounds are computed + * @param formalTypeVariable the type parameter that {@code lhsWildcard} instantiates * @return whether {@code lhsWildcard} contains {@code rhsTypeArgument} */ private boolean wildcardContains( @@ -329,7 +362,8 @@ private boolean wildcardContains( Type lhsUpperBound, Type rhsTypeArgument, Type rhsUpperBound, - ContainmentKey key) { + ContainmentKey key, + Type.TypeVar formalTypeVariable) { if (successfulWildcardComparisons != null && successfulWildcardComparisons.contains(key)) { return true; } @@ -358,7 +392,11 @@ private boolean wildcardContains( try { boolean result = switch (lhsWildcard.kind) { - case UNBOUND, EXTENDS -> typeArgumentSubtype(lhsUpperBound, rhsUpperBound); + case UNBOUND, EXTENDS -> + typeArgumentSubtype( + lhsUpperBound, + rhsUpperBound, + actualOperator(formalTypeVariable, rhsTypeArgument, rhsUpperBound)); case SUPER -> superWildcardContains(lhsWildcard, rhsTypeArgument); }; // A nested success may rely on an unfinished check, so cache results only after the outer @@ -381,6 +419,179 @@ private boolean wildcardContains( } } + /** + * The JSpecify nullness operator + * of a type usage: what the usage says about null beyond what its base type says. + */ + enum NullnessOperator { + /** The usage is annotated {@code @Nullable}, in the code or by NullAway. */ + UNION_NULL, + /** The usage is annotated {@code @NonNull}, in the code or by NullAway. */ + MINUS_NULL, + /** The usage carries no nullness annotation and takes the nullness of its base type. */ + NO_CHANGE, + /** + * The check does not decide the usage's nullness: inference removed its annotations, or another + * check owns the question. {@link #actualOperator} assigns it to an actual type argument, and + * {@link #isNullExclusive} reads it as excluding null, which is the specification's "some + * world" rule. + */ + UNSPECIFIED + } + + private NullnessOperator operatorOf(Type type) { + if (genericsChecks.isNullableAnnotated(type)) { + return NullnessOperator.UNION_NULL; + } + if (Nullness.hasNonNullAnnotation(type.getAnnotationMirrors().stream(), config)) { + return NullnessOperator.MINUS_NULL; + } + return NullnessOperator.NO_CHANGE; + } + + /** + * Returns the operator of an actual type argument's effective upper bound against a formal {@code + * ?} or {@code ? extends}: the operator written on that bound, which for a capture is the one + * written on the wildcard it captures. The operator is {@link NullnessOperator#UNSPECIFIED} where + * the bound carries none and either of these holds: + * + *

+ */ + private NullnessOperator actualOperator( + Type.TypeVar formalTypeVariable, Type rhsTypeArgument, Type rhsUpperBound) { + NullnessOperator operator = operatorOf(rhsUpperBound); + if (operator == NullnessOperator.NO_CHANGE + && rhsTypeArgument instanceof Type.CapturedType + && context.actualFromCallInference()) { + return NullnessOperator.UNSPECIFIED; + } + if (operator == NullnessOperator.NO_CHANGE + && rhsUpperBound instanceof Type.TypeVar + && !GenericsUtils.upperBoundIsNullable( + formalTypeVariable.asElement(), config, handler, state)) { + return NullnessOperator.UNSPECIFIED; + } + return operator; + } + + /** + * Returns whether the check treats a value of the type as null-exclusive: never null under any + * instantiation of the type variables in scope, or {@link NullnessOperator#UNSPECIFIED}, which + * the check reads leniently. That holds for {@link NullnessOperator#MINUS_NULL} and {@link + * NullnessOperator#UNSPECIFIED}, never for {@link NullnessOperator#UNION_NULL}, and for {@link + * NullnessOperator#NO_CHANGE} where the type is one of these: + * + * + */ + private boolean isNullExclusive(Type type, NullnessOperator operator) { + return switch (operator) { + case UNION_NULL -> false; + case MINUS_NULL, UNSPECIFIED -> true; + case NO_CHANGE -> { + if (type instanceof Type.TypeVar typeVar) { + yield !GenericsUtils.boundIsExplicitlyNullable( + typeVar.asElement(), config, handler, state); + } + if (type instanceof Type.IntersectionClassType intersection) { + yield intersection.getExplicitComponents().stream() + .anyMatch(component -> isNullExclusive(component, operatorOf(component))); + } + yield true; + } + }; + } + + /** + * Returns whether the type reaches the type variable {@code target} through declared upper bounds + * none of which is explicitly nullable: the specification's nullness-subtype-establishing path, + * which makes {@code S} a subtype of {@code T} for {@code } and {@code } but not for {@code }. The path may pass through any + * element of an intersection, so a capture bounded by {@code T & @Nullable Runnable} reaches + * {@code T}. Returns {@code false} where no chain of bounds reaches {@code target}, as for a + * {@code target} declared by another method. + */ + private boolean hasSubtypeEstablishingPath( + Type type, NullnessOperator operator, Type.TypeVar target) { + if (operator == NullnessOperator.UNION_NULL) { + return false; + } + if (type instanceof Type.IntersectionClassType intersection) { + return intersection.getExplicitComponents().stream() + .anyMatch( + component -> hasSubtypeEstablishingPath(component, operatorOf(component), target)); + } + if (!(type instanceof Type.TypeVar typeVar)) { + return false; + } + if (typeVar.tsym.equals(target.tsym)) { + return true; + } + if (GenericsUtils.declaredBoundIsExplicitlyNullable( + typeVar.asElement(), config, handler, state)) { + return false; + } + return hasSubtypeEstablishingPath(typeVar.getUpperBound(), NullnessOperator.NO_CHANGE, target); + } + + /** + * Returns whether {@code subtype} is a JSpecify nullness subtype of + * {@code supertype}, judged at the top level only: a value of {@code subtype} that may be null + * fits {@code supertype} only where {@code supertype} admits null. That holds where {@code + * supertype} is null-inclusive, where {@code subtype} is null-exclusive, or where {@code + * supertype} is a type variable, not written {@code @NonNull}, that {@code subtype} reaches + * through bounds none of which is explicitly nullable. Nested type arguments are compared by the + * caller. + * + *

Where either side is a bare type variable that NullAway does not infer at the call or method + * reference being checked (see {@link ComparisonContext#uninferredTypeVariables}), its bounds are + * not read, and only a {@code subtype} annotated {@code @Nullable} fails. + */ + private boolean isNullnessSubtype( + Type subtype, + NullnessOperator subtypeOperator, + Type supertype, + NullnessOperator supertypeOperator) { + if (isUninferredTypeVariable(subtype, subtypeOperator) + || isUninferredTypeVariable(supertype, supertypeOperator)) { + return subtypeOperator != NullnessOperator.UNION_NULL; + } + if (supertypeOperator == NullnessOperator.UNION_NULL + || isNullExclusive(subtype, subtypeOperator)) { + return true; + } + return supertype instanceof Type.TypeVar target + && supertypeOperator != NullnessOperator.MINUS_NULL + && hasSubtypeEstablishingPath(subtype, subtypeOperator, target); + } + + /** + * Returns whether {@code type} is a type variable, written without a nullness annotation, that + * NullAway does not infer at the call or method reference being checked. + */ + private boolean isUninferredTypeVariable(Type type, NullnessOperator operator) { + return operator == NullnessOperator.NO_CHANGE + && type instanceof Type.TypeVar + && !(type instanceof Type.CapturedType) + && context.uninferredTypeVariables().contains(type.tsym); + } + /** * Returns whether a formal {@code ? super S} contains the actual type argument on the right. For * concrete actuals {@code T} and wildcard actuals {@code ? super T}, containment holds when @@ -399,22 +610,26 @@ private boolean superWildcardContains(Type.WildcardType lhsWildcard, Type rhsTyp return true; } Type rhsBound = castToNonNull(rhsWildcard.getSuperBound()); - return typeArgumentSubtype(rhsBound, lhsBound); + return typeArgumentSubtype(rhsBound, lhsBound, operatorOf(lhsBound)); } - return typeArgumentSubtype(rhsTypeArgument, lhsBound); + return typeArgumentSubtype(rhsTypeArgument, lhsBound, operatorOf(lhsBound)); } /** - * Returns whether the actual type argument on the right is a nullability-aware subtype of the - * formal type argument on the left. This check first rejects flows from nullable to non-null at - * the top level of the type argument, then delegates to {@link - * GenericsChecks#subtypeParameterNullability(Type, Type, VisitorState)} for recursive nested - * checks. + * Returns whether {@code rhsType} is a nullability-aware subtype of {@code lhsType}. For a formal + * {@code ? extends}, {@code rhsType} is the actual's upper bound; for a formal {@code ? super S}, + * {@code rhsType} is {@code S} and {@code lhsType} is the actual. The top level is {@link + * #isNullnessSubtype}; nested type arguments are delegated to {@link + * GenericsChecks#subtypeParameterNullability(Type, Type, VisitorState, + * CheckIdenticalNullabilityVisitor)}. + * + * @param lhsType the supertype + * @param rhsType the subtype + * @param rhsOperator the nullness operator of {@code rhsType}, which the caller may have relaxed + * to {@link NullnessOperator#UNSPECIFIED} */ - private boolean typeArgumentSubtype(Type lhsType, Type rhsType) { - boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType); - boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType); - if (isRHSNullableAnnotated && !isLHSNullableAnnotated) { + private boolean typeArgumentSubtype(Type lhsType, Type rhsType, NullnessOperator rhsOperator) { + if (!isNullnessSubtype(rhsType, rhsOperator, lhsType, operatorOf(lhsType))) { return false; } return genericsChecks.subtypeParameterNullability(lhsType, rhsType, state, this); 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..c07b54d601 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolver.java @@ -5,6 +5,7 @@ import java.util.List; import java.util.Map; import javax.lang.model.element.Element; +import org.jspecify.annotations.Nullable; /** * An interface for solving constraints on type variables, such as subtype relationships between @@ -62,14 +63,51 @@ class UnsatisfiableConstraintsException extends RuntimeException { /** Whether a {@code @Nullable} constraint conflicts with the type variable's upper bound. */ private final boolean causedByNonNullUpperBound; + /** + * The type variable with an explicitly nullable bound that was passed for {@code ? extends} + * {@link #typeVariable} and so constrains {@link #typeVariable} to be {@code @Nullable}; {@code + * null} where another constraint caused the conflict. + */ + private final @Nullable Type nullableBoundTypeVariable; + + /** + * The type variable whose declared bound makes the bound of {@link #nullableBoundTypeVariable} + * explicitly nullable: that type variable itself, or one its bound reaches through other type + * variables; {@code null} exactly where {@link #nullableBoundTypeVariable} is. + */ + private final @Nullable Element typeVariableWithNullableBound; + public UnsatisfiableConstraintsException(Element typeVariable) { this(typeVariable, false); } public UnsatisfiableConstraintsException( Element typeVariable, boolean causedByNonNullUpperBound) { + this(typeVariable, causedByNonNullUpperBound, null, null); + } + + /** + * Creates an exception for a {@code typeVariable} whose bound excludes null, where {@code + * nullableBoundTypeVariable}, a type variable with an explicitly nullable bound, was passed for + * {@code ? extends typeVariable}, and the declared bound of {@code + * typeVariableWithNullableBound} makes that bound explicitly nullable. + */ + public UnsatisfiableConstraintsException( + Element typeVariable, + Type nullableBoundTypeVariable, + Element typeVariableWithNullableBound) { + this(typeVariable, true, nullableBoundTypeVariable, typeVariableWithNullableBound); + } + + private UnsatisfiableConstraintsException( + Element typeVariable, + boolean causedByNonNullUpperBound, + @Nullable Type nullableBoundTypeVariable, + @Nullable Element typeVariableWithNullableBound) { this.typeVariable = typeVariable; this.causedByNonNullUpperBound = causedByNonNullUpperBound; + this.nullableBoundTypeVariable = nullableBoundTypeVariable; + this.typeVariableWithNullableBound = typeVariableWithNullableBound; } public Element getTypeVariable() { @@ -79,6 +117,14 @@ public Element getTypeVariable() { public boolean isCausedByNonNullUpperBound() { return causedByNonNullUpperBound; } + + public @Nullable Type getNullableBoundTypeVariable() { + return nullableBoundTypeVariable; + } + + public @Nullable Element getTypeVariableWithNullableBound() { + return typeVariableWithNullableBound; + } } /** @@ -97,14 +143,49 @@ public boolean isCausedByNonNullUpperBound() { void addSubtypeConstraint(Type subtype, Type supertype, boolean localVariableType) throws UnsatisfiableConstraintsException; + /** The nullness the solver found for an inference variable. */ enum InferredNullability { + /** + * A constraint fixed the variable to be non-null, or no constraint fixed it and no unannotated + * type variable that is not under inference and whose bound admits null flowed into it, so + * non-null is the least solution. The solver tracks such a flow only where {@link + * com.uber.nullaway.Config#isNullableBoundInferenceEnabled} holds; otherwise every variable + * that no constraint fixed is {@code NONNULL}. + */ NONNULL, - NULLABLE + /** A constraint fixed the variable to be nullable. */ + NULLABLE, + /** + * No constraint fixed the variable, a type variable {@code T} whose bound is explicitly + * nullable flowed into it, and the variable's own bound is explicitly nullable, as {@link + * GenericsUtils#typeVariableWithNullableBound} decides it. Where javac inferred a type with + * parametric nullness ({@link GenericsUtils#hasParametricNullness}), a capture included, the + * variable is that type with no synthetic annotation; where javac inferred an intersection + * type, it carries no annotation; where javac inferred any other type, such as the least upper + * bound of {@code T} and {@code String}, or a type variable {@code R} whose bound excludes null + * for {@code T extends @Nullable R}, the variable is {@code @Nullable}, the least type that + * holds a null {@code T}. + */ + TYPE_VARIABLE_OR_NULLABLE, + /** + * No constraint fixed the variable and an unannotated type variable that is not under inference + * and whose bound admits null flowed into it, but {@link #TYPE_VARIABLE_OR_NULLABLE} does not + * apply: no such type variable has an explicitly nullable bound, or the variable's own bound is + * not explicitly nullable. Where javac inferred a type with parametric nullness ({@link + * GenericsUtils#hasParametricNullness}), a capture included, the variable is that type with no + * synthetic annotation; where javac inferred an intersection type, it carries no annotation; + * where javac inferred any other type, the variable is {@code @NonNull}, as if no type variable + * had flowed into it. + */ + TYPE_VARIABLE_OR_NONNULL; } /** * Solve the constraints, returning a map from inference variables to their inferred nullability. - * The map only contains inference variables that appear in constraints. + * The map only contains inference variables that appear in constraints or, where {@link + * com.uber.nullaway.Config#isNullableBoundInferenceEnabled} holds, that such a variable reaches + * through a chain of declared bounds read as {@code U <: R}: for {@code } with only {@code U} constrained, the map holds {@code U}, {@code R}, and {@code Q}. * * @return a map from inference variables to their inferred nullability * @throws UnsatisfiableConstraintsException if the constraints 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..6210eb1a13 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/ConstraintSolverImpl.java @@ -18,6 +18,7 @@ import com.uber.nullaway.Nullness; import com.uber.nullaway.handlers.Handler; import java.util.ArrayDeque; +import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.IdentityHashMap; @@ -48,6 +49,17 @@ public final class ConstraintSolverImpl implements ConstraintSolver { private final IdentityHashMap inferenceVariables = new IdentityHashMap<>(); + /** + * Maps an inference variable whose declared bound is an unannotated use of another inference + * variable of the same site, such as {@code U} in {@code }, to that variable, + * where the declaration of {@code U} does not make its bound nullable by {@link + * GenericsUtils#declaredUpperBoundIsNullable}. {@link #solve()} makes each such bound a supertype + * edge {@code U <: R} for every {@code U} that appears in a constraint or that an earlier edge + * reaches, so it follows a chain such as {@code } from {@code U} to + * {@code Q}. Recorded only where {@link Config#isNullableBoundInferenceEnabled} holds. + */ + private final Map declaredBounds = new LinkedHashMap<>(); + public ConstraintSolverImpl(Config config, VisitorState state, NullAway analysis) { this.config = config; this.handler = analysis.getHandler(); @@ -74,6 +86,21 @@ private static final class VarState { NullnessState nullness = NullnessState.UNKNOWN; + /** + * Whether a type with parametric nullness ({@link GenericsUtils#hasParametricNullness}) that is + * not under inference flowed into this variable. Such a flow fixes no nullness, but where javac + * inferred a type with parametric nullness, the variable takes that type with no synthetic + * annotation rather than the non-null default. Recorded only where {@link + * Config#isNullableBoundInferenceEnabled} holds. + */ + boolean parametric; + + /** + * Whether one of the type variables that set {@link #parametric} has a bound that is explicitly + * nullable, rather than nullable by default in unannotated code. + */ + boolean parametricNullable; + /** Important to use a LinkedHashSet here for determinism in error messages. */ final Set supertypes = new LinkedHashSet<>(); @@ -119,6 +146,17 @@ public Map registerInferenceVariables( for (Map.Entry entry : fresh.entrySet()) { inferenceVariables.put(entry.getValue().tsym, new InferenceVariable(entry.getKey(), site)); } + if (config.isNullableBoundInferenceEnabled()) { + for (Type.TypeVar typeVar : fresh.values()) { + InferenceVariable inferenceVar = castToNonNull(inferenceVariables.get(typeVar.tsym)); + InferenceVariable boundVar = inferenceVariableForUse(typeVar.getUpperBound()); + if (boundVar != null + && !GenericsUtils.declaredUpperBoundIsNullable( + inferenceVar.typeVariable(), config, handler, state)) { + declaredBounds.put(inferenceVar, boundVar); + } + } + } return fresh; } @@ -276,9 +314,15 @@ private void equateTypeArguments(Type subtypeTypeArg, Type supertypeTypeArg) { /** * Adds constraints for type-argument containment where the formal argument is a wildcard. For * {@code ? extends S} and {@code ?}, containment requires the actual argument's effective upper - * bound to be a subtype of {@code S}. For {@code ? super S}, concrete actual arguments require - * {@code S <: subtypeTypeArg}; {@code ? super T} actual arguments require {@code S <: T}. Other - * actual wildcard forms place no useful nullability constraint. + * bound to be a subtype of {@code S}. For {@code ? extends U}, where {@code U} is an inference + * variable whose bound excludes null, an actual that is an unannotated, uncaptured type + * variable {@code T} with an explicitly nullable bound also constrains {@code U} to be + * {@code @Nullable}, which no solution satisfies; this check runs only where {@link + * Config#isNullableBoundInferenceEnabled} holds. An actual wildcard or capture bounded by such + * a {@code T}, as in {@code Box}, adds no such constraint (#2189). For {@code ? + * super S}, concrete actual arguments require {@code S <: subtypeTypeArg}; {@code ? super T} + * actual arguments require {@code S <: T}. Other actual wildcard forms place no useful + * nullability constraint. * *

Self-referential bounds such as {@code N extends Node} can lead back to the exact same * containment check. Re-entering a check that is already in progress adds no constraints, since @@ -298,8 +342,27 @@ private void constrainContainedByWildcard(Type subtypeTypeArg, WildcardType supe case UNBOUND, EXTENDS -> { Type subtypeUpperBound = GenericsUtils.effectiveWildcardUpperBound(subtypeTypeArg, state, config, handler); - subtypeUpperBound.accept( - this, GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler)); + Type supertypeUpperBound = + GenericsUtils.wildcardUpperBound(supertypeWildcard, state, config, handler); + InferenceVariable supertypeVar = inferenceVariableForUse(supertypeUpperBound); + if (config.isNullableBoundInferenceEnabled() + && supertypeWildcard.kind == BoundKind.EXTENDS + && supertypeVar != null + && !getState(supertypeVar).nullableAllowed) { + Element typeVariableWithNullableBound = + typeVariableWithNullableBoundFor(subtypeTypeArg); + if (typeVariableWithNullableBound != null) { + // Under JSpecify, an unannotated T whose bound is @Nullable is a subtype of U only + // where U is @Nullable, and the non-null bound of U forbids that. Where the bound + // of U allows null, U is left unconstrained: the solver infers one nullness per + // variable, so a @Nullable U would replace the T that javac inferred for U with + // @Nullable T, and List c = copy(in), with + // List copy(List in), would be reported. + throw new UnsatisfiableConstraintsException( + supertypeVar.typeVariable(), subtypeTypeArg, typeVariableWithNullableBound); + } + } + subtypeUpperBound.accept(this, supertypeUpperBound); } case SUPER -> { Type supertypeLowerBound = castToNonNull(supertypeWildcard.getSuperBound()); @@ -354,6 +417,22 @@ private void constrainWildcardToSupertype(WildcardType subtypeWildcard, Type sup @Override public Map solve() throws UnsatisfiableConstraintsException { + /* U extends R ⇒ U <: R, for every U that appears in a constraint or that an edge reaches */ + if (!declaredBounds.isEmpty()) { + List boundedVars = new ArrayList<>(vars.keySet()); + for (int i = 0; i < boundedVars.size(); i++) { + InferenceVariable sub = boundedVars.get(i); + InferenceVariable sup = declaredBounds.get(sub); + if (sup != null) { + if (!vars.containsKey(sup)) { + boundedVars.add(sup); + } + getState(sub).supertypes.add(sup); + getState(sup).subtypes.add(sub); + } + } + } + /* ---------- work-list propagation of nullability ---------- */ Deque work = new ArrayDeque<>(); vars.forEach( @@ -391,17 +470,48 @@ public Map solve() } } + /* a type variable that flowed into a variable flows into each of its supertype variables */ + vars.forEach( + (inferenceVar, st) -> { + if (st.parametric) { + work.add(inferenceVar); + } + }); + while (!work.isEmpty()) { + VarState st = castToNonNull(vars.get(work.removeFirst())); + for (InferenceVariable sup : st.supertypes) { + VarState supState = castToNonNull(vars.get(sup)); + if (!supState.parametric || (st.parametricNullable && !supState.parametricNullable)) { + supState.parametric = true; + supState.parametricNullable |= st.parametricNullable; + work.add(sup); + } + } + } + /* ---------- build final solution map ---------- */ Map result = new LinkedHashMap<>(); vars.forEach( (inferenceVar, st) -> { - // Note: if the nullness state is UNKNOWN, we infer NONNULL arbitrarily - // TODO does this matter? should we use NULLABLE instead? result.put( inferenceVar, - st.nullness == NullnessState.NULLABLE - ? InferredNullability.NULLABLE - : InferredNullability.NONNULL); + switch (st.nullness) { + case NULLABLE -> InferredNullability.NULLABLE; + case NONNULL -> InferredNullability.NONNULL; + // nothing pushed the variable toward null, so non-null is the least solution, + // unless an unannotated type variable whose bound admits null flowed in and + // decides its nullness + case UNKNOWN -> { + if (!st.parametric) { + yield InferredNullability.NONNULL; + } + yield st.parametricNullable + && GenericsUtils.boundIsExplicitlyNullable( + inferenceVar.typeVariable(), config, handler, state) + ? InferredNullability.TYPE_VARIABLE_OR_NULLABLE + : InferredNullability.TYPE_VARIABLE_OR_NONNULL; + } + }); }); return result; } @@ -437,6 +547,16 @@ private void directlyConstrainTypePair(Type s, Type t) throws UnsatisfiableConst if (isKnownNullable(s) && tVar != null) { updateNullness(tVar, NullnessState.NULLABLE); } + if (config.isNullableBoundInferenceEnabled() + && tVar != null + && sVar == null + && GenericsUtils.hasParametricNullness(s, config, handler, state)) { + VarState st = getState(tVar); + st.parametric = true; + if (GenericsUtils.boundIsExplicitlyNullable(s.asElement(), config, handler, state)) { + st.parametricNullable = true; + } + } } /* ───────────────────── nullability bookkeeping ───────────────────── */ @@ -501,6 +621,21 @@ private boolean treatAsTypeVariableForInference(Type t) { return inferenceVariableForUse(t) != null; } + /** + * Where {@code t} is a type variable not under inference, not a capture, and carrying no nullness + * annotation at this use, returns the type variable whose declared bound makes the bound of + * {@code t} explicitly nullable, as {@link GenericsUtils#typeVariableWithNullableBound} finds it; + * returns {@code null} otherwise. + */ + private @Nullable Element typeVariableWithNullableBoundFor(Type t) { + return t instanceof TypeVar tv + && !(t instanceof CapturedType) + && !inferenceVariables.containsKey(tv.asElement()) + && !GenericsUtils.hasNullnessAnnotation(t, config) + ? GenericsUtils.typeVariableWithNullableBound(tv.asElement(), config, handler, state) + : null; + } + /** Returns whether a type is explicitly nullable or is the null type. */ private boolean isKnownNullable(Type t) { return t instanceof NullType || GenericsUtils.isAnnotatedAsNullable(t, config); diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java index 6c9f73da45..09021e5ca0 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -8,59 +8,128 @@ import com.sun.tools.javac.code.BoundKind; import com.sun.tools.javac.code.Type; import com.sun.tools.javac.code.Types; +import java.util.List; import org.jspecify.annotations.Nullable; /** * A visitor that pretty prints a generic type including its type-use nullability annotations, for * use in error messages. * + *

Nodes named by {@link TypePath} may be marked, in which case each printed form is bracketed by + * {@link #MARK_START}, the index of the path that matched, and {@link #MARK_END}, so that a caller + * can find its columns and draw a caret under it. A path that the printed type does not reach + * leaves no bracket, which is how a caller learns that the node it asked about is not printed: an + * unbounded wildcard prints as {@code ?} and its upper bound appears nowhere. + * *

This code is a modified and extended version of code in {@link * com.google.errorprone.util.Signatures} */ final class GenericTypePrettyPrintingVisitor extends Types.DefaultTypeVisitor { + /** + * Opens the printed form of a marked node, followed by the digit naming which requested path + * matched. The characters cannot occur in a printed type, so the caller can locate the marked + * node's columns and then strip them. + */ + static final char MARK_START = '\u0001'; + + static final char MARK_END = '\u0002'; + private final VisitorState state; + /** + * The positions whose printed form is bracketed, in the order the caller numbers them. At most + * ten, since the index is printed as one digit, and disjoint, since a node reported as a mismatch + * is never descended into. An entry is {@code null} where the caller has a position for the other + * side of the comparison and none here, which keeps the indices of the two sides aligned. + */ + private final List<@Nullable TypePath> markedPaths; + + /** The position of the node being printed, maintained as the visitor descends. */ + private TypePath currentPath = TypePath.root(); + GenericTypePrettyPrintingVisitor(VisitorState state) { + this(state, List.of()); + } + + GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) { this.state = state; + this.markedPaths = markedPaths; + } + + /** Brackets {@code printed} when the node being printed sits at one of the requested paths. */ + private String mark(String printed) { + for (int i = 0; i < markedPaths.size(); i++) { + TypePath markedPath = markedPaths.get(i); + if (markedPath != null && markedPath.reachesSameNodeAs(currentPath)) { + return MARK_START + Integer.toString(i) + printed + MARK_END; + } + } + return printed; + } + + /** Strips the bracket around {@code printed}, where the whole of it is one marked node. */ + private static String withoutOuterMark(String printed) { + return printed.length() > 2 + && printed.charAt(0) == MARK_START + && printed.charAt(printed.length() - 1) == MARK_END + ? printed.substring(2, printed.length() - 1) + : printed; + } + + /** Prints {@code child}, which {@code step} descends to from the node being printed. */ + private String descend(TypePath.Step step, Type child) { + TypePath enclosingPath = currentPath; + currentPath = enclosingPath.then(step); + try { + return child.accept(this, null); + } finally { + currentPath = enclosingPath; + } } @Override public String visitWildcardType(Type.WildcardType t, @Nullable Void unused) { - // NOTE: we have not tested this code yet as we do not yet support wildcard types StringBuilder sb = new StringBuilder(); sb.append(t.kind); if (t.kind != BoundKind.UNBOUND) { - sb.append(t.type.accept(this, null)); + sb.append(descend(TypePath.Step.wildcardBound(), t.type)); } - return sb.toString(); + return mark(sb.toString()); } @Override public String visitClassType(Type.ClassType t, @Nullable Void s) { if (t.isIntersection()) { - return prettyIntersectionType((Type.IntersectionClassType) t); + return mark(prettyIntersectionType((Type.IntersectionClassType) t)); } if (t.tsym.isAnonymous()) { // eventually, we could probably do even better formatting here, but this provides all the // needed information for now - return t.toString(); + return mark(t.toString()); } StringBuilder sb = new StringBuilder(); Type enclosingType = t.getEnclosingType(); if (!ASTHelpers.isSameType(enclosingType, Type.noType, state)) { - sb.append(enclosingType.accept(this, null)).append('.'); + sb.append(descend(TypePath.Step.enclosingType(), enclosingType)).append('.'); } appendNullableAnnotationIfPresent(t, sb); sb.append(t.tsym.getSimpleName()); if (t.getTypeArguments().nonEmpty()) { sb.append('<'); - sb.append( - t.getTypeArguments().stream().map(a -> a.accept(this, null)).collect(joining(", "))); + StringBuilder arguments = new StringBuilder(); + for (int i = 0; i < t.getTypeArguments().size(); i++) { + if (i > 0) { + arguments.append(", "); + } + arguments.append( + descend(TypePath.Step.typeArgument(i, null, null), t.getTypeArguments().get(i))); + } + sb.append(arguments); sb.append(">"); } - return sb.toString(); + return mark(sb.toString()); } /** @@ -70,7 +139,9 @@ public String visitClassType(Type.ClassType t, @Nullable Void s) { */ private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) { for (Attribute.TypeCompound compound : t.getAnnotationMirrors()) { - String annotName = compound.type.accept(this, null); + // the annotation type is printed by a visitor of its own, so that its own path bookkeeping + // does not place a mark inside an annotation name + String annotName = compound.type.accept(new GenericTypePrettyPrintingVisitor(state), null); if ("Nullable".equals(annotName)) { sb.append("@Nullable "); break; @@ -83,7 +154,7 @@ public String visitTypeVar(Type.TypeVar t, @Nullable Void unused) { StringBuilder sb = new StringBuilder(); appendNullableAnnotationIfPresent(t, sb); sb.append(t.tsym.getSimpleName()); - return sb.toString(); + return mark(sb.toString()); } private String prettyIntersectionType(Type.IntersectionClassType t) { @@ -97,27 +168,30 @@ public String visitCapturedType(Type.CapturedType t, @Nullable Void s) { StringBuilder sb = new StringBuilder(); appendNullableAnnotationIfPresent(t, sb); sb.append("capture of "); - sb.append(t.wildcard.accept(this, null)); - return sb.toString(); + // no step: a captured wildcard and the wildcard it captured are one node, which is also how + // GenericsUtils.asWildcard reads them, so the two agree on what a path addresses. One node + // takes one bracket, and it is the outer one, which covers the annotation printed above + sb.append(withoutOuterMark(t.wildcard.accept(this, null))); + return mark(sb.toString()); } @Override public String visitArrayType(Type.ArrayType t, @Nullable Void unused) { StringBuilder sb = new StringBuilder(); - sb.append(t.elemtype.accept(this, null)).append(' '); + sb.append(descend(TypePath.Step.arrayElement(), t.elemtype)).append(' '); appendNullableAnnotationIfPresent(t, sb); - return sb.append("[]").toString(); + return mark(sb.append("[]").toString()); } @Override public String visitErrorType(Type.ErrorType t, @Nullable Void unused) { // this arises for our synthetic @Nullable and @NonNull annotations; we just return the simple // name - return t.tsym.getSimpleName().toString(); + return mark(t.tsym.getSimpleName().toString()); } @Override public String visitType(Type t, @Nullable Void s) { - return t.toString(); + return mark(t.toString()); } } 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..913206b36e 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -59,6 +59,7 @@ import com.uber.nullaway.dataflow.AccessPathNullnessAnalysis; import com.uber.nullaway.dataflow.EnclosingEnvironmentNullness; import com.uber.nullaway.dataflow.NullnessStore; +import com.uber.nullaway.generics.CheckIdenticalNullabilityVisitor.ComparisonContext; import com.uber.nullaway.generics.ConstraintSolver.UnsatisfiableConstraintsException; import com.uber.nullaway.generics.GenericsUtils.MethodRefTypeRelationKind; import com.uber.nullaway.generics.PolyNullInference.PolyNullInferenceContext; @@ -99,7 +100,8 @@ private static final class InferenceSuccess implements CallInferenceResult { private final IdentityHashMap> typeVarNullabilityBySite = new IdentityHashMap<>(); - private final IdentityHashMap polyNullnessByInvocation; + private final IdentityHashMap + polyNullnessByInvocation; /** * Groups the solution by tree identity, preserving solution iteration order within each site's @@ -110,7 +112,8 @@ private static final class InferenceSuccess implements CallInferenceResult { */ private InferenceSuccess( Map solution, - IdentityHashMap polyNullnessByInvocation) { + IdentityHashMap + polyNullnessByInvocation) { this.polyNullnessByInvocation = polyNullnessByInvocation; solution.forEach( (inferenceVar, nullability) -> @@ -173,8 +176,8 @@ private InferenceFailure(@Nullable String errorMessage) { * PolyNull results inferred separately from generic call inference, cached by invocation * identity. Results from joint generic inference remain in {@link InferenceSuccess}. */ - private final IdentityHashMap separatelyInferredPolyNullness = - new IdentityHashMap<>(); + private final IdentityHashMap + separatelyInferredPolyNullness = new IdentityHashMap<>(); /** * Tracks generic method invocations currently undergoing nested-nullability repair so re-entrant @@ -457,7 +460,9 @@ private void reportInvalidInstantiationError( private void reportInvalidAssignmentInstantiationError( Tree tree, Type lhsType, Type rhsType, VisitorState state) { ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - String msg = errorMessageForIncompatibleTypesAtPseudoAssignment(lhsType, rhsType, state); + String msg = + new NullabilityMismatchMessage(this, config, handler, state) + .build(lhsType, rhsType, tree instanceof VariableTree); ErrorMessage errorMessage = new ErrorMessage(ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, msg); state.reportMatch( @@ -465,178 +470,14 @@ private void reportInvalidAssignmentInstantiationError( errorMessage, analysis.buildDescription(tree), state, null)); } - private String errorMessageForIncompatibleTypesAtPseudoAssignment( - Type lhsType, Type rhsType, VisitorState state) { - String prettyRhsType = prettyTypeForError(rhsType, state); - String prettyLhsType = prettyTypeForError(lhsType, state); - String result = - String.format( - "incompatible types: %s cannot be converted to %s", prettyRhsType, prettyLhsType); - boolean allowNonCaptureMismatch = prettyRhsType.equals(prettyLhsType); - WildcardBoundMismatch wildcardBoundMismatch = - firstWildcardBoundMismatch(lhsType, rhsType, state, allowNonCaptureMismatch); - if (wildcardBoundMismatch != null) { - result += " (" + describeWildcardBoundMismatch(wildcardBoundMismatch) + ")"; - } - if (!ASTHelpers.isSameType(lhsType, rhsType, state) - && lhsType.getKind() == TypeKind.DECLARED - && rhsType.getKind() == TypeKind.DECLARED) { - Symbol.TypeSymbol lhsSym = lhsType.asElement(); - if (lhsSym instanceof Symbol.ClassSymbol classSymbol) { - Type asSuper = - TypeSubstitutionUtils.asSuper(state.getTypes(), rhsType, classSymbol, config); - if (asSuper != null) { - result += - String.format( - " (%s is a subtype of %s)", prettyRhsType, prettyTypeForError(asSuper, state)); - } - } - } - return result; - } - - /** - * Returns the first wildcard bound difference between {@code lhsType} and {@code rhsType}, or - * {@code null} if no such difference can be found. Recursively traverses {@code lhsType} and - * {@code rhsType} to find such a difference. - * - *

This is especially useful when two types pretty-print identically, but differ in the - * effective upper bound of a wildcard nested somewhere inside the type. - * - * @param lhsType the lhs (target) type - * @param rhsType the rhs (source) type - * @param state the visitor state - * @param allowNonCaptureMismatch whether a mismatch may be returned when neither causal wildcard - * is captured. Such details are useful when the full types print identically, but redundant - * when the full types already expose the difference. - */ - private @Nullable WildcardBoundMismatch firstWildcardBoundMismatch( - Type lhsType, Type rhsType, VisitorState state, boolean allowNonCaptureMismatch) { - // base case: both wildcard types - Type.WildcardType lhsWildcard = GenericsUtils.asWildcard(lhsType); - Type.WildcardType rhsWildcard = GenericsUtils.asWildcard(rhsType); - if (lhsWildcard != null && rhsWildcard != null) { - if (!allowNonCaptureMismatch - && !(lhsType instanceof Type.CapturedType) - && !(rhsType instanceof Type.CapturedType)) { - return null; - } - return wildcardBoundMismatch(lhsType, rhsType, lhsWildcard, rhsWildcard, state); - } - if (lhsType instanceof Type.ClassType lhsClassType && rhsType instanceof Type.ClassType) { - Type rhsTypeAsSuper = - TypeSubstitutionUtils.asSuper( - state.getTypes(), rhsType, (Symbol.ClassSymbol) lhsType.tsym, config); - if (!(rhsTypeAsSuper instanceof Type.ClassType rhsClassType) - || rhsTypeAsSuper.isRaw() - || lhsType.isRaw()) { - return null; - } - List lhsTypeArguments = lhsClassType.getTypeArguments(); - List rhsTypeArguments = rhsClassType.getTypeArguments(); - if (lhsTypeArguments.size() != rhsTypeArguments.size()) { - return null; - } - for (int i = 0; i < lhsTypeArguments.size(); i++) { - WildcardBoundMismatch mismatch = - firstWildcardBoundMismatch( - lhsTypeArguments.get(i), rhsTypeArguments.get(i), state, allowNonCaptureMismatch); - if (mismatch != null) { - return mismatch; - } - } - return firstWildcardBoundMismatch( - lhsClassType.getEnclosingType(), - rhsClassType.getEnclosingType(), - state, - allowNonCaptureMismatch); - } - if (lhsType instanceof Type.ArrayType lhsArrayType - && rhsType instanceof Type.ArrayType rhsArrayType) { - return firstWildcardBoundMismatch( - lhsArrayType.elemtype, rhsArrayType.elemtype, state, allowNonCaptureMismatch); - } - return null; - } - - /** - * Creates a structured mismatch for two wildcards with visibly different effective upper bounds, - * or returns {@code null} if those bounds pretty-print the same. - */ - private @Nullable WildcardBoundMismatch wildcardBoundMismatch( - Type lhsType, - Type rhsType, - Type.WildcardType lhsWildcard, - Type.WildcardType rhsWildcard, - VisitorState state) { - Type lhsUpperBound = GenericsUtils.wildcardUpperBound(lhsWildcard, state, config, handler); - Type rhsUpperBound = GenericsUtils.wildcardUpperBound(rhsWildcard, state, config, handler); - String prettyLhsUpperBound = prettyTypeForError(lhsUpperBound, state); - String prettyRhsUpperBound = prettyTypeForError(rhsUpperBound, state); - if (!prettyLhsUpperBound.equals(prettyRhsUpperBound)) { - return new WildcardBoundMismatch(lhsType, rhsType, prettyLhsUpperBound, prettyRhsUpperBound); - } - return null; - } - - /** - * Describes a wildcard-bound mismatch, including provenance for every captured wildcard that - * directly participates in that mismatch. - */ - private static String describeWildcardBoundMismatch(WildcardBoundMismatch mismatch) { - String result = - String.format( - "target wildcard upper bound is %s; source wildcard upper bound is %s", - mismatch.prettyTargetUpperBound(), mismatch.prettySourceUpperBound()); - String targetCaptureDescription = - captureProvenanceDescription(mismatch.targetWildcardType(), "target"); - if (targetCaptureDescription != null) { - result += "; " + targetCaptureDescription; - } - String sourceCaptureDescription = - captureProvenanceDescription(mismatch.sourceWildcardType(), "source"); - if (sourceCaptureDescription != null) { - result += "; " + sourceCaptureDescription; - } - return result; - } - - /** Returns a short description of the type parameter underlying a captured type, if available. */ - private static @Nullable String captureProvenanceDescription(Type type, String assignmentRole) { - if (!(type instanceof Type.CapturedType capturedType)) { - return null; - } - Type.TypeVar formalTypeVariable = capturedType.wildcard.bound; - if (formalTypeVariable == null - || !(formalTypeVariable.tsym.owner instanceof Symbol.ClassSymbol owner) - || owner.getSimpleName().isEmpty()) { - return null; - } - return String.format( - "%s wildcard is the type argument for type variable %s of %s", - assignmentRole, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName()); - } - - /** - * A difference between the effective upper bounds of two corresponding wildcards. - * - *

The wildcard types are retained so the diagnostic can report provenance for the captured - * wildcard or wildcards that directly caused the mismatch, without reporting unrelated captures - * elsewhere in the enclosing types. - */ - private record WildcardBoundMismatch( - Type targetWildcardType, - Type sourceWildcardType, - String prettyTargetUpperBound, - String prettySourceUpperBound) {} - private void reportInvalidReturnTypeError( Tree tree, Type methodType, Type returnType, VisitorState state) { ErrorBuilder errorBuilder = analysis.getErrorBuilder(); ErrorMessage errorMessage = new ErrorMessage( ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, - errorMessageForIncompatibleTypesAtPseudoAssignment(methodType, returnType, state)); + new NullabilityMismatchMessage(this, config, handler, state) + .build(methodType, returnType, false)); state.reportMatch( errorBuilder.createErrorDescription( errorMessage, analysis.buildDescription(tree), state, null)); @@ -668,8 +509,8 @@ private void reportInvalidParametersNullabilityError( ErrorMessage errorMessage = new ErrorMessage( ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, - errorMessageForIncompatibleTypesAtPseudoAssignment( - formalParameterType, actualParameterType, state)); + new NullabilityMismatchMessage(this, config, handler, state) + .build(formalParameterType, actualParameterType, false)); state.reportMatch( errorBuilder.createErrorDescription( errorMessage, analysis.buildDescription(paramExpression), state, null)); @@ -1140,7 +981,9 @@ public void checkTypeParameterNullnessForAssignability(Tree tree, VisitorState s if (varLocalDeclaration) { lhsType = rhsType; } - boolean isAssignmentValid = subtypeParameterNullability(lhsType, rhsType, state); + boolean isAssignmentValid = + subtypeParameterNullability( + lhsType, rhsType, state, comparisonContextFor(ImmutableSet.of(), rhsTree)); if (!isAssignmentValid) { reportInvalidAssignmentInstantiationError(tree, lhsType, rhsType, state); } @@ -1445,15 +1288,24 @@ private Type inferCallType( if (callTree instanceof MethodInvocationTree invocationTree) { Type inferredCallType = TypeSubstitutionUtils.updateTypeWithInferredNullability( - typeAtCallSite, executableType.getReturnType(), typeVarNullability, state, config); + typeAtCallSite, + executableType.getReturnType(), + typeVarNullability, + state, + config, + handler); if (result instanceof InferenceSuccess successResult) { - Nullness polyNullness = successResult.polyNullnessByInvocation.get(invocationTree); + ConstraintSolver.InferredNullability polyNullness = + successResult.polyNullnessByInvocation.get(invocationTree); if (polyNullness != null) { inferredCallType = PolyNullInference.applyToReturnType( inferredCallType, handler.onGetPolyNullLocations(ASTHelpers.getSymbol(invocationTree), state), - polyNullAnnotationType(polyNullness, state)); + polyNullness, + state, + config, + handler); } } return inferredCallType; @@ -1462,7 +1314,12 @@ private Type inferCallType( Type constructedTypeAtCallSite = getConstructedTypeAtCallSite((NewClassTree) callTree); Type constructedTypeWithTypeVars = constructedTypeAtCallSite.tsym.type; return TypeSubstitutionUtils.updateTypeWithInferredNullability( - constructedTypeAtCallSite, constructedTypeWithTypeVars, typeVarNullability, state, config); + constructedTypeAtCallSite, + constructedTypeWithTypeVars, + typeVarNullability, + state, + config, + handler); } /** @@ -1555,7 +1412,8 @@ private CallInferenceResult runInferenceForCall( formalParamGroundTargetType, typeVarNullability, state, - config); + config, + handler); inferredPolyExpressionTypes.put(argument, typeWithInferredNullability); } } @@ -1585,6 +1443,26 @@ private String inferenceFailureMessage( if (polyNullInvocation != null) { return PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(polyNullInvocation)); } + Type nullableBoundTypeVariable = e.getNullableBoundTypeVariable(); + Element typeVariableWithNullableBound = e.getTypeVariableWithNullableBound(); + if (nullableBoundTypeVariable != null && typeVariableWithNullableBound != null) { + Element passedElement = nullableBoundTypeVariable.tsym; + String constrained = withDeclaringElement(typeVariable, false); + String passed = withDeclaringElement(passedElement, false); + String withNullableBound = withDeclaringElement(typeVariableWithNullableBound, false); + if (constrained.equals(passed) || constrained.equals(withNullableBound)) { + constrained = withDeclaringElement(typeVariable, true); + passed = withDeclaringElement(passedElement, true); + withNullableBound = withDeclaringElement(typeVariableWithNullableBound, true); + } + String reason = + typeVariableWithNullableBound.equals(passedElement) + ? passed + " has a @Nullable upper bound" + : passed + " extends " + withNullableBound + ", which has a @Nullable upper bound"; + return String.format( + "inference failure: type variable %s is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument %s passed for ? extends %s admits null, since %s", + constrained, nullableBoundTypeVariable, typeVariable, reason); + } if (e.isCausedByNonNullUpperBound()) { return String.format( "inference failure: type variable %s is constrained to be @Nullable, but its upper bound requires it to be @NonNull", @@ -1595,6 +1473,35 @@ private String inferenceFailureMessage( typeVariable); } + /** + * Returns the name of {@code typeVariable} followed by the class or method that declares it, such + * as {@code E of List.copyOf}, so that type variables of one name declared by different classes + * or methods can be told apart. + * + * @param qualified whether to name the class by its flat name, such as {@code java.util.List}, + * rather than its simple name + */ + private static String withDeclaringElement(Element typeVariable, boolean qualified) { + Symbol owner = ((Symbol) typeVariable).owner; + String ownerName = + owner instanceof Symbol.MethodSymbol method + ? method.isConstructor() + ? "the constructor of " + className(method.owner, qualified) + : className(method.owner, qualified) + "." + method.getSimpleName() + : className(owner, qualified); + return typeVariable.getSimpleName() + " of " + ownerName; + } + + /** + * Returns the flat name of {@code type}, such as {@code Test$Inner}, where {@code qualified} is + * set or the class has no simple name, as an anonymous class does; its simple name otherwise. + */ + private static String className(Symbol type, boolean qualified) { + return qualified || type.getSimpleName().isEmpty() + ? type.flatName().toString() + : type.getSimpleName().toString(); + } + /** Returns the type parameters whose nullability is inferred for {@code callTree}. */ private List getCallTypeParameters(ExpressionTree callTree) { if (callTree instanceof MethodInvocationTree invocationTree) { @@ -2237,7 +2144,7 @@ private Type.MethodType getFunctionalInterfaceMethodType( } 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 - result = getInferredMethodTypeForGenericMethodReference(result, state); + result = getInferredMethodTypeForGenericMethodReference(memberReferenceTree, result, state); } // finally, run any handlers return handler.onOverrideMethodType(overridingMethod, result, state, null); @@ -2547,7 +2454,11 @@ public void checkTypeParameterNullnessForFunctionReturnType( return; } boolean isReturnTypeValid = - subtypeParameterNullability(formalReturnType, returnExpressionType, state); + subtypeParameterNullability( + formalReturnType, + returnExpressionType, + state, + comparisonContextFor(ImmutableSet.of(), retExpr)); if (!isReturnTypeValid) { reportInvalidReturnTypeError(retExpr, formalReturnType, returnExpressionType, state); } @@ -2583,11 +2494,54 @@ private boolean identicalTypeParameterNullability( * @param state the visitor state */ boolean subtypeParameterNullability(Type lhsType, Type rhsType, VisitorState state) { + return subtypeParameterNullability(lhsType, rhsType, state, ComparisonContext.NONE); + } + + /** + * Like {@link #subtypeParameterNullability(Type, Type, VisitorState)}, with what the caller knows + * about the compared types that the types do not show. + * + * @param lhsType type for the lhs of the assignment + * @param rhsType type for the rhs of the assignment + * @param state the visitor state + * @param context the uninferred type variables and the origin of {@code rhsType} + */ + boolean subtypeParameterNullability( + Type lhsType, Type rhsType, VisitorState state, ComparisonContext context) { return subtypeParameterNullability( lhsType, rhsType, state, - new CheckIdenticalNullabilityVisitor(state, this, config, handler)); + new CheckIdenticalNullabilityVisitor(state, this, config, handler, context)); + } + + /** + * Returns the comparison context for the type NullAway computes for {@code actual}, where the + * type variables in {@code uninferredTypeVariables} are not instantiated. + */ + private ComparisonContext comparisonContextFor( + ImmutableSet uninferredTypeVariables, ExpressionTree actual) { + return new ComparisonContext(uninferredTypeVariables, hasTypeOfCallInference(actual)); + } + + /** + * Returns whether the type NullAway computes for {@code expression} is the type of a generic + * method or diamond constructor call that needs inference: the expression is such a call, or a + * {@code var} local, whose type is that of its initializer, initialized with one. + */ + private boolean hasTypeOfCallInference(ExpressionTree expression) { + ExpressionTree stripped = ASTHelpers.stripParentheses(expression); + if (isCallNeedingInference(stripped)) { + return true; + } + if (stripped instanceof IdentifierTree) { + TreePath declarationPath = varLocalDeclarations.get(ASTHelpers.getSymbol(stripped)); + if (declarationPath != null) { + ExpressionTree initializer = ((VariableTree) declarationPath.getLeaf()).getInitializer(); + return initializer != null && hasTypeOfCallInference(initializer); + } + } + return false; } /** @@ -2756,12 +2710,20 @@ public void checkTypeParameterNullnessForConditionalExpression( // the nullability annotations, we check that the true and false parts are assignable to the // type of the whole expression if (truePartType != null) { - if (!subtypeParameterNullability(condExprType, truePartType, state)) { + if (!subtypeParameterNullability( + condExprType, + truePartType, + state, + comparisonContextFor(ImmutableSet.of(), tree.getTrueExpression()))) { reportMismatchedTypeForTernaryOperator(truePartTree, condExprType, truePartType, state); } } if (falsePartType != null) { - if (!subtypeParameterNullability(condExprType, falsePartType, state)) { + if (!subtypeParameterNullability( + condExprType, + falsePartType, + state, + comparisonContextFor(ImmutableSet.of(), tree.getFalseExpression()))) { reportMismatchedTypeForTernaryOperator(falsePartTree, condExprType, falsePartType, state); } } @@ -2995,6 +2957,29 @@ public void compareGenericTypeParameterNullabilityForCall( } Type.MethodType finalMethodType = getInvokedMethodTypeAtCall(methodSymbol, tree, null, state, false); + ImmutableSet uninferred = + tree instanceof NewClassTree + ? ImmutableSet.copyOf(methodSymbol.getTypeParameters()) + : ImmutableSet.of(); + compareArgumentsAtCall(tree, finalMethodType, uninferred, state); + } + + /** + * Compares the type parameter nullability of each argument at a call with that of its formal + * parameter, as {@link #compareGenericTypeParameterNullabilityForCall} describes. + * + * @param tree the tree representing the call + * @param finalMethodType the type of the invoked method at the call + * @param uninferredTypeVariables type variables of the invoked constructor that NullAway does not + * instantiate at the call; empty for a method call + * @param state the visitor state + */ + @SuppressWarnings("ReferenceEquality") // deliberate reference equality checks + private void compareArgumentsAtCall( + Tree tree, + Type.MethodType finalMethodType, + ImmutableSet uninferredTypeVariables, + VisitorState state) { new InvocationArguments(tree, finalMethodType) .forEach( (currentActualParam, argPos, formalParameter, unused) -> { @@ -3023,13 +3008,24 @@ public void compareGenericTypeParameterNullabilityForCall( handler)) { Type groundFormalParameter = GenericsUtils.groundTargetType(formalParameter, state, config, handler); + Symbol.MethodSymbol referencedMethod = ASTHelpers.getSymbol(memberReferenceTree); + ComparisonContext referenceContext = + new ComparisonContext( + referencedMethod != null + ? ImmutableSet.builder() + .addAll(uninferredTypeVariables) + .addAll(referencedMethod.getTypeParameters()) + .build() + : uninferredTypeVariables, + false); GenericsUtils.processMethodRefTypeRelations( this, groundFormalParameter, memberReferenceTree, actualParameterAndState.state(), (subtype, supertype, relationKind) -> { - if (!subtypeParameterNullability(supertype, subtype, state)) { + if (!subtypeParameterNullability( + supertype, subtype, state, referenceContext)) { if (relationKind == MethodRefTypeRelationKind.RETURN) { reportInvalidMethodReferenceReturnTypeError( memberReferenceTree, supertype, subtype, state); @@ -3082,7 +3078,11 @@ public void compareGenericTypeParameterNullabilityForCall( if (actualParameterType == null) { return; } - if (!subtypeParameterNullability(formalParameter, actualParameterType, state)) { + if (!subtypeParameterNullability( + formalParameter, + actualParameterType, + state, + comparisonContextFor(uninferredTypeVariables, currentActualParam))) { reportInvalidParametersNullabilityError( formalParameter, actualParameterType, currentActualParam, state); } @@ -3091,36 +3091,59 @@ 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. - * - * @param methodType the original method type + * Returns the type of the method that a generic method reference refers to, with the nullness + * inferred for its type parameters, where the reference is an argument of a method call or a + * diamond {@code new} whose inference succeeded. Where {@link + * Config#isNullableBoundInferenceEnabled} is false, only a method call parent is considered and + * the nullness is copied onto {@code methodType} rather than onto the type javac inferred. + * + * @param memberReferenceTree the generic method reference + * @param methodType the member type of the referenced method, with the receiver's type arguments + * substituted, before inference of the method's own type arguments * @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 type javac inferred for the referenced method at the reference, with the inferred + * nullness copied onto it; {@code methodType} with that nullness where javac's type has + * another number of parameters or {@link Config#isNullableBoundInferenceEnabled} is false; + * {@code methodType} unchanged where the enclosing call needs no inference, or is not a + * method call while that predicate is false, or its inference failed */ private Type.MethodType getInferredMethodTypeForGenericMethodReference( - Type.MethodType methodType, VisitorState state) { + MemberReferenceTree memberReferenceTree, 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)) { + boolean useInferredReferentType = config.isNullableBoundInferenceEnabled(); + if (parentTree instanceof ExpressionTree parentExpression + && (useInferredReferentType || parentTree instanceof MethodInvocationTree) + && isCallNeedingInference(parentExpression)) { CallInferenceResult inferenceResult = - inferredTypeVarNullabilityForGenericCalls.get(methodInvocationTree); + inferredTypeVarNullabilityForGenericCalls.get(parentTree); if (inferenceResult instanceof InferenceSuccess successResult) { - // the referenced method's type variables are inferred at the method reference itself - Tree memberReferenceTree = state.getPath().getLeaf(); + // the type javac inferred for the referenced method decides what an inference variable + // whose nullness depends on it resolves to; the referenced method's type variables are + // inferred at the method reference itself + Type referentType = ((JCTree.JCMemberReference) memberReferenceTree).referentType; + // the inferred nullness is copied parameter by parameter, so a referent type of another + // arity falls back to the declared type; no call shape is known to produce one, a + // varargs method referenced with two arguments included + Type.MethodType typeToUpdate = + useInferredReferentType + && referentType instanceof Type.MethodType referentMethodType + // diff-coverage: ignore -- defensive guard, no known call shape reaches it + && referentMethodType.getParameterTypes().size() + == methodType.getParameterTypes().size() + ? referentMethodType + : methodType; return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability( - methodType, + typeToUpdate, methodType, successResult.typeVarNullabilityForSite(memberReferenceTree), state, - config); + config, + handler); } } return methodType; @@ -3152,10 +3175,13 @@ public void checkTypeParameterNullnessForMethodOverriding( .isSymbolUnannotated(overriddenMethod, config, handler)) { return; } - checkTypeParameterNullnessForOverridingMethodReturnType(tree, overriddenMethodType, state); - checkTypeParameterNullnessForOverridingMethodParameterType(tree, overriddenMethodType, state); - checkMethodTypeVariableUpperBoundNullnessForOverriding( - tree, overridingMethod, overriddenMethod, overriddenMethodType, state); + // JLS 8.4.4 compares the signatures of methods with the same type parameters only; where the + // nullness of a bound differs, the bound mismatch is the error to report + if (checkMethodTypeVariableUpperBoundNullnessForOverriding( + tree, overridingMethod, overriddenMethod, overriddenMethodType, state)) { + checkTypeParameterNullnessForOverridingMethodReturnType(tree, overriddenMethodType, state); + checkTypeParameterNullnessForOverridingMethodParameterType(tree, overriddenMethodType, state); + } } /** @@ -3258,8 +3284,10 @@ public Type getModeledOverriddenMethodType( * @param overriddenMethodType type of the overridden method after member-type substitution in the * overriding class context * @param state the visitor state + * @return whether every corresponding pair of upper bounds agrees in nullability, so that nothing + * was reported */ - private void checkMethodTypeVariableUpperBoundNullnessForOverriding( + private boolean checkMethodTypeVariableUpperBoundNullnessForOverriding( MethodTree tree, Symbol.MethodSymbol overridingMethod, Symbol.MethodSymbol overriddenMethod, @@ -3267,15 +3295,16 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding( VisitorState state) { // Generic methods are Type.ForAll; non-generic overridden methods have no method type vars. if (!(overriddenMethodType instanceof Type.ForAll forAll)) { - return; + return true; } com.sun.tools.javac.util.List overriddenTypeVars = forAll.tvars; List overridingTypeParams = overridingMethod.getTypeParameters(); // If counts differ, javac would not treat this as a valid override; leave that to the // compiler. if (overridingTypeParams.size() != overriddenTypeVars.size()) { - return; + return true; } + boolean boundsAgree = true; List typeParameterTrees = tree.getTypeParameters(); for (int i = 0; i < overridingTypeParams.size(); i++) { Symbol.TypeVariableSymbol overridingTv = overridingTypeParams.get(i); @@ -3287,6 +3316,7 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding( substitutedMethodTypeVarUpperBoundIsNullable( overriddenTypeVar, overriddenMethod, i, state); if (overridingNullable != overriddenNullable) { + boundsAgree = false; reportMismatchedMethodTypeVariableBoundError( typeParameterTrees.get(i), overridingTv, @@ -3296,6 +3326,7 @@ private void checkMethodTypeVariableUpperBoundNullnessForOverriding( state); } } + return boundsAgree; } /** @@ -3641,7 +3672,7 @@ private Type.MethodType substituteTypeArgsInGenericMethodType( : ((NewClassTree) tree).getTypeArguments(); com.sun.tools.javac.util.List explicitTypeArgs = convertTreesToTypes(typeArgumentTrees); Type.MethodType substitutedMethodType; - Nullness jointlyInferredPolyNullness = null; + ConstraintSolver.InferredNullability jointlyInferredPolyNullness = null; boolean genericInferenceFailed = false; // There are no explicit type arguments, so use the inferred types @@ -3692,7 +3723,8 @@ private Type.MethodType substituteTypeArgsInGenericMethodType( methodType, successResult.typeVarNullabilityForSite(invocationTree), state, - config); + config, + handler); jointlyInferredPolyNullness = successResult.polyNullnessByInvocation.get(invocationTree); } else { // Inference failed; use the call-site type without inferred nullability substitutions. @@ -3965,6 +3997,10 @@ private Type.MethodType getInvokedMethodTypeAtCall( && invokedMethodType instanceof Type.ForAll forAllType) { return substituteTypeArgsInGenericMethodType( tree, forAllType, path, state, calledFromDataflow); + } else if (config.isNullableBoundInferenceEnabled() + && tree instanceof NewClassTree newClassTree + && invokedMethodType instanceof Type.ForAll forAllType) { + invokedMethodType = substituteInferredConstructorTypeArgs(newClassTree, forAllType, state); } Type.MethodType modeledMethodType = handler.onOverrideMethodType( @@ -3992,7 +4028,7 @@ private Type.MethodType applyPolyNullModel( Symbol.MethodSymbol methodSymbol, MethodInvocationTree invocationTree, Type.MethodType substitutedMethodType, - @Nullable Nullness jointlyInferredPolyNullness, + ConstraintSolver.@Nullable InferredNullability jointlyInferredPolyNullness, @Nullable TreePath path, VisitorState state, boolean calledFromDataflow) { @@ -4000,7 +4036,7 @@ private Type.MethodType applyPolyNullModel( if (locations.isEmpty()) { return substitutedMethodType; } - Nullness polyNullness = + ConstraintSolver.InferredNullability polyNullness = jointlyInferredPolyNullness != null ? jointlyInferredPolyNullness : inferPolyNullnessSeparately( @@ -4015,23 +4051,30 @@ private Type.MethodType applyPolyNullModel( return substitutedMethodType; } return PolyNullInference.applyToMethodType( - substitutedMethodType, locations, polyNullAnnotationType(polyNullness, state)); + substitutedMethodType, locations, polyNullness, state, config, handler); } /** * Infers the nullness shared by all PolyNull occurrences when no jointly inferred value is * available. This includes non-generic calls and generic calls with explicit type arguments. * - *

All modeled locations share one synthetic type variable. Ordinary assignment-compatibility - * constraints select {@code @NonNull} unless an argument or the result target requires - * {@code @Nullable}. + *

All modeled locations share one synthetic type variable, which ordinary + * assignment-compatibility constraints fix as {@code @Nullable} or {@code @NonNull} where an + * argument or the result target requires it. Where no constraint fixes it and an argument passes + * a type variable with parametric nullness, each location takes the annotation {@link + * GenericsUtils#inferredNullnessAnnotation} gives it: a location where javac inferred a type + * variable with parametric nullness or an intersection type stays unannotated, and any other + * location is {@code @Nullable} where the bound of the passed type variable is explicitly + * nullable, and {@code @NonNull} otherwise. So with a {@code Supplier} argument, {@code T + * extends @Nullable Object}, and no non-null result target, a location inferred as {@code T} + * stays {@code T} and a class-type location becomes {@code @Nullable}. * * @return the inferred shared nullness, or {@code null} if no modeled parameter location applies. * Unsatisfiable constraints return {@code null} when {@code WarnOnGenericInferenceFailure} is - * enabled; otherwise they return {@code Nullness.NULLABLE} to preserve ordinary nullness - * errors. They are reported only outside dataflow. + * enabled; otherwise they return {@code NULLABLE} to preserve ordinary nullness errors. They + * are reported only outside dataflow. */ - private @Nullable Nullness inferPolyNullnessSeparately( + private ConstraintSolver.@Nullable InferredNullability inferPolyNullnessSeparately( Symbol.MethodSymbol methodSymbol, MethodInvocationTree invocationTree, Type.MethodType substitutedMethodType, @@ -4039,7 +4082,8 @@ private Type.MethodType applyPolyNullModel( @Nullable TreePath path, VisitorState state, boolean calledFromDataflow) { - Nullness cached = separatelyInferredPolyNullness.get(invocationTree); + ConstraintSolver.InferredNullability cached = + separatelyInferredPolyNullness.get(invocationTree); if (cached != null) { return cached; } @@ -4076,7 +4120,7 @@ private Type.MethodType applyPolyNullModel( calledFromDataflow); Map solution = solver.solve(); - Nullness resolved = + ConstraintSolver.InferredNullability resolved = PolyNullInference.resolveContext(invocationTree, inferenceContext, solution); if (!calledFromDataflow) { separatelyInferredPolyNullness.put(invocationTree, resolved); @@ -4088,7 +4132,9 @@ private Type.MethodType applyPolyNullModel( PolyNullInference.inferenceFailureMessage(ASTHelpers.getSymbol(invocationTree)), state, calledFromDataflow); - return config.warnOnGenericInferenceFailure() ? null : Nullness.NULLABLE; + return config.warnOnGenericInferenceFailure() + ? null + : ConstraintSolver.InferredNullability.NULLABLE; } } @@ -4185,11 +4231,38 @@ private void reportInferenceFailure( errorMessage, analysis.buildDescription(callTree), state, null)); } - /** Returns the synthetic annotation type representing the resolved PolyNull qualifier. */ - private static Type polyNullAnnotationType(Nullness nullness, VisitorState state) { - return nullness == Nullness.NULLABLE - ? getSyntheticNullableAnnotType(state) - : getSyntheticNonNullAnnotType(state); + /** + * Returns the type of a generic constructor at a diamond call, with the nullness inferred for the + * constructor's own type variables. Returns {@code forAllType} unchanged where the call has + * explicit type arguments, where its inference did not run or failed, and where the constructor + * javac resolved has more parameters than the declared one, as the constructor of an anonymous + * subclass of an inner class has: it takes the enclosing instance first. + * + * @param tree the constructor call + * @param forAllType the constructor's type, with the class type variables already substituted + * @param state the visitor state + */ + private Type substituteInferredConstructorTypeArgs( + NewClassTree tree, Type.ForAll forAllType, VisitorState state) { + if (!tree.getTypeArguments().isEmpty() + || !(inferredTypeVarNullabilityForGenericCalls.get(tree) + instanceof InferenceSuccess successResult)) { + return forAllType; + } + Type.MethodType declaredMethodType = forAllType.asMethodType(); + Type constructorTypeAtCallSite = ((JCTree.JCNewClass) tree).constructorType; + if (!(constructorTypeAtCallSite instanceof Type.MethodType methodTypeAtCallSite) + || methodTypeAtCallSite.getParameterTypes().size() + != declaredMethodType.getParameterTypes().size()) { + return forAllType; + } + return TypeSubstitutionUtils.updateMethodTypeWithInferredNullability( + methodTypeAtCallSite, + declaredMethodType, + successResult.typeVarNullabilityForSite(tree), + state, + config, + handler); } /** @@ -4527,7 +4600,13 @@ private void checkTypeParameterNullnessForOverridingMethodParameterType( if (overridingMethodParameterType != null) { // allow contravariant subtyping if (!subtypeParameterNullability( - overridingMethodParameterType, overriddenMethodParameterType, state)) { + adaptToOverriddenTypeParameters( + overridingMethodParameterType, + ASTHelpers.getSymbol(tree).type, + overriddenMethodType, + state), + overriddenMethodParameterType, + state)) { reportInvalidOverridingMethodParamTypeError( methodParameters.get(i), overriddenMethodParameterType, @@ -4538,6 +4617,23 @@ private void checkTypeParameterNullnessForOverridingMethodParameterType( } } + /** + * Adapts {@code type} to the type parameters of the overridden method, as JLS 8.4.4 defines for + * methods with the same type parameters: each type variable of the overriding method is replaced + * by the corresponding one of the overridden method, so that a bound written against one can be + * compared with a use of the other. The result is for the comparison only; a diagnostic prints + * the type as declared. + */ + private Type adaptToOverriddenTypeParameters( + Type type, Type overridingMethodType, Type overriddenMethodType, VisitorState state) { + if (overridingMethodType instanceof Type.ForAll overriding + && overriddenMethodType instanceof Type.ForAll overridden) { + return TypeSubstitutionUtils.subst( + state.getTypes(), type, overriding.tvars, overridden.tvars, config); + } + return type; + } + /** * This method compares the type parameter annotations for an overriding method's return type with * corresponding type parameters for the overridden method and reports an error if they don't @@ -4558,7 +4654,13 @@ private void checkTypeParameterNullnessForOverridingMethodReturnType( } // allow covariant subtyping if (!subtypeParameterNullability( - overriddenMethodReturnType, overridingMethodReturnType, state)) { + overriddenMethodReturnType, + adaptToOverriddenTypeParameters( + overridingMethodReturnType, + ASTHelpers.getSymbol(tree).type, + overriddenMethodType, + state), + state)) { reportInvalidOverridingMethodReturnTypeError( tree, overriddenMethodReturnType, overridingMethodReturnType, state); } @@ -4695,9 +4797,10 @@ private static Nullness getTypeNullnessForRead( /** * Returns a pretty-printed representation of type suitable for error messages. The representation - * uses simple names rather than fully-qualified names, and retains all type-use annotations. + * uses simple names rather than fully-qualified names, and keeps {@code @Nullable} and drops + * every other type-use annotation. */ - private static String prettyTypeForError(Type type, VisitorState state) { + static String prettyTypeForError(Type type, VisitorState state) { return type.accept(new GenericTypePrettyPrintingVisitor(state), null); } @@ -4837,12 +4940,12 @@ public static ValueTarget arrayElement(@Nullable Type arrayType) { * Returns whether {@code target} accepts a value of type {@code valueType} for which {@link * Nullness#isNoChange()} holds. Such a value is null only when the corresponding type variable * {@code T} is instantiated with a nullable type argument. A location accepts it when its type is - * a type variable {@code T}, or a capture of {@code ? super T}, such that neither the type nor - * the location's declaration is annotated {@code @NonNull}, and {@code valueType} is {@code T} or - * a subtype of {@code T} that reaches {@code T} through upper bounds none of which is nullable. - * Then the assigned location admits null whenever the value may be null. In {@code }, the bound of {@code U} breaks the chain, since {@code U} may be nullable - * while {@code T} is not. + * a type variable {@code T}, a capture included, or a capture of {@code ? super T}, such that + * neither {@code T} nor the location's declaration is annotated {@code @NonNull}, and {@code + * valueType} is {@code T} or a subtype of {@code T} that reaches {@code T} through upper bounds + * none of which is nullable. Then the assigned location admits null whenever the value may be + * null. In {@code }, the bound of {@code U} breaks the chain, since {@code + * U} may be nullable while {@code T} is not. * *

This test should be applied to the {@link ValueTarget} of the assigned location at every * pseudo-assignment, so that a {@code NO_CHANGE} fact always holds relative to the static type of @@ -4855,18 +4958,26 @@ public static ValueTarget arrayElement(@Nullable Type arrayType) { public boolean acceptsNoChangeValue(Type valueType, ValueTarget target, VisitorState state) { Type targetType = target.type(); Symbol declaration = target.declaration(); - // A capture of ? super T accepts every value of type T - Type typeVariable = - targetType instanceof Type.CapturedType capturedType - ? capturedType.getLowerBound() - : targetType; if (target.excludesNull() - || !(typeVariable instanceof Type.TypeVar) - || GenericsUtils.isAnnotatedAsNonNull(typeVariable, config) || (declaration != null && Nullness.hasNonNullAnnotation(declaration, config))) { return false; } - return reachesThroughNonNullableBounds(valueType, typeVariable, state); + return acceptsNoChangeValueOf(valueType, targetType, state) + // A capture of ? super T accepts every value of type T + || (targetType instanceof Type.CapturedType capturedType + && acceptsNoChangeValueOf(valueType, capturedType.getLowerBound(), state)); + } + + /** + * Returns whether {@code typeVariable} is a type variable, a capture included, that is not + * annotated {@code @NonNull} and that {@code valueType} reaches by {@link + * #reachesThroughNonNullableBounds}. + */ + private boolean acceptsNoChangeValueOf( + Type valueType, @Nullable Type typeVariable, VisitorState state) { + return typeVariable instanceof Type.TypeVar + && !GenericsUtils.isAnnotatedAsNonNull(typeVariable, config) + && reachesThroughNonNullableBounds(valueType, typeVariable, state); } /** diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java index 0da472288f..b095911b10 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -377,10 +377,62 @@ private static Type applyDeclarationUpperBoundNullabilityIfApplicable( return upperBound; } - private static boolean hasNullnessAnnotation(Type type, Config config) { + static boolean hasNullnessAnnotation(Type type, Config config) { return isAnnotatedAsNonNull(type, config) || isAnnotatedAsNullable(type, config); } + /** + * Returns the synthetic nullness annotation type that {@code inferred} adds to {@code + * inferredType}, the type javac inferred for the variable at one location, or {@code null} where + * that type takes no synthetic annotation. + * + *

{@code NULLABLE} and {@code NONNULL} annotate every type. {@code TYPE_VARIABLE_OR_NULLABLE} + * and {@code TYPE_VARIABLE_OR_NONNULL} add no annotation to an {@code inferredType} that has + * parametric nullness, the test ({@link #hasParametricNullness}) the solver also applies to a + * type that flows into the variable, or to an intersection type, whose nullness comes from its + * elements and stays non-null where they exclude null. Any other type, including a wildcard and a + * type variable with a nullness annotation, takes {@code @Nullable} for {@code + * TYPE_VARIABLE_OR_NULLABLE} and {@code @NonNull} for {@code TYPE_VARIABLE_OR_NONNULL}. + */ + static @Nullable Type inferredNullnessAnnotation( + Type inferredType, + ConstraintSolver.InferredNullability inferred, + Config config, + Handler handler, + VisitorState state) { + return switch (inferred) { + case NULLABLE -> GenericsChecks.getSyntheticNullableAnnotType(state); + case NONNULL -> GenericsChecks.getSyntheticNonNullAnnotType(state); + case TYPE_VARIABLE_OR_NULLABLE -> + inferredType.isCompound() || hasParametricNullness(inferredType, config, handler, state) + ? null + : GenericsChecks.getSyntheticNullableAnnotType(state); + case TYPE_VARIABLE_OR_NONNULL -> + inferredType.isCompound() || hasParametricNullness(inferredType, config, handler, state) + ? null + : GenericsChecks.getSyntheticNonNullAnnotType(state); + }; + } + + /** + * Returns whether {@code type} has parametric nullness as NullAway decides it: it is a type + * variable, a captured one included, that carries no nullness annotation at this use and whose + * bound admits null by {@link #upperBoundIsNullable}, which counts the default for a type + * variable declared in unannotated code. Such a use includes null exactly where the type argument + * substituted for it does. The closest JSpecify notion is the {@code NO_CHANGE} nullness + * operator, which also covers an unannotated type variable whose bound excludes null and does not + * cover one declared in null-unmarked code. + * + * @see JSpecify: nullness + * operator + */ + static boolean hasParametricNullness( + Type type, Config config, Handler handler, VisitorState state) { + return type instanceof Type.TypeVar typeVariable + && !hasNullnessAnnotation(type, config) + && upperBoundIsNullable(typeVariable.asElement(), config, handler, state); + } + /** * Returns true if the upper bound of the given type variable should be treated as nullable. * @@ -417,8 +469,82 @@ static boolean declaredUpperBoundIsNullable( if (fromUnannotatedMethodOrClass(typeVarElement, config, handler, state)) { return true; } - // Models use declaration indices, which fresh inference symbols do not have. Keep looking at - // the fresh bound below, but consult its original declaration for library-model overrides. + if (libraryModelMakesBoundNullable(typeVarElement, handler, state)) { + return true; + } + Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); + return isAnnotatedAsNullable(upperBound, config); + } + + /** + * Returns true if the upper bound of the given type variable is explicitly nullable, as {@link + * #typeVariableWithNullableBound} defines it. + */ + static boolean boundIsExplicitlyNullable( + Element typeVarElement, Config config, Handler handler, VisitorState state) { + return typeVariableWithNullableBound(typeVarElement, config, handler, state) != null; + } + + /** + * Returns the type variable whose declared bound makes the bound of {@code typeVarElement} + * explicitly nullable, or {@code null} where that bound is not explicitly nullable. + * + *

A declared bound is explicitly nullable where it is annotated {@code @Nullable} or a library + * model makes it nullable; that type variable is the result. A declared bound that is another + * type variable and carries no nullness annotation is explicitly nullable where the bound of that + * type variable is, so for {@code } the + * result for {@code T} is {@code S}. Unlike {@link #upperBoundIsNullable}, a type variable + * declared in unannotated code gets no nullable default, while a {@code @Nullable} written there + * still counts, as JSpecify gives annotations in null-unmarked code their meaning. + */ + static @Nullable Element typeVariableWithNullableBound( + Element typeVarElement, Config config, Handler handler, VisitorState state) { + if (declaredBoundIsExplicitlyNullable(typeVarElement, config, handler, state)) { + return typeVarElement; + } + Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); + return !hasNullnessAnnotation(upperBound, config) && upperBound.getKind() == TypeKind.TYPEVAR + ? typeVariableWithNullableBound(upperBound.asElement(), config, handler, state) + : null; + } + + /** + * Returns true if the declared upper bound of the given type variable is annotated + * {@code @Nullable}, in every element for an intersection, or a library model makes it nullable. + * Unlike {@link #typeVariableWithNullableBound}, this does not follow a bound that is itself a + * type variable, and unlike {@link #declaredUpperBoundIsNullable}, a type variable declared in + * unannotated code gets no nullable default. + */ + static boolean declaredBoundIsExplicitlyNullable( + Element typeVarElement, Config config, Handler handler, VisitorState state) { + Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); + return isAnnotatedAsNullable(upperBound, config) + || libraryModelMakesBoundNullable(typeVarElement, handler, state); + } + + /** + * Returns the declared upper bound of {@code typeVariable}, annotated {@code @Nullable} where + * {@link #boundIsExplicitlyNullable} holds and the bound does not carry the annotation itself. + * + *

This describes the declaration and not a use of it: a {@code @Nullable T} carries its own + * nullness where it is written, and a caller that replaced it with this bound would discard it. + */ + static Type typeVariableUpperBound( + Type.TypeVar typeVariable, VisitorState state, Config config, Handler handler) { + Type upperBound = typeVariable.getUpperBound(); + if (boundIsExplicitlyNullable(typeVariable.asElement(), config, handler, state) + && !Nullness.hasNullableAnnotation(upperBound.getAnnotationMirrors().stream(), config)) { + return TypeSubstitutionUtils.typeWithAnnot( + upperBound, GenericsChecks.getSyntheticNullableAnnotType(state)); + } + return upperBound; + } + + /** Returns true if a library model overrides the upper bound of the given type variable. */ + private static boolean libraryModelMakesBoundNullable( + Element typeVarElement, Handler handler, VisitorState state) { + // Models use declaration indices, which fresh inference symbols do not have, so consult the + // original declaration of a fresh symbol. Element modeledTypeVariable = typeVarElement; while (modeledTypeVariable instanceof FreshTypeVariableSymbol freshSymbol) { modeledTypeVariable = freshSymbol.declaredSymbol; @@ -442,11 +568,14 @@ static boolean declaredUpperBoundIsNullable( return true; } } - Type upperBound = (Type) ((TypeVariable) typeVarElement.asType()).getUpperBound(); - return isAnnotatedAsNullable(upperBound, config); + return false; } - private static boolean fromUnannotatedMethodOrClass( + /** + * Returns true if {@code typeVarElement} is declared by a method or class that NullAway treats as + * unannotated code. + */ + static boolean fromUnannotatedMethodOrClass( Element typeVarElement, Config config, Handler handler, VisitorState state) { Element enclosingElement = typeVarElement.getEnclosingElement(); if (!(enclosingElement instanceof Symbol.MethodSymbol) diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java new file mode 100644 index 0000000000..6922aab756 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -0,0 +1,855 @@ +package com.uber.nullaway.generics; + +import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; + +import com.google.errorprone.VisitorState; +import com.google.errorprone.util.ASTHelpers; +import com.sun.tools.javac.code.Attribute; +import com.sun.tools.javac.code.BoundKind; +import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.code.Symtab; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.TypeTag; +import com.sun.tools.javac.code.Types; +import com.uber.nullaway.Config; +import com.uber.nullaway.Nullness; +import com.uber.nullaway.handlers.Handler; +import java.util.ArrayList; +import java.util.IdentityHashMap; +import java.util.List; +import javax.lang.model.type.TypeKind; +import org.jspecify.annotations.Nullable; + +/** + * Renders the diagnostic for a pseudo-assignment whose source type does not have the nullness its + * target type requires. + * + *

The message is built from the positions {@link NullabilityMismatches} found, and this class + * decides what a reader is told about them. The rules below are the contract every such message + * follows, and a new reporter that reaches this class inherits them; a reporter that builds its own + * message text is not bound by them and reads worse for it. + * + *

The vocabulary

+ * + *

Four words carry the message, and they mean the same thing wherever they appear. {@code found} + * is what the source has, {@code required} is what the target demands, {@code path} is where in the + * type that pair sits, and {@code note} is a fact about the source that its printed form does not + * show. A reader who has learned one message has learned every other, and a tool matching on the + * text has four stable keys rather than a sentence to parse. + * + *

The first line

+ * + *

It opens {@code incompatible nullability:} and then states the one difference, or how many + * there are where naming one would misrepresent the rest. It states the two nodes rather than + * calling the source unassignable to the target, because the difference runs both ways: a type + * argument the source states outright has to match, so {@code String} fails against + * {@code @Nullable String} as surely as the reverse. That direction is the one a reader can misread + * as a false subtype claim, since every {@code String} is a {@code @Nullable String}, so there the + * line says first that a type argument has to match exactly. It never carries the two whole types, + * which are printed below where a caret can point into them. + * + *

The caret

+ * + *

A caret marks the smallest node whose nullness differs, {@code @Nullable String} rather than + * the {@code Collection<@Nullable String>} around it, and it marks that node in both printed types. + * The comparison views the source as the target's supertype, so which node of the type the reader + * wrote the caret belongs under is a question with two answers: where the view is that same class, + * the position is the same position; where it is another class, only a node the substitution + * carried over rather than rebuilt can be pointed at. Where neither answers, the view is printed as + * {@code found as} and carries the carets, so a caret marks the type the check compared rather than + * a node in one where the difference cannot be seen. + * + *

A note explains itself in the entities the message already shows, and it appears where the + * printed source does not carry the nullness the comparison used: under a wildcard that inherits a + * bound, and under a type variable whose own declaration supplies one. Where the source wildcard + * stands at a position of the type the reader wrote, including one the supertype view carried over + * from it, the note names the type parameter it takes its bound from. Where the view rebuilt the + * wildcard, as from the supertype a subclass declares, that parameter belongs to a declaration this + * message never prints, and naming it would set a second frame of reference against the {@code + * path} line: {@code Base type argument B} beside {@code type parameter S of Sub} reads as a + * contradiction rather than as two answers. The note there states the bound and stops. Where the + * node is one a side does not print, as with the bound an unbounded wildcard leaves implicit, the + * caret rises to the deepest node that side does print, and a {@code note} says what the reader + * cannot see there. Where a position cannot be told from another, because one type instance sits at + * two of them, that side gets no caret at all: a caret under a guess is worse than none, and the + * {@code path} line still names the position. + * + *

The repairs

+ * + *

Two repairs may be offered, and both are checked before they are printed: the candidate is + * passed to the predicate that rejected the assignment, and it has to print as Java a reader could + * write, since a type the check accepts may still print {@code capture of ?}. + * + *

They differ in what they presume. Writing an explicit bound on a wildcard the reader already + * wrote is a mechanical repair of that wildcard, so it is offered wherever it works. Changing the + * required type is a claim about which side of a contract is wrong, which this class cannot know, + * so it comes with two limits: it is offered only where the required type is written at the + * diagnostic itself, as it is in a variable declaration, and it only ever adds {@code @Nullable}. + * At a call the required type comes from a signature somewhere else, and proposing an edit to it + * would be a guess at what that signature is for; taking a {@code @Nullable} away would be a guess + * of the same kind about a contract the author stated on purpose. + * + *

A repair also has to survive printing. The printer shows {@code @Nullable} and drops every + * other type-use annotation, which costs a message that only describes a type nothing, and costs a + * reader who pastes one whatever the printer left out, so a type carrying such an annotation is not + * offered. + */ +final class NullabilityMismatchMessage { + + private final GenericsChecks checks; + private final Config config; + private final Handler handler; + private final VisitorState state; + + NullabilityMismatchMessage( + GenericsChecks checks, Config config, Handler handler, VisitorState state) { + this.checks = checks; + this.config = config; + this.handler = handler; + this.state = state; + } + + /** How many mismatches a message lists before it says only how many more there are. */ + private static final int MAX_LISTED_MISMATCHES = 5; + + /** + * Builds the diagnostic for an assignment, a return, or an argument the nullability check + * rejected. + * + *

Where the traversal finds no nullness difference it can name, the message is the two types + * and the subtype relation between them, which is all that can be said about a difference nothing + * located. + * + * @param requiredTypeIsWrittenHere whether the required type is written at the diagnostic, which + * is what admits a suggestion about it + */ + String build(Type lhsType, Type rhsType, boolean requiredTypeIsWrittenHere) { + List mismatches = + new NullabilityMismatches(checks, config, handler, state).collect(lhsType, rhsType); + if (mismatches.isEmpty()) { + return plainIncompatibleTypesMessage(lhsType, rhsType); + } + List listed = + mismatches.size() > MAX_LISTED_MISMATCHES + ? mismatches.subList(0, MAX_LISTED_MISMATCHES) + : mismatches; + boolean numbered = listed.size() > 1; + StringBuilder message = new StringBuilder(summaryLine(mismatches)); + List<@Nullable TypePath> viewCarets = sourceCarets(listed); + Type comparedSourceType = sourceViewedAsTarget(lhsType, rhsType); + // a position of the view is a position of the written type where the two are one class; where + // they are not, only a node the view shares with it can be marked, and the instance says which + List<@Nullable TypePath> writtenCarets = + comparedSourceType == null ? viewCarets : instanceCarets(listed, rhsType); + MarkedType found = markedTypeLines("found", rhsType, writtenCarets, numbered); + if (found.marksPlaced() == listed.size()) { + message.append(found.lines()); + } else { + message.append(markedTypeLines("found", rhsType, noCarets(listed.size()), numbered).lines()); + if (comparedSourceType != null) { + // what the comparison reached is at no position of the type the reader wrote, so the type + // it did compare is printed too and carries the carets + message.append( + markedTypeLines("found as", comparedSourceType, viewCarets, numbered).lines()); + } + } + message.append(markedTypeLines("required", lhsType, targetCarets(listed), numbered).lines()); + for (int i = 0; i < listed.size(); i++) { + message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, rhsType)); + } + // a numbered entry stands apart from the next, so the list stays readable, and what follows + // the list stands apart from it in the same way + String separator = numbered ? "\n" : ""; + if (mismatches.size() > listed.size()) { + message.append( + String.format( + "%s\n and %d more, not listed", separator, mismatches.size() - listed.size())); + } + Type rewrittenSourceType = rewriteWithExplicitBounds(rhsType, mismatches); + String suggestion = + rewrittenSourceType == null ? null : suggestedSourceType(lhsType, rewrittenSourceType); + String targetSuggestion = + requiredTypeIsWrittenHere ? suggestedTargetType(lhsType, rhsType, mismatches) : null; + if (suggestion != null) { + message.append(String.format("%s\n did you mean %s?", separator, suggestion)); + separator = ""; + } + if (targetSuggestion != null) { + message.append( + String.format( + "%s\n consider changing the required type to:\n %s", + separator, targetSuggestion)); + } + return message.toString(); + } + + /** + * Builds the message for a difference the traversal did not locate: the two types, and the + * supertype view that lines them up where their erasures differ. + */ + private String plainIncompatibleTypesMessage(Type lhsType, Type rhsType) { + String prettyRhsType = GenericsChecks.prettyTypeForError(rhsType, state); + String prettyLhsType = GenericsChecks.prettyTypeForError(lhsType, state); + String result = + String.format( + "incompatible types: %s cannot be converted to %s", prettyRhsType, prettyLhsType); + if (!ASTHelpers.isSameType(lhsType, rhsType, state) + && lhsType.getKind() == TypeKind.DECLARED + && rhsType.getKind() == TypeKind.DECLARED + && lhsType.asElement() instanceof Symbol.ClassSymbol classSymbol) { + Type asSuper = TypeSubstitutionUtils.asSuper(state.getTypes(), rhsType, classSymbol, config); + if (asSuper != null) { + result += + String.format( + " (%s is a subtype of %s)", + prettyRhsType, GenericsChecks.prettyTypeForError(asSuper, state)); + } + } + return result; + } + + /** + * The line a reader sees first, and the only one some tools show: the difference itself where + * there is one, and how many there are where naming one would misrepresent the rest. + */ + private String summaryLine(List mismatches) { + if (mismatches.size() == 1) { + NullabilityMismatches.Mismatch only = mismatches.get(0); + // a nullable source where a non-null one is required is a subtype claim and reads as one. + // The other direction is not: every String is a @Nullable String, and what fails is that a + // type argument has to match rather than be a subtype, which the pair alone does not say + String exactly = + checks.isNullableAnnotated(only.targetNode()) + && !checks.isNullableAnnotated(only.sourceNode()) + ? "a type argument must match exactly; " + : ""; + return String.format( + "incompatible nullability: %sfound %s, required %s", + exactly, + GenericsChecks.prettyTypeForError(only.sourceNode(), state), + GenericsChecks.prettyTypeForError(only.targetNode(), state)); + } + return String.format( + "incompatible nullability: %d mismatches between source and target types", + mismatches.size()); + } + + /** + * Where each mismatch is drawn in the target, which the traversal walked as the reader wrote it. + */ + private static List<@Nullable TypePath> targetCarets( + List mismatches) { + List<@Nullable TypePath> paths = new ArrayList<>(); + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + paths.add(mismatch.targetCaret()); + } + return paths; + } + + /** + * Returns {@code sourceType} viewed as the class {@code targetType} names, or {@code null} where + * that view is the type the reader wrote or cannot be taken. + * + *

The traversal compares the source in this view at every level, so a node it reports may sit + * at no position in the type the reader wrote: viewing a {@code Sub} declared as {@code extends + * Base>} as a {@code Base} reports a node that only the declaration of + * {@code Sub} contains. Printing the view gives the caret something to point at that the + * comparison actually used. + */ + private @Nullable Type sourceViewedAsTarget(Type targetType, Type sourceType) { + if (!(targetType.tsym instanceof Symbol.ClassSymbol targetSymbol) + || targetSymbol.equals(sourceType.tsym)) { + // the same class, so the comparison ran on the type the reader wrote and its positions are + // that type's own. Whether the view would print differently decides nothing: two classes of + // one simple name print alike and remain two classes + return null; + } + return TypeSubstitutionUtils.asSuper(state.getTypes(), sourceType, targetSymbol, config); + } + + /** + * Where each mismatch is drawn in the source type as the reader wrote it, with {@code null} for + * one that type does not show. + * + *

By instance, since the view the comparison used is a type of another class and a position in + * it names nothing here: what the two share is the node itself, wherever a substitution carried + * it over rather than building one of its own. + */ + private static List<@Nullable TypePath> instanceCarets( + List mismatches, Type sourceType) { + List<@Nullable TypePath> paths = new ArrayList<>(); + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + paths.add(NullabilityMismatches.pathOfInstance(sourceType, mismatch.sourcePrintedNode())); + } + return paths; + } + + /** A caret for no position at all, one per mismatch, so the two sides stay numbered alike. */ + private static List<@Nullable TypePath> noCarets(int mismatches) { + List<@Nullable TypePath> paths = new ArrayList<>(); + for (int i = 0; i < mismatches; i++) { + paths.add(null); + } + return paths; + } + + /** + * Where each mismatch sits in the source, as the traversal viewed it. + * + *

The same positions serve the type the reader wrote and the view of it the comparison used, + * since the two agree wherever the view changed nothing; where they do not agree, the position + * reaches nothing in the written type and the caller prints the view instead. + */ + private static List<@Nullable TypePath> sourceCarets( + List mismatches) { + List<@Nullable TypePath> paths = new ArrayList<>(); + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + paths.add(mismatch.sourceCaret()); + } + return paths; + } + + /** + * Prints {@code type} on a labelled line, with a caret run under each position in {@code paths} + * and, where {@code numbered}, the index of each under its caret. + * + *

Pointing at the position is what naming the type variable cannot do. One type may hold + * several arguments for identically named variables — {@code Map, List>} has + * two for {@code E} of {@code List} — so a name leaves the reader to work out which occurrence is + * meant, and even a unique name makes them map it back onto the printed type themselves. + */ + private MarkedType markedTypeLines( + String label, Type type, List<@Nullable TypePath> paths, boolean numbered) { + String printed = type.accept(new GenericTypePrettyPrintingVisitor(state, paths), null); + StringBuilder stripped = new StringBuilder(); + StringBuilder carets = new StringBuilder(); + StringBuilder numbers = new StringBuilder(); + int marks = 0; + int i = 0; + while (i < printed.length()) { + char c = printed.charAt(i); + if (c != GenericTypePrettyPrintingVisitor.MARK_START || i + 1 >= printed.length()) { + stripped.append(c); + i++; + continue; + } + int index = printed.charAt(i + 1) - '0'; + int start = stripped.length(); + i += 2; + while (i < printed.length() + && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_END) { + stripped.append(printed.charAt(i)); + i++; + } + i++; + padTo(carets, start).append("^".repeat(Math.max(stripped.length() - start, 1))); + padTo(numbers, start).append(index + 1); + marks++; + } + String prefix = String.format(" %-9s ", label + ":"); + // the printer brackets what it was asked to, and this removes any marker regardless: nothing a + // caller marks may put a control character in front of a reader + String line = + "\n" + + prefix + + stripped + .toString() + .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_START), "") + .replace(String.valueOf(GenericTypePrettyPrintingVisitor.MARK_END), ""); + if (carets.length() > 0) { + line += "\n" + " ".repeat(prefix.length()) + carets; + if (numbered) { + line += "\n" + " ".repeat(prefix.length()) + numbers; + } + } + return new MarkedType(line, marks); + } + + /** + * A printed type and the number of positions the printer could mark in it. + * + *

The count is what tells a caller whether the type it printed is the one to draw on: a + * position the traversal reached in its own view of the source reaches nothing in the type the + * reader wrote once those two are different types. + */ + private record MarkedType(String lines, int marksPlaced) {} + + /** Pads {@code line} with spaces up to {@code column}, so the next run starts there. */ + private static StringBuilder padTo(StringBuilder line, int column) { + if (line.length() < column) { + line.append(" ".repeat(column - line.length())); + } + return line; + } + + /** + * Names where one mismatch sits and, for a numbered entry, what the two sides have there. + * + *

The two shapes carry the same fields in the same order, because a reader who has learned one + * message has learned the other: a single mismatch states its position under the two types, and + * where there are several, each entry states its own position and the pair the summary could not + * name. + */ + private String mismatchDetail( + NullabilityMismatches.Mismatch mismatch, int number, Type sourceType) { + // the root stands as a guard rather than as a case with traffic: a nullness difference at the + // root of the two types is reported by the check for assigning a @Nullable value, before a + // pseudo-assignment of type arguments is looked at + String position = mismatch.path().isRoot() ? "the type itself" : mismatch.path().describe(); + String header = number == 0 ? " " : " " + number + ". "; + String body = " ".repeat(header.length()); + StringBuilder detail = new StringBuilder(); + if (number != 0) { + detail.append("\n"); + } + detail + .append("\n") + .append(header) + .append(wrapped("path: " + position, header.length(), body + " ")); + if (number != 0) { + detail.append("\n").append(body).append("found: "); + detail.append(GenericsChecks.prettyTypeForError(mismatch.sourceNode(), state)); + detail.append("\n").append(body).append("required: "); + detail.append(GenericsChecks.prettyTypeForError(mismatch.targetNode(), state)); + } + String note = boundOriginNote(mismatch, sourceType); + if (note != null) { + detail + .append("\n") + .append(body) + .append(wrapped("note: " + note, body.length(), body + " ")); + } + return detail.toString(); + } + + /** The column a message line may not run past, which a deeply nested type reaches easily. */ + private static final int MAX_LINE_LENGTH = 100; + + /** + * Returns {@code text} broken across lines that end before {@link #MAX_LINE_LENGTH}, with every + * line after the first opening at {@code continuation}. + * + *

A type path breaks before one of its {@code ->} separators, so that a line starts with the + * step it describes; any other text breaks at a space. + */ + private static String wrapped(String text, int firstLineIndent, String continuation) { + String[] segments = text.contains(" -> ") ? text.split(" (?=-> )") : text.split(" "); + StringBuilder wrappedText = new StringBuilder(segments[0]); + int lineLength = firstLineIndent + segments[0].length(); + for (int i = 1; i < segments.length; i++) { + String segment = segments[i]; + if (lineLength + 1 + segment.length() > MAX_LINE_LENGTH) { + wrappedText.append("\n").append(continuation).append(segment); + lineLength = continuation.length() + segment.length(); + } else { + wrappedText.append(" ").append(segment); + lineLength += 1 + segment.length(); + } + } + return wrappedText.toString(); + } + + /** + * Says where the source takes a nullness its printed form does not show: the bound a wildcard + * inherits, or the bound a type variable was declared with. Returns {@code null} where the + * printed type shows it already. + * + *

A wildcard with no explicit upper bound and a captured one both take a bound the printed + * type does not state, and a reader who is not told where it comes from reads the two bounds as a + * contradiction. For a captured wildcard the note also says when the owner is unannotated, which + * is what makes the bound {@code @Nullable} and the one thing about the situation a reader can go + * and change. Unannotated is NullAway's own sense of the word: a class outside + * {@code @NullMarked} code, and also one the configuration names as unannotated. + */ + private @Nullable String boundOriginNote( + NullabilityMismatches.Mismatch mismatch, Type sourceType) { + // the node the caret sits on, not the one that differs: the note answers a reader who is + // looking at a wildcard and reading that the source has a bound the wildcard does not print + Type.WildcardType wildcard = GenericsUtils.asWildcard(mismatch.sourcePrintedNode()); + if (wildcard == null) { + // a captured wildcard is a Type.TypeVar as well, so it is ruled out above rather than here + // a type variable that carries its own @Nullable is printed with it, and needs no note + return mismatch.sourcePrintedNode() instanceof Type.TypeVar sourceTypeVariable + && !checks.isNullableAnnotated(mismatch.sourcePrintedNode()) + ? String.format( + "the source %s has no nullness of its own, so it takes the nullness of its declared" + + " upper bound", + sourceTypeVariable.tsym.getSimpleName()) + : null; + } + if (mismatch.sourcePrintedNode() instanceof Type.CapturedType) { + // a captured wildcard was captured where it was written, so its bound link still names the + // type variable of the type the user wrote, e.g. T of Flow for a (Flow) cast + Type.TypeVar capturedTypeVariable = wildcard.bound; + Symbol.ClassSymbol owner = typeVariableOwner(capturedTypeVariable); + if (capturedTypeVariable == null || owner == null) { + return null; + } + String note = + String.format( + "the source wildcard is the type argument for type parameter %s of %s", + capturedTypeVariable.tsym.getSimpleName(), owner.getSimpleName()); + return GenericsUtils.fromUnannotatedMethodOrClass( + capturedTypeVariable.tsym, config, handler, state) + ? note + String.format(", and %s is unannotated", owner.getSimpleName()) + : note; + } + if (wildcard.kind == BoundKind.EXTENDS) { + return null; + } + Type.TypeVar formalTypeVariable = + typeVariableAtPositionOf(mismatch.sourcePrintedNode(), sourceType); + Symbol.ClassSymbol owner = typeVariableOwner(formalTypeVariable); + String source = + wildcard.kind == BoundKind.UNBOUND + ? "?" + : "? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); + if (formalTypeVariable == null || owner == null) { + // no type parameter this message prints stands behind the bound: the wildcard sits at no + // position in the type the reader wrote, as happens where the supertype view rebuilt it from + // a subclass declaration, or the variable it instantiates has no named owner. The note says + // what the + // bound is and leaves where it came from alone + // "the source wildcard" rather than the symbol: two printed types carry a ? here, and the + // note is about the one the comparison used rather than about a character to go and find + return String.format( + "the source wildcard has an implicit %s upper bound", + GenericsChecks.prettyTypeForError( + GenericsUtils.wildcardUpperBound(wildcard, state, config, handler), state)); + } + return String.format( + "the source %s has no explicit upper bound, so its upper bound is inherited from type parameter %s of %s", + source, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName()); + } + + /** + * Returns the printed form of {@code rewrittenSourceType} where it is worth offering as a + * rewrite, or {@code null} where it is not. + */ + private @Nullable String suggestedSourceType(Type targetType, Type rewrittenSourceType) { + if (!printsEveryAnnotation(rewrittenSourceType)) { + // the printer shows @Nullable and drops every other type-use annotation, which is harmless + // where the type is only described and wrong where it is offered to be pasted + return null; + } + if (!isDenotable(rewrittenSourceType)) { + // the rewrite would print a type the reader cannot write, such as one holding a captured + // wildcard, and the clause invites them to paste it + return null; + } + // javac rejects a `? super S` target holding a `?` before NullAway runs, which is the one + // position where the comparison below would accept without analysing + if (!checks.subtypeParameterNullability(targetType, rewrittenSourceType, state)) { + // the rewrite does not repair every incompatibility, so suggesting it would only produce the + // same diagnostic again. This is the check's own comparison rather than a prediction of it: + // a mismatch it rejects for a reason writing a bound out does not address, such as a nullness + // difference on a concrete type argument, is one no rewritten wildcard reaches. + return null; + } + return GenericsChecks.prettyTypeForError(rewrittenSourceType, state); + } + + /** + * Returns the printed form of the target type with the nullness the source has at every position + * that differs, or {@code null} where that type is not worth offering. Whether it is offered at + * all is the caller's decision, which the class comment states. + */ + private @Nullable String suggestedTargetType( + Type targetType, Type sourceType, List mismatches) { + if (mismatches.isEmpty()) { + return null; + } + Type rewrittenTargetType = targetType; + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + Type rewritten = withNullableAddedFrom(mismatch.sourceNode(), mismatch.targetNode()); + if (rewritten == null) { + return null; + } + rewrittenTargetType = replaceAt(rewrittenTargetType, mismatch.path().steps(), 0, rewritten); + if (rewrittenTargetType == null) { + return null; + } + } + if (!printsEveryAnnotation(rewrittenTargetType) + || !isDenotable(rewrittenTargetType) + || !checks.subtypeParameterNullability(rewrittenTargetType, sourceType, state)) { + return null; + } + String printed = GenericsChecks.prettyTypeForError(rewrittenTargetType, state); + return printed.equals(GenericsChecks.prettyTypeForError(targetType, state)) ? null : printed; + } + + /** + * Returns {@code target} with {@code @Nullable} added where {@code source} carries it, or {@code + * null} where the two already agree or the annotation to copy cannot be found. + * + *

The repair only ever widens what the target accepts. Taking a {@code @Nullable} away, which + * is what the other direction would need, changes a contract the author stated on purpose, and no + * reading of the assignment says which of the two sides meant what. + */ + private @Nullable Type withNullableAddedFrom(Type source, Type target) { + if (!checks.isNullableAnnotated(source) || checks.isNullableAnnotated(target)) { + return null; + } + for (Attribute.TypeCompound annotation : source.getAnnotationMirrors()) { + if (Nullness.isNullableAnnotation(annotation.type.toString(), config)) { + return TypeSubstitutionUtils.typeWithAnnot(target, annotation.type); + } + } + return null; + } + + /** + * Returns {@code type} with the node that {@code steps} reach, starting at {@code from}, replaced + * by {@code replacement}, or {@code null} where {@code type} prints no node there, as for the + * bound an unbounded wildcard leaves implicit. + * + *

A path names the node because one {@code Type} instance can fill several positions, as one + * {@code String} does in {@code Map}, and only one of them is to change. + */ + private static @Nullable Type replaceAt( + Type type, List steps, int from, Type replacement) { + if (from == steps.size()) { + return replacement; + } + TypePath.Step step = steps.get(from); + switch (step.kind()) { + case TYPE_ARGUMENT -> { + if (!(type instanceof Type.ClassType classType) + || step.index() >= classType.getTypeArguments().size()) { + return null; + } + List typeArguments = new ArrayList<>(classType.getTypeArguments()); + Type typeArgument = + replaceAt(typeArguments.get(step.index()), steps, from + 1, replacement); + if (typeArgument == null) { + return null; + } + typeArguments.set(step.index(), typeArgument); + return TYPE_METADATA_BUILDER.createClassType( + classType, classType.getEnclosingType(), typeArguments); + } + case ENCLOSING_TYPE -> { + if (!(type instanceof Type.ClassType classType)) { + return null; + } + Type enclosingType = replaceAt(classType.getEnclosingType(), steps, from + 1, replacement); + return enclosingType == null + ? null + : TYPE_METADATA_BUILDER.createClassType( + classType, enclosingType, classType.getTypeArguments()); + } + case WILDCARD_BOUND -> { + if (!(type instanceof Type.WildcardType wildcard) || wildcard.kind != BoundKind.EXTENDS) { + return null; + } + Type bound = replaceAt(wildcard.type, steps, from + 1, replacement); + return bound == null ? null : TYPE_METADATA_BUILDER.createWildcardType(wildcard, bound); + } + case ARRAY_ELEMENT -> { + if (!(type instanceof Type.ArrayType arrayType)) { + return null; + } + Type elementType = replaceAt(arrayType.elemtype, steps, from + 1, replacement); + return elementType == null + ? null + : TYPE_METADATA_BUILDER.createArrayType(arrayType, elementType); + } + } + throw new AssertionError(step.kind()); + } + + /** + * Returns {@code sourceType} with an explicit upper bound written out for every wildcard that + * gains one, or {@code null} if there is no such wildcard. + * + *

A wildcard gains an explicit bound when it is unbounded, its implicit bound is + * {@code @Nullable}, and the target requires a non-null class type there: writing that bound out + * is the whole of the repair this class knows how to propose. Whether the result is worth + * suggesting is decided by the caller, against the rewritten type rather than against this list. + * + *

Requiring the bound to be a class type stands as a guard rather than as a filter with + * traffic: no input is known to reach it, since a target bound naming a method's type variable + * fails inference first and a class's type variable is rejected by javac. Passing it would not + * put the name in scope where the source type was declared either, because a declared type may be + * unimported there or carry a type variable among its own type arguments. + */ + private @Nullable Type rewriteWithExplicitBounds( + Type sourceType, List mismatches) { + // identity, not isSameType: a wildcard is rewritten where it occurs, not wherever an equal one + // does, and the same wildcard may be reported at several positions + IdentityHashMap boundForWildcard = new IdentityHashMap<>(); + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + Type.WildcardType sourceWildcard = mismatch.sourceWildcard(); + Type targetUpperBound = mismatch.targetUpperBound(); + if (sourceWildcard == null + || targetUpperBound == null + || sourceWildcard.kind != BoundKind.UNBOUND) { + // only an unbounded wildcard gains an upper bound by being written out + continue; + } + if (targetUpperBound.getKind() != TypeKind.DECLARED + || Nullness.hasNullableAnnotation( + targetUpperBound.getAnnotationMirrors().stream(), config) + || !Nullness.hasNullableAnnotation( + mismatch.sourceNode().getAnnotationMirrors().stream(), config)) { + // the bound to write out is not a class type, or writing it out would not make the source + // wildcard non-null, which is the only repair this method knows + continue; + } + boundForWildcard.put(sourceWildcard, targetUpperBound); + } + if (boundForWildcard.isEmpty()) { + return null; + } + return sourceType.accept( + new Type.StructuralTypeMapping<@Nullable Void>() { + @Override + public Type visitWildcardType(Type.WildcardType t, @Nullable Void unused) { + Type requiredBound = boundForWildcard.get(t); + return requiredBound == null + ? super.visitWildcardType(t, null) + : new Type.WildcardType( + requiredBound, BoundKind.EXTENDS, Symtab.instance(state.context).boundClass); + } + }, + null); + } + + /** + * Returns whether every type-use annotation in {@code type} survives printing, so that a + * suggestion naming it says what the reader would be pasting. + * + *

{@link GenericTypePrettyPrintingVisitor} prints {@code @Nullable} and drops every other + * type-use annotation. A message that only describes a type loses nothing a reader needs; a + * suggestion that drops one hands them a type that says something else about their code. + */ + private boolean printsEveryAnnotation(Type type) { + for (Attribute.TypeCompound annotation : type.getAnnotationMirrors()) { + if (!Nullness.isNullableAnnotation(annotation.type.toString(), config)) { + return false; + } + } + if (type instanceof Type.ClassType classType) { + for (Type typeArgument : classType.getTypeArguments()) { + if (!printsEveryAnnotation(typeArgument)) { + return false; + } + } + Type enclosingType = classType.getEnclosingType(); + return enclosingType.hasTag(TypeTag.NONE) || printsEveryAnnotation(enclosingType); + } + if (type instanceof Type.WildcardType wildcardType) { + return wildcardType.kind == BoundKind.UNBOUND || printsEveryAnnotation(wildcardType.type); + } + if (type instanceof Type.ArrayType arrayType) { + return printsEveryAnnotation(arrayType.elemtype); + } + return true; + } + + /** + * Returns whether {@code type} prints as Java a reader could write, so that a suggestion naming + * it is worth offering. + * + *

This mirrors {@link GenericTypePrettyPrintingVisitor}: that printer has four arms whose + * output cannot serve as a suggestion. Three emit text no declaration may contain — a captured + * wildcard prints as {@code capture of ?}, an intersection as {@code A & B}, an anonymous class + * under its binary name. The fourth prints a type that did not resolve under a bare name, which + * is writable but denotes nothing, so pasting it trades one compile error for another. Dispatch + * is by visitor rather than by {@code instanceof} because {@link Type.CapturedType} extends + * {@link Type.TypeVar} and {@link Type.IntersectionClassType} extends {@link Type.ClassType}, so + * a chain of {@code instanceof} arms would classify a capture as a type variable. + */ + private static boolean isDenotable(Type type) { + return type.accept(DENOTABILITY_VISITOR, null); + } + + private static final Types.DefaultTypeVisitor DENOTABILITY_VISITOR = + new Types.DefaultTypeVisitor<>() { + @Override + public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { + if (t.isIntersection() || t.tsym.isAnonymous()) { + return false; + } + for (Type typeArgument : t.getTypeArguments()) { + if (!typeArgument.accept(this, null)) { + return false; + } + } + Type enclosingType = t.getEnclosingType(); + return enclosingType.hasTag(TypeTag.NONE) || enclosingType.accept(this, null); + } + + @Override + public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) { + return t.kind == BoundKind.UNBOUND || t.type.accept(this, null); + } + + @Override + public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) { + return t.elemtype.accept(this, null); + } + + @Override + public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) { + return false; + } + + @Override + public Boolean visitErrorType(Type.ErrorType t, @Nullable Void unused) { + return false; + } + + @Override + public Boolean visitType(Type t, @Nullable Void unused) { + return true; + } + }; + + /** Returns the named class declaring {@code typeVariable}, or {@code null} if there is none. */ + private static Symbol.@Nullable ClassSymbol typeVariableOwner( + Type.@Nullable TypeVar typeVariable) { + if (typeVariable == null + || !(typeVariable.tsym.owner instanceof Symbol.ClassSymbol owner) + || owner.getSimpleName().isEmpty()) { + return null; + } + return owner; + } + + /** + * Returns the type variable that {@code typeArgument} instantiates where it occurs inside {@code + * enclosingType}, or {@code null} if {@code typeArgument} is not a type argument of {@code + * enclosingType} or of a type nested in it. + * + *

javac keeps a similar link in {@link Type.WildcardType#bound}, but overwrites it whenever + * the wildcard is substituted into a supertype: after viewing {@code List} as a {@code + * Collection}, the wildcard points at a type variable of an intermediate supertype rather than at + * {@code E} of {@code List}. Locating the wildcard by position reports the type the user wrote. + */ + @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) + private static Type.@Nullable TypeVar typeVariableAtPositionOf( + Type typeArgument, Type enclosingType) { + if (enclosingType instanceof Type.ArrayType arrayType) { + return typeVariableAtPositionOf(typeArgument, arrayType.elemtype); + } + if (!(enclosingType instanceof Type.ClassType classType)) { + return null; + } + List typeArguments = classType.getTypeArguments(); + List formals = classType.tsym.type.getTypeArguments(); + for (int i = 0; i < typeArguments.size(); i++) { + Type actual = typeArguments.get(i); + // identity, not isSameType: the same wildcard may appear at several positions + if (actual == typeArgument) { + return i < formals.size() && formals.get(i) instanceof Type.TypeVar formal ? formal : null; + } + Type.TypeVar nested = typeVariableAtPositionOf(typeArgument, actual); + if (nested != null) { + return nested; + } + } + return typeVariableAtPositionOf(typeArgument, classType.getEnclosingType()); + } +} diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java new file mode 100644 index 0000000000..fe9f552abf --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -0,0 +1,341 @@ +package com.uber.nullaway.generics; + +import com.google.errorprone.VisitorState; +import com.sun.tools.javac.code.BoundKind; +import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.code.Type; +import com.uber.nullaway.Config; +import com.uber.nullaway.handlers.Handler; +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Set; +import org.jspecify.annotations.Nullable; + +/** + * Finds the positions where a source type does not have the nullness a target type requires. + * + *

The search descends the two types together and reports the smallest pair of nodes that still + * differs, so that a diagnostic can point at {@code @Nullable String} rather than at the {@code + * Collection<@Nullable String>} that contains it. A reported node is not descended into, so the + * positions are disjoint and a caret drawn under one cannot sit inside another. + * + *

The two sides are addressed differently, because only one of them is traversed as the reader + * wrote it. The target is, so a mismatch names a {@link TypePath} in it, which reads as prose and + * also tells the printer where to draw a caret. The source is viewed as the target's supertype at + * every level, which is a type the reader never wrote, so a mismatch instead carries the source + * node itself; the caller locates that instance in the type the reader did write. + */ +final class NullabilityMismatches { + + private final GenericsChecks checks; + private final Config config; + private final Handler handler; + private final VisitorState state; + + /** + * The source wildcards whose bound is being compared with each target wildcard's bound, by + * identity. A bound can name its own type variable again, as in {@code X extends Sibling}, and the descent returns to a pair it has not finished; {@code + * CheckIdenticalNullabilityVisitor} accepts such a pair, so this traversal reports nothing for + * it. + */ + private final IdentityHashMap> activeBoundComparisons = + new IdentityHashMap<>(); + + NullabilityMismatches(GenericsChecks checks, Config config, Handler handler, VisitorState state) { + this.checks = checks; + this.config = config; + this.handler = handler; + this.state = state; + } + + /** + * One position where the source does not have the nullness the target requires. + * + * @param path the position in the target, which names the mismatch in prose and carries the + * target's caret + * @param targetNode the smallest node the target requires + * @param sourceNode the smallest node the source has there + * @param targetCaret the deepest position the target prints, at or above {@code path} + * @param sourcePrintedNode the deepest node the source prints for this mismatch, which is the + * wildcard itself where the bound at fault is one the wildcard leaves implicit + * @param sourceCaret the deepest position the source prints, in the source as this traversal + * views it, which is the type the caller prints where that node sits nowhere in the type the + * reader wrote + * @param sourceWildcard the source wildcard whose upper bound is at fault, or {@code null} where + * the source states the type outright + * @param targetUpperBound the bound the target requires there, which is what writing an explicit + * bound on {@code sourceWildcard} would have to produce + */ + record Mismatch( + TypePath path, + Type targetNode, + Type sourceNode, + TypePath targetCaret, + Type sourcePrintedNode, + TypePath sourceCaret, + Type.@Nullable WildcardType sourceWildcard, + @Nullable Type targetUpperBound) {} + + /** + * Where a node sits in the target, and the deepest printed position a caret can go under. + * + *

The two part company as soon as a descent reaches something the printer does not show, such + * as the upper bound an unbounded wildcard leaves implicit. Every step below such a node is + * invisible too, so {@link #caret} stops there and stays. + */ + private record Position(TypePath path, TypePath caret, boolean printed) { + + static Position root() { + return new Position(TypePath.root(), TypePath.root(), true); + } + + Position then(TypePath.Step step, boolean stepIsPrinted) { + TypePath child = path.then(step); + boolean childIsPrinted = printed && stepIsPrinted; + return new Position(child, childIsPrinted ? child : caret, childIsPrinted); + } + } + + /** + * The comparison of two upper bounds, which is the one place a difference may be repaired by + * writing a bound out, and the one place a non-null source is accepted where a nullable one is + * allowed. + * + * @param sourceWildcard the wildcard the source bound came from, or {@code null} where the source + * states the type outright + * @param targetUpperBound the bound the target requires + */ + private record BoundComparison( + Type.@Nullable WildcardType sourceWildcard, Type targetUpperBound) {} + + /** + * Returns every position where {@code sourceType} does not have the nullness {@code targetType} + * requires, in the order a traversal of the target encounters them. + */ + List collect(Type targetType, Type sourceType) { + List mismatches = new ArrayList<>(); + collect(targetType, sourceType, Position.root(), sourceType, Position.root(), null, mismatches); + return mismatches; + } + + /** + * Compares one node of the target with the node the source has there, and appends what it finds + * to {@code mismatches}. + * + * @param target the node the target requires + * @param source the node the source has there, in the view this traversal took of it + * @param targetPosition where {@code target} sits in the target, and the deepest position the + * target prints at or above it + * @param sourcePrintedNode the deepest node the source prints for this position, which stays on a + * wildcard whose bound the printed form does not show + * @param sourcePosition the same as {@code targetPosition}, in the source as viewed here + * @param bound the bound comparison this descent is part of, or {@code null} where the two nodes + * are compared as type arguments, which decides both what a repair could rewrite and whether + * a non-null source is accepted where a nullable one is allowed + * @param mismatches the list to append to + */ + private void collect( + Type target, + Type source, + Position targetPosition, + Type sourcePrintedNode, + Position sourcePosition, + @Nullable BoundComparison bound, + List mismatches) { + Type.WildcardType targetWildcard = GenericsUtils.asWildcard(target); + Type.WildcardType sourceWildcard = GenericsUtils.asWildcard(source); + if (targetWildcard != null && sourceWildcard != null) { + Set activeSources = + activeBoundComparisons.computeIfAbsent( + targetWildcard, unused -> Collections.newSetFromMap(new IdentityHashMap<>())); + if (!activeSources.add(sourceWildcard)) { + return; + } + try { + // the check compares the effective upper bounds, and only an `? extends X` wildcard prints + // the bound it is compared by: `?` and `? super X` take one from a type variable + Type targetUpperBound = + GenericsUtils.wildcardUpperBound(targetWildcard, state, config, handler); + Type sourceUpperBound = + GenericsUtils.wildcardUpperBound(sourceWildcard, state, config, handler); + collect( + targetUpperBound, + sourceUpperBound, + targetPosition.then( + TypePath.Step.wildcardBound(), targetWildcard.kind == BoundKind.EXTENDS), + sourceWildcard.kind == BoundKind.EXTENDS ? sourceUpperBound : sourcePrintedNode, + sourcePosition.then( + TypePath.Step.wildcardBound(), sourceWildcard.kind == BoundKind.EXTENDS), + new BoundComparison(sourceWildcard, targetUpperBound), + mismatches); + } finally { + activeSources.remove(sourceWildcard); + } + return; + } + if (targetWildcard != null && targetWildcard.kind == BoundKind.EXTENDS) { + // a type argument the source states outright, against a bound the target states, as with + // List against ? extends List + collect( + targetWildcard.type, + source, + targetPosition.then(TypePath.Step.wildcardBound(), true), + sourcePrintedNode, + sourcePosition, + new BoundComparison(null, targetWildcard.type), + mismatches); + return; + } + if (sourceWildcard != null || targetWildcard != null) { + // a wildcard on one side only, in a position javac itself rejects before NullAway runs + return; + } + if (bound != null + && source instanceof Type.TypeVar sourceTypeVar + && !(source instanceof Type.CapturedType) + && !checks.isNullableAnnotated(source)) { + // against a bound, a type variable that says nothing at the use site is judged by the bound + // it was declared with, which is what the check compares and what the printed T does not + // show. A @Nullable T says it, and is compared as written + source = GenericsUtils.typeVariableUpperBound(sourceTypeVar, state, config, handler); + } + boolean sourceIsNullable = checks.isNullableAnnotated(source); + boolean targetIsNullable = checks.isNullableAnnotated(target); + if (sourceIsNullable != targetIsNullable && (sourceIsNullable || bound == null)) { + // the smallest pair that differs. An upper bound accepts a non-null source where a nullable + // one is allowed; a type argument the source states outright has to match + mismatches.add( + new Mismatch( + targetPosition.path(), + target, + source, + targetPosition.caret(), + sourcePrintedNode, + sourcePosition.caret(), + bound == null ? null : bound.sourceWildcard(), + bound == null ? null : bound.targetUpperBound())); + return; + } + if (target instanceof Type.ClassType targetClassType + && source instanceof Type.ClassType sourceClassType) { + collectFromClassTypes( + targetClassType, sourceClassType, targetPosition, sourcePosition, mismatches); + return; + } + if (target instanceof Type.ArrayType targetArrayType + && source instanceof Type.ArrayType sourceArrayType) { + collect( + targetArrayType.elemtype, + sourceArrayType.elemtype, + targetPosition.then(TypePath.Step.arrayElement(), true), + sourceArrayType.elemtype, + sourcePosition.then(TypePath.Step.arrayElement(), true), + null, + mismatches); + } + } + + /** Descends into the type arguments and the enclosing type of two class types. */ + private void collectFromClassTypes( + Type.ClassType target, + Type.ClassType source, + Position targetPosition, + Position sourcePosition, + List mismatches) { + if (!(target.tsym instanceof Symbol.ClassSymbol targetSymbol)) { + return; + } + Type sourceAsSuper = + TypeSubstitutionUtils.asSuper(state.getTypes(), source, targetSymbol, config); + if (!(sourceAsSuper instanceof Type.ClassType sourceAsTarget) + || sourceAsSuper.isRaw() + || target.isRaw()) { + return; + } + List targetArguments = target.getTypeArguments(); + List sourceArguments = sourceAsTarget.getTypeArguments(); + if (targetArguments.size() != sourceArguments.size()) { + return; + } + List formals = target.tsym.type.getTypeArguments(); + for (int i = 0; i < targetArguments.size(); i++) { + Type.TypeVar formal = + i < formals.size() && formals.get(i) instanceof Type.TypeVar typeVar ? typeVar : null; + collect( + targetArguments.get(i), + sourceArguments.get(i), + targetPosition.then(TypePath.Step.typeArgument(i, formal, targetSymbol), true), + sourceArguments.get(i), + sourcePosition.then(TypePath.Step.typeArgument(i, formal, targetSymbol), true), + null, + mismatches); + } + collect( + target.getEnclosingType(), + sourceAsTarget.getEnclosingType(), + targetPosition.then(TypePath.Step.enclosingType(), true), + sourceAsTarget.getEnclosingType(), + sourcePosition.then(TypePath.Step.enclosingType(), true), + null, + mismatches); + } + + /** + * Returns where {@code node} occurs inside {@code type}, or {@code null} where it occurs nowhere + * or at more than one position. + * + *

Identity, not equality: the caller has a node the traversal reached and wants the place the + * printer will print it, and javac hands back one instance for a plain reference such as {@code + * String}. Where an instance sits at two positions nothing says which one was compared, and a + * caret under a guess is worse than none, so the search reports neither. + */ + static @Nullable TypePath pathOfInstance(Type type, Type node) { + List found = new ArrayList<>(); + findInstance(type, node, TypePath.root(), found); + return found.size() == 1 ? found.get(0) : null; + } + + /** + * Appends to {@code found} every position of {@code type} that holds {@code node} itself, walking + * the type the way {@link GenericTypePrettyPrintingVisitor} prints it so that a position found + * here is one that printer can mark. + */ + @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) + private static void findInstance(Type type, Type node, TypePath path, List found) { + if (type == node) { + found.add(path); + return; + } + if (type instanceof Type.CapturedType capturedType) { + // the printer treats a capture and the wildcard it captured as one node, and so does the + // traversal above, so neither is a step of its own + findInstance(capturedType.wildcard, node, path, found); + return; + } + if (type instanceof Type.WildcardType wildcardType) { + if (wildcardType.kind != BoundKind.UNBOUND) { + findInstance(wildcardType.type, node, path.then(TypePath.Step.wildcardBound()), found); + } + return; + } + if (type instanceof Type.ArrayType arrayType) { + findInstance(arrayType.elemtype, node, path.then(TypePath.Step.arrayElement()), found); + return; + } + if (type instanceof Type.ClassType classType) { + List typeArguments = classType.getTypeArguments(); + for (int i = 0; i < typeArguments.size(); i++) { + findInstance( + typeArguments.get(i), + node, + path.then(TypePath.Step.typeArgument(i, null, null)), + found); + } + findInstance( + classType.getEnclosingType(), node, path.then(TypePath.Step.enclosingType()), found); + } + } +} diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java index 13a35aaa94..21a909c975 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/PolyNullInference.java @@ -15,7 +15,7 @@ import com.uber.nullaway.LibraryModels.PolyNullLocation.Position; import com.uber.nullaway.LibraryModels.PolyNullLocation.Return; import com.uber.nullaway.NullabilityUtil; -import com.uber.nullaway.Nullness; +import com.uber.nullaway.handlers.Handler; import com.uber.nullaway.librarymodel.NestedTypePathUpdater; import java.util.ArrayList; import java.util.IdentityHashMap; @@ -57,10 +57,23 @@ boolean hasReturnLocations() { private PolyNullInference() {} - /** Applies a resolved PolyNull annotation to every modeled parameter and return location. */ + /** + * Applies the resolved shared PolyNull variable to every modeled parameter and return location. + * + *

Each location takes the annotation that {@link GenericsUtils#inferredNullnessAnnotation} + * gives its type, as the type javac inferred for a method's own type variable does in {@link + * TypeSubstitutionUtils}. A type variable with a nullness annotation, such as an explicit type + * argument, takes {@code @Nullable} for {@code NULLABLE} and {@code TYPE_VARIABLE_OR_NULLABLE}, + * and {@code @NonNull} otherwise. + */ @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality checks static Type.MethodType applyToMethodType( - Type.MethodType methodType, ImmutableSet locations, Type annotationType) { + Type.MethodType methodType, + ImmutableSet locations, + ConstraintSolver.InferredNullability inferred, + VisitorState state, + Config config, + Handler handler) { boolean changed = false; ListBuffer updatedParameterTypes = new ListBuffer<>(); int parameterIndex = 0; @@ -69,12 +82,20 @@ static Type.MethodType applyToMethodType( remaining = remaining.tail, parameterIndex++) { Type parameterType = remaining.head; Type updatedParameterType = - applyToType(parameterType, new Parameter(parameterIndex), locations, annotationType); + applyToType( + parameterType, + new Parameter(parameterIndex), + locations, + inferred, + state, + config, + handler); updatedParameterTypes.append(updatedParameterType); changed |= updatedParameterType != parameterType; } Type returnType = methodType.restype; - Type updatedReturnType = applyToReturnType(returnType, locations, annotationType); + Type updatedReturnType = + applyToReturnType(returnType, locations, inferred, state, config, handler); changed |= updatedReturnType != returnType; return changed ? new Type.MethodType( @@ -82,17 +103,27 @@ static Type.MethodType applyToMethodType( : methodType; } - /** Applies a resolved PolyNull annotation to every modeled location within a return type. */ + /** + * Applies the resolved shared PolyNull variable to every modeled location within a return type, + * as {@link #applyToMethodType} does. + */ static Type applyToReturnType( - Type returnType, ImmutableSet locations, Type annotationType) { - return applyToType(returnType, new Return(), locations, annotationType); + Type returnType, + ImmutableSet locations, + ConstraintSolver.InferredNullability inferred, + VisitorState state, + Config config, + Handler handler) { + return applyToType(returnType, new Return(), locations, inferred, state, config, handler); } /** Resolves PolyNull nullness by invocation after a shared generic-inference solver run. */ - static IdentityHashMap resolveNullnessByInvocation( - IdentityHashMap contexts, - Map solution) { - IdentityHashMap nullnessByInvocation = new IdentityHashMap<>(); + static IdentityHashMap + resolveNullnessByInvocation( + IdentityHashMap contexts, + Map solution) { + IdentityHashMap + nullnessByInvocation = new IdentityHashMap<>(); for (Map.Entry entry : contexts.entrySet()) { nullnessByInvocation.put( entry.getKey(), resolveContext(entry.getKey(), entry.getValue(), solution)); @@ -101,18 +132,14 @@ static IdentityHashMap resolveNullnessByInvocati } /** Resolves the shared PolyNull variable for one invocation. */ - static Nullness resolveContext( + static ConstraintSolver.InferredNullability resolveContext( MethodInvocationTree invocationTree, PolyNullInferenceContext inferenceContext, Map solution) { - ConstraintSolver.InferredNullability inferred = - solution.getOrDefault( - new ConstraintSolver.InferenceVariable( - inferenceContext.inferenceVariable().asElement(), invocationTree), - ConstraintSolver.InferredNullability.NONNULL); - return inferred == ConstraintSolver.InferredNullability.NULLABLE - ? Nullness.NULLABLE - : Nullness.NONNULL; + return solution.getOrDefault( + new ConstraintSolver.InferenceVariable( + inferenceContext.inferenceVariable().asElement(), invocationTree), + ConstraintSolver.InferredNullability.NONNULL); } /** @@ -245,13 +272,25 @@ private static Type.TypeVar createInferenceVariable( return variable; } - /** Applies {@code annotationType} at modeled locations within one method-type component. */ + /** Applies {@code inferred} at modeled locations within one method-type component. */ private static Type applyToType( - Type type, Position position, ImmutableSet locations, Type annotationType) { + Type type, + Position position, + ImmutableSet locations, + ConstraintSolver.InferredNullability inferred, + VisitorState state, + Config config, + Handler handler) { Type updated = type; for (PolyNullLocation location : locations) { if (location.position().equals(position)) { - updated = NestedTypePathUpdater.addAnnotation(updated, location.typePath(), annotationType); + updated = + NestedTypePathUpdater.addAnnotation( + updated, + location.typePath(), + leaf -> + GenericsUtils.inferredNullnessAnnotation( + leaf, inferred, config, handler, state)); } } return updated; diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java new file mode 100644 index 0000000000..c42f9b0c01 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -0,0 +1,122 @@ +package com.uber.nullaway.generics; + +import com.google.common.collect.ImmutableList; +import com.sun.tools.javac.code.Symbol; +import com.sun.tools.javac.code.Type; +import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; + +/** + * A position inside a printed type, as the sequence of descents that reaches it from the root. + * + *

A position rather than an instance: javac hands back one {@code Type} instance for a plain + * reference such as {@code String}, and substitution can put one instance at two type-argument + * positions, so a node cannot be named by identity. The same path addresses the node for two + * purposes that have to agree, a caret drawn under it by {@link GenericTypePrettyPrintingVisitor} + * and the prose that names it in a diagnostic, which is why the steps are those the printer takes. + */ +final class TypePath { + + /** One descent into a type. */ + record Step( + Kind kind, int index, Type.@Nullable TypeVar formal, Symbol.@Nullable ClassSymbol owner) { + + enum Kind { + /** Into the type argument at {@link Step#index}. */ + TYPE_ARGUMENT, + /** Into the declared upper bound of a wildcard. */ + WILDCARD_BOUND, + /** Into the element type of an array. */ + ARRAY_ELEMENT, + /** Into the enclosing instance type of an inner class. */ + ENCLOSING_TYPE + } + + static Step typeArgument( + int index, Type.@Nullable TypeVar formal, Symbol.@Nullable ClassSymbol owner) { + return new Step(Kind.TYPE_ARGUMENT, index, formal, owner); + } + + static Step wildcardBound() { + return new Step(Kind.WILDCARD_BOUND, -1, null, null); + } + + static Step arrayElement() { + return new Step(Kind.ARRAY_ELEMENT, -1, null, null); + } + + static Step enclosingType() { + return new Step(Kind.ENCLOSING_TYPE, -1, null, null); + } + + /** + * Whether this step reaches the same node as {@code other}, ignoring the names carried for + * prose. Two steps of the same kind and index address one node however they were built. + */ + boolean reachesSameNodeAs(Step other) { + return kind == other.kind && index == other.index; + } + + /** Names this step for a reader, as {@code Map type argument K} or {@code array element}. */ + String describe() { + return switch (kind) { + case TYPE_ARGUMENT -> + formal == null || owner == null + ? "type argument " + (index + 1) + : owner.getSimpleName() + " type argument " + formal.tsym.getSimpleName(); + case WILDCARD_BOUND -> "wildcard upper bound"; + case ARRAY_ELEMENT -> "array element"; + case ENCLOSING_TYPE -> "enclosing type"; + }; + } + } + + private static final TypePath ROOT = new TypePath(ImmutableList.of()); + + private final ImmutableList steps; + + private TypePath(ImmutableList steps) { + this.steps = steps; + } + + /** The path of the type itself, which no step has descended from. */ + static TypePath root() { + return ROOT; + } + + /** Returns this path extended by {@code step}. */ + TypePath then(Step step) { + return new TypePath(ImmutableList.builder().addAll(steps).add(step).build()); + } + + /** Returns the descents from the root, in order. */ + ImmutableList steps() { + return steps; + } + + boolean isRoot() { + return steps.isEmpty(); + } + + /** Whether this path and {@code other} address the same node. */ + boolean reachesSameNodeAs(TypePath other) { + if (steps.size() != other.steps.size()) { + return false; + } + for (int i = 0; i < steps.size(); i++) { + if (!steps.get(i).reachesSameNodeAs(other.steps.get(i))) { + return false; + } + } + return true; + } + + /** + * Names this path for a reader, as {@code Map type argument V -> List type argument E -> wildcard + * upper bound}. The arrow is ASCII so that the diagnostic survives a console encoding that has no + * arrow character. + */ + String describe() { + return steps.stream().map(Step::describe).collect(Collectors.joining(" -> ")); + } +} diff --git a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java index 298c2ceab0..f7acb58e41 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypeSubstitutionUtils.java @@ -1,7 +1,6 @@ package com.uber.nullaway.generics; import static com.uber.nullaway.generics.ClassDeclarationNullnessAnnotUtils.getAnnotatedSupertype; -import static com.uber.nullaway.generics.ConstraintSolver.InferredNullability.NULLABLE; import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; import com.google.common.base.Verify; @@ -16,6 +15,7 @@ import com.sun.tools.javac.util.ListBuffer; import com.uber.nullaway.Config; import com.uber.nullaway.Nullness; +import com.uber.nullaway.handlers.Handler; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; @@ -143,7 +143,7 @@ public static Type memberType(Types types, Type t, Symbol sym, Config config) { */ public static Type restoreExplicitNullabilityAnnotations( Type origType, Type newType, Types types, Config config) { - return new RestoreNullnessAnnotationsVisitor(types, config).visit(newType, origType); + return new RestoreNullnessAnnotationsVisitor(types, config, null).visit(newType, origType); } /** @@ -233,7 +233,11 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound( * *

3 . Apply the nullability annotations from the result of 2 to {@code typeToUpdate}. So, if * {@code typeToUpdate} is {@code List}, and the result of 2 is {@code List<@Nullable T>}, - * the final result will be {@code List<@Nullable String>}. + * the final result will be {@code List<@Nullable String>}. Step 1 leaves a variable inferred as + * {@link ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NULLABLE} or {@link + * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL} unannotated, and step 3 resolves + * it with the annotation, if any, that {@link GenericsUtils#inferredNullnessAnnotation} gives the + * type javac inferred. * * @param typeToUpdate the type to update * @param origType the original type with type variables and possibly explicit nullability @@ -241,6 +245,7 @@ public static Type.WildcardType replaceImplicitWildcardUpperBound( * @param typeVarNullability a map from type variable elements to their inferred nullability * @param state the visitor state * @param config the NullAway config + * @param handler the NullAway handler, which decides whether a type variable's bound admits null * @return the updated type with inferred nullability applied */ static Type updateTypeWithInferredNullability( @@ -248,7 +253,8 @@ static Type updateTypeWithInferredNullability( Type origType, @Nullable Map typeVarNullability, VisitorState state, - Config config) { + Config config, + Handler handler) { if (typeVarNullability == null) { // no updates to perform return typeToUpdate; @@ -262,15 +268,20 @@ static Type updateTypeWithInferredNullability( origType, inferredNullabilitySubstituted, state.getTypes(), config); // step 3 // TODO optimize these steps to avoid doing so many substitutions in the future, if needed - return restoreExplicitNullabilityAnnotations( - origExplicitAnnotationsRestored, typeToUpdate, state.getTypes(), config); + // the only step that sees both the inferred nullness and the type javac inferred, so a + // variable step 1 left unannotated is resolved here + return new RestoreNullnessAnnotationsVisitor( + state.getTypes(), + config, + new InferredTypeVariableNullness(typeVarNullability, state, handler)) + .visit(typeToUpdate, origExplicitAnnotationsRestored); } /** * Updates a method type {@code typeToUpdate} by applying inferred nullability for type variables. * The update is applied to the argument types, return type, and thrown types of the method type, - * using {@link #updateMethodTypeWithInferredNullability(Type.MethodType, Type.MethodType, Map, - * VisitorState, Config)} + * using {@link #updateTypeWithInferredNullability(Type, Type, Map, VisitorState, Config, + * Handler)} * * @param methodTypeToUpdate method type to update * @param origMethodType original method type, with type variables and possibly explicit @@ -278,6 +289,7 @@ static Type updateTypeWithInferredNullability( * @param typeVarNullability a map from type variable elements to their inferred nullability * @param state the visitor state * @param config the NullAway config + * @param handler the NullAway handler, which decides whether a type variable's bound admits null * @return the updated method type with inferred nullability applied */ @SuppressWarnings("ReferenceEquality") @@ -286,18 +298,20 @@ public static Type.MethodType updateMethodTypeWithInferredNullability( Type.MethodType origMethodType, @Nullable Map typeVarNullability, VisitorState state, - Config config) { + Config config, + Handler handler) { List argtypes = methodTypeToUpdate.argtypes; Type restype = methodTypeToUpdate.restype; List thrown = methodTypeToUpdate.thrown; List argtypes1 = updateTypeListNullability( - argtypes, origMethodType.argtypes, typeVarNullability, state, config); + argtypes, origMethodType.argtypes, typeVarNullability, state, config, handler); Type restype1 = updateTypeWithInferredNullability( - restype, origMethodType.restype, typeVarNullability, state, config); + restype, origMethodType.restype, typeVarNullability, state, config, handler); List thrown1 = - updateTypeListNullability(thrown, origMethodType.thrown, typeVarNullability, state, config); + updateTypeListNullability( + thrown, origMethodType.thrown, typeVarNullability, state, config, handler); if (argtypes1 == argtypes && restype1 == restype && thrown1 == thrown) { return methodTypeToUpdate; } else { @@ -311,14 +325,16 @@ private static List updateTypeListNullability( List origTypes, @Nullable Map typeVarNullability, VisitorState state, - Config config) { + Config config, + Handler handler) { ListBuffer buf = new ListBuffer<>(); boolean changed = false; for (List l = typesToUpdate, l1 = origTypes; l.nonEmpty(); l = l.tail, l1 = l1.tail) { Type toUpdate = l.head; Type orig = l1.head; Type t2 = - updateTypeWithInferredNullability(toUpdate, orig, typeVarNullability, state, config); + updateTypeWithInferredNullability( + toUpdate, orig, typeVarNullability, state, config, handler); buf.append(t2); if (t2 != toUpdate) { changed = true; @@ -345,6 +361,16 @@ private static Type substituteInferredNullabilityForTypeVariables( ListBuffer inferredTypes = new ListBuffer<>(); for (Map.Entry entry : typeVarNullability.entrySet()) { + Type annotType = + switch (entry.getValue()) { + case NULLABLE -> GenericsChecks.getSyntheticNullableAnnotType(state); + case NONNULL -> GenericsChecks.getSyntheticNonNullAnnotType(state); + // step 3 resolves these against the type javac inferred + case TYPE_VARIABLE_OR_NULLABLE, TYPE_VARIABLE_OR_NONNULL -> null; + }; + if (annotType == null) { + continue; + } // find all TypeVars occurring in targetType with the same symbol and substitute for those. // we can have multiple such TypeVars due to previous substitutions that modified the type // in some way, e.g., by changing its bounds @@ -353,12 +379,7 @@ private static Type substituteInferredNullabilityForTypeVariables( targetType.accept(tvc, null); for (Type.TypeVar tv : tvc.getMatches()) { typeVars.append(tv); - inferredTypes.append( - typeWithAnnot( - tv, - entry.getValue() == NULLABLE - ? GenericsChecks.getSyntheticNullableAnnotType(state) - : GenericsChecks.getSyntheticNonNullAnnotType(state))); + inferredTypes.append(typeWithAnnot(tv, annotType)); } } List typeVarsToReplace = typeVars.toList(); @@ -407,6 +428,16 @@ static Type substituteTypeVariables( return subst(types, targetType, typeVarsToReplace, replacementTypes.toList(), config); } + /** + * The inferred nullness of the type variables of a call, with what {@link + * GenericsUtils#inferredNullnessAnnotation} needs to decide whether a type variable's bound + * admits null. + */ + private record InferredTypeVariableNullness( + Map typeVarNullability, + VisitorState state, + Handler handler) {} + /** * A visitor that restores explicit nullability annotations on types nested within another type to * the corresponding positions in the visited type. If no annotations need to be restored, returns @@ -588,9 +619,25 @@ private Type restoreImplicitWildcardBound(BoundPair pair, Type targetBound, Type return completed.resultType; } - RestoreNullnessAnnotationsVisitor(Types types, Config config) { + /** + * The inferred nullness whose {@link + * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NULLABLE} and {@link + * ConstraintSolver.InferredNullability#TYPE_VARIABLE_OR_NONNULL} variables this visitor + * resolves against the visited type, or {@code null} to resolve none. Set only in the step that + * copies inferred nullness onto the destination type, which is the type javac inferred wherever + * one is available; that step alone can tell whether javac inferred a type variable or a class + * type. A generic method reference keeps its declared type as the destination where {@link + * Config#isNullableBoundInferenceEnabled} is false or javac's type for the referenced method + * has another number of parameters. Where that predicate is false, the solver produces none of + * these variables. + */ + private final @Nullable InferredTypeVariableNullness inferredNullness; + + RestoreNullnessAnnotationsVisitor( + Types types, Config config, @Nullable InferredTypeVariableNullness inferredNullness) { this.types = types; this.config = config; + this.inferredNullness = inferredNullness; } @Override @@ -891,7 +938,10 @@ public Type visitForAll(Type.ForAll t, Type other) { * Updates the nullability annotations on a type {@code t} based on the nullability annotations * on a type {@code other}. When {@code other} is an intersection, copies the nullness * annotation of the first explicit component that carries one and whose nullability matches the - * intersection's. If no such component exists, returns {@code t} unchanged. + * intersection's. If no such component exists, returns {@code t} unchanged. Where {@code other} + * is an unannotated type variable that inference resolved to {@code TYPE_VARIABLE_OR_NULLABLE} + * or {@code TYPE_VARIABLE_OR_NONNULL}, adds to {@code t} the annotation that {@link + * GenericsUtils#inferredNullnessAnnotation} gives it, if any. * * @param t the type to update * @param other the type to update from @@ -918,7 +968,19 @@ private Type updateDirectNullabilityAnnotationsForType(Type t, Type other) { return typeWithAnnot(t, annot); } } - return t; + if (inferredNullness == null || !(other instanceof Type.TypeVar)) { + return t; + } + ConstraintSolver.InferredNullability inferred = + inferredNullness.typeVarNullability().get(other.tsym); + if (inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NULLABLE + && inferred != ConstraintSolver.InferredNullability.TYPE_VARIABLE_OR_NONNULL) { + return t; + } + Type annotationType = + GenericsUtils.inferredNullnessAnnotation( + t, inferred, config, inferredNullness.handler(), inferredNullness.state()); + return annotationType == null ? t : TypeSubstitutionUtils.typeWithAnnot(t, annotationType); } /** diff --git a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java index d19e84eaed..25345990ed 100644 --- a/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java +++ b/nullaway/src/main/java/com/uber/nullaway/librarymodel/NestedTypePathUpdater.java @@ -1,5 +1,6 @@ package com.uber.nullaway.librarymodel; +import static com.uber.nullaway.NullabilityUtil.castToNonNull; import static com.uber.nullaway.generics.TypeMetadataBuilder.TYPE_METADATA_BUILDER; import com.google.common.base.Verify; @@ -10,6 +11,8 @@ import com.sun.tools.javac.util.ListBuffer; import com.uber.nullaway.generics.TypeSubstitutionUtils; import com.uber.nullaway.libmodel.NestedAnnotationInfo; +import java.util.function.Function; +import org.jspecify.annotations.Nullable; /** Updates a type at a nested location identified by a library-model type path. */ @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality checks @@ -21,16 +24,26 @@ private enum UpdateKind { } private final ImmutableList typePath; - private final Type annotationOrReplacementType; private final UpdateKind updateKind; + /** The type that replaces the type at {@link #typePath}, for {@link UpdateKind#REPLACE_TYPE}. */ + private final @Nullable Type replacementType; + + /** + * For {@link UpdateKind#ADD_ANNOTATION}, maps the type at {@link #typePath} to the annotation + * type added to it, or to {@code null} where that type stays unchanged. + */ + private final @Nullable Function annotationFor; + private NestedTypePathUpdater( ImmutableList typePath, - Type annotationOrReplacementType, - UpdateKind updateKind) { + UpdateKind updateKind, + @Nullable Type replacementType, + @Nullable Function annotationFor) { this.typePath = typePath; - this.annotationOrReplacementType = annotationOrReplacementType; this.updateKind = updateKind; + this.replacementType = replacementType; + this.annotationFor = annotationFor; } /** @@ -40,7 +53,24 @@ private NestedTypePathUpdater( */ public static Type addAnnotation( Type type, ImmutableList typePath, Type annotationType) { - return new NestedTypePathUpdater(typePath, annotationType, UpdateKind.ADD_ANNOTATION) + return addAnnotation(type, typePath, leaf -> annotationType); + } + + /** + * Adds the annotation type that {@code annotationFor} returns for the type at {@code typePath} to + * that type, as {@link #addAnnotation(Type, ImmutableList, Type)} adds a fixed one; where {@code + * annotationFor} returns {@code null}, the type stays unchanged. A wildcard or a captured type + * variable at {@code typePath} is passed to {@code annotationFor} itself, and the annotation it + * returns is added to its upper bound: the bound of {@code ? extends}, the upper bound of the + * corresponding type parameter for another wildcard, or the upper bound of the capture. + * + * @return the updated type, or the original {@code type} instance if no change was made + */ + public static Type addAnnotation( + Type type, + ImmutableList typePath, + Function annotationFor) { + return new NestedTypePathUpdater(typePath, UpdateKind.ADD_ANNOTATION, null, annotationFor) .apply(type); } @@ -51,7 +81,8 @@ public static Type addAnnotation( */ public static Type replaceType( Type type, ImmutableList typePath, Type replacement) { - return new NestedTypePathUpdater(typePath, replacement, UpdateKind.REPLACE_TYPE).apply(type); + return new NestedTypePathUpdater(typePath, UpdateKind.REPLACE_TYPE, replacement, null) + .apply(type); } private Type apply(Type type) { @@ -59,9 +90,18 @@ private Type apply(Type type) { } private Type updateLeaf(Type type) { - return updateKind == UpdateKind.ADD_ANNOTATION - ? TypeSubstitutionUtils.typeWithAnnot(type, annotationOrReplacementType) - : annotationOrReplacementType; + if (updateKind == UpdateKind.REPLACE_TYPE) { + return castToNonNull(replacementType); + } + Type annotationType = annotationTypeFor(type); + return annotationType == null + ? type + : TypeSubstitutionUtils.typeWithAnnot(type, annotationType); + } + + /** Returns the annotation type to add to {@code type} at {@link #typePath}, or {@code null}. */ + private @Nullable Type annotationTypeFor(Type type) { + return castToNonNull(annotationFor).apply(type); } @Override @@ -117,15 +157,20 @@ public Type visitWildcardType(Type.WildcardType t, Integer pathIndex) { if (updateKind == UpdateKind.REPLACE_TYPE) { return updateLeaf(t); } + Type annotationType = annotationTypeFor(t); + if (annotationType == null) { + // diff-coverage: ignore -- PolyNull inference returns no annotation only for a type + // variable or an intersection + return t; + } if (t.kind == BoundKind.EXTENDS) { return TYPE_METADATA_BUILDER.createWildcardType( - t, TypeSubstitutionUtils.typeWithAnnot(t.type, annotationOrReplacementType)); + t, TypeSubstitutionUtils.typeWithAnnot(t.type, annotationType)); } Type.TypeVar formalTypeVariable = Verify.verifyNotNull(t.bound, "wildcard has no corresponding formal type variable"); Type updatedUpperBound = - TypeSubstitutionUtils.typeWithAnnot( - formalTypeVariable.getUpperBound(), annotationOrReplacementType); + TypeSubstitutionUtils.typeWithAnnot(formalTypeVariable.getUpperBound(), annotationType); return TypeSubstitutionUtils.replaceImplicitWildcardUpperBound( t, formalTypeVariable, updatedUpperBound); } @@ -184,11 +229,14 @@ public Type visitCapturedType(Type.CapturedType t, Integer pathIndex) { updatedWildcard = (Type.WildcardType) wildcard.accept(this, pathIndex); } else { Verify.verify(pathIndex == typePath.size(), "path index out of bounds"); + Type annotationType = annotationTypeFor(t); + if (annotationType == null) { + return t; + } Type updatedUpperBound = - TypeSubstitutionUtils.typeWithAnnot(t.getUpperBound(), annotationOrReplacementType); + TypeSubstitutionUtils.typeWithAnnot(t.getUpperBound(), annotationType); if (wildcard.kind == BoundKind.EXTENDS) { - Type updatedBound = - TypeSubstitutionUtils.typeWithAnnot(wildcard.type, annotationOrReplacementType); + Type updatedBound = TypeSubstitutionUtils.typeWithAnnot(wildcard.type, annotationType); updatedWildcard = TYPE_METADATA_BUILDER.createWildcardType(wildcard, updatedBound); } else { // The capture supplies the resolved upper bound, including receiver substitutions. diff --git a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java index ea8a80bb89..9b60f8f6af 100644 --- a/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java +++ b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java @@ -127,7 +127,7 @@ static boolean ownExtendsObject(Collection collection) { } static boolean callOwnExtendsObject(Collection<@Nullable String> collection) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required Object return ownExtendsObject(collection); } } @@ -513,7 +513,7 @@ class Test { return list.toArray(); } static Object[] invalidCall(List list) { - // BUG: Diagnostic contains: incompatible types: @Nullable Object [] cannot be converted to Object [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return list.toArray(); } static class DelegatingList extends AbstractList { diff --git a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java index 432d2b3443..5779fd78dd 100644 --- a/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/ParameterAssignmentTests.java @@ -72,14 +72,14 @@ public void nestedParameterNullness() { @NullMarked class Test { void typeArgumentMismatchIsReported(List p, List<@Nullable String> q) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String p = q; } void matchingTypeArgumentsAreAllowed(List<@Nullable String> p, List<@Nullable String> q) { p = q; } void arrayElementMismatchIsReported(String[] p, @Nullable String[] q) { - // BUG: Diagnostic contains: incompatible types: @Nullable String [] cannot be converted to String [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String p = q; } void matchingArrayElementTypesAreAllowed(@Nullable String[] p, @Nullable String[] q) { diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java index 77aee54f7f..ccea236780 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitorTests.java @@ -589,7 +589,12 @@ private static final class CountingVisitor extends CheckIdenticalNullabilityVisi private int budget; CountingVisitor(VisitorState state, NullAway nullAway, int budget) { - super(state, nullAway.getGenericsChecks(), nullAway.getConfig(), nullAway.getHandler()); + super( + state, + nullAway.getGenericsChecks(), + nullAway.getConfig(), + nullAway.getHandler(), + ComparisonContext.NONE); this.budget = budget; } diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java index dbef2b0dc9..2478781b62 100644 --- a/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/generics/PolyNullInferenceTests.java @@ -14,8 +14,10 @@ import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MethodTree; import com.sun.tools.javac.code.Type; +import com.uber.nullaway.DummyOptionsConfig; import com.uber.nullaway.LibraryModels.PolyNullLocation; import com.uber.nullaway.LibraryModels.PolyNullLocation.Return; +import com.uber.nullaway.handlers.Handlers; import com.uber.nullaway.libmodel.NestedAnnotationInfo.TypePathEntry; import com.uber.nullaway.libmodel.NestedAnnotationInfo.TypePathEntry.Kind; import org.junit.Test; @@ -62,7 +64,10 @@ public Description matchMethod(MethodTree tree, VisitorState state) { ImmutableSet.of( new PolyNullLocation( new Return(), ImmutableList.of(new TypePathEntry(Kind.TYPE_ARGUMENT, 0)))), - annotation); + ConstraintSolver.InferredNullability.NONNULL, + state, + new DummyOptionsConfig(), + Handlers.buildEmpty()); assertThat(updated.getReturnType().getTypeArguments().head.getAnnotationMirrors().head.type) .isSameInstanceAs(annotation); assertThat(updated.getParameterTypes().head) diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java index fd25a676ba..8e5a933855 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/BytecodeGenericsTests.java @@ -267,7 +267,7 @@ public void genericsChecksForAssignments() { import com.uber.lib.generics.NullableTypeParam; class Test { static void testPositive(NullableTypeParam<@Nullable String> t1) { - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableTypeParam t2 = t1; } static void testNegative(NullableTypeParam<@Nullable String> t1) { @@ -289,9 +289,9 @@ public void genericsChecksForFieldAssignments() { import com.uber.lib.generics.NullableTypeParam; class Test { static void testPositive(NullableTypeParam t1) { - // BUG: Diagnostic contains: incompatible types: NullableTypeParam + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String NullableTypeParam.staticField = t1; - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableTypeParam t2 = NullableTypeParam.staticField; } static void testNegative(NullableTypeParam<@Nullable String> t1) { @@ -315,9 +315,9 @@ public void genericsChecksForParamPassingAndReturns() { import com.uber.lib.generics.GenericTypeArgMethods; class Test { static void testPositive(NullableTypeParam t1) { - // BUG: Diagnostic contains: incompatible types: NullableTypeParam + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableTypeParam t2 = GenericTypeArgMethods.nullableTypeParamReturn(); } static void testNegative(NullableTypeParam<@Nullable String> t1) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java index 0e2bbda553..9546db5b86 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericDiamondTests.java @@ -34,9 +34,9 @@ void testNegative() { Bar<@Nullable Void> b = new Bar<>(Foo.make()); } void testPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Bar b = new Bar<>(Foo.makeNullableStr()); - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable Void> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void Bar b2 = new Bar<>(Foo.make()); } } @@ -103,7 +103,7 @@ static class Bar { return new Bar<>(Foo.make()); } Bar testPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return new Bar<>(Foo.makeNullableStr()); } } @@ -139,7 +139,7 @@ void testNegative() { takeNullableVoid(new Bar<>(Foo.make())); } void testPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String takeStr(new Bar<>(Foo.makeNullableStr())); } } @@ -172,7 +172,7 @@ static class Bar { return (new Bar<>(Foo.make())); } Bar testPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return (new Bar<>(Foo.makeNullableStr())); } } @@ -209,7 +209,7 @@ static class Baz { return new Baz<>(new Bar<>(Foo.make())); } Baz testPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return new Baz<>(new Bar<>(Foo.makeNullableStr())); } } @@ -342,14 +342,14 @@ static void takeStr(Bar b) {} return new Bar<>(Foo.make()) {}; } Bar returnPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return new Bar<>(Foo.makeNullableStr()) {}; } void paramNegative() { takeNullableVoid(new Bar<>(Foo.make()) {}); } void paramPositive() { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String takeStr(new Bar<>(Foo.makeNullableStr()) {}); } } @@ -438,7 +438,7 @@ static void testNegative2(Foo<@Nullable String> f1, Foo<@Nullable String> f2) { new Bar<>(f1, f2); } static void testPositive(Foo f1, Foo<@Nullable String> f2) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String new Bar<>(f1, f2); } } @@ -471,7 +471,7 @@ static void testNegative() { takeFooNullableString(id(new FooImpl<>(makeNullableFoo()))); } static void testPositive() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String takeFooString(id(new FooImpl<>(makeNullableFoo()))); } } @@ -502,7 +502,7 @@ static class Box { return new Box<>(id(makeNullableFoo())); } static Box testPositive() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return new Box<>(id(makeNullableFoo())); } } 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..269d22820d 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInferenceErrorReportingTests.java @@ -234,7 +234,7 @@ class Test { // since it will pad the array with `null` whenever the passed new length is greater // than original.length (the example below is safe, but NullAway / JSpecify do not reason // about integer constraints) - // BUG: Diagnostic contains: incompatible types: @Nullable E [] cannot be converted to E @Nullable [] + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found @Nullable E [], required E @Nullable [] return Arrays.copyOf(original, original.length); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java index 576610876b..93ff41d452 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -361,7 +361,7 @@ static class ListFuture } static MyFuture> invalid() { - // BUG: Diagnostic contains: incompatible types: ListFuture cannot be converted to MyFuture> (ListFuture is a subtype of MyFuture>) + // BUG: Diagnostic contains: incompatible nullability: found @Nullable V, required V return new ListFuture(); } } @@ -393,10 +393,10 @@ static void test( List<@Nullable String> nullableList, List nonNullList) { List<@Nullable String> valid = box.get(); - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String List invalid = box.get(); box.set(nullableList); - // BUG: Diagnostic contains: incompatible types: List cannot be converted to List<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String box.set(nonNullList); } } @@ -423,7 +423,7 @@ abstract class Child void test(Child child) { List<@Nullable O> valid = child.get(); - // BUG: Diagnostic contains: incompatible types: List<@Nullable O> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable O, required O List invalid = child.get(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java index cb163f3b77..d660011b67 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericLambdaTests.java @@ -727,11 +727,11 @@ void blockBodyToUnmarkedInterface(List<@Nullable String> l) { UnmarkedListSupplier s = () -> { return l; }; } void expressionBodyToMarkedInterface(List<@Nullable String> l) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String MarkedListSupplier s = () -> l; } void blockBodyToMarkedInterface(List<@Nullable String> l) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String MarkedListSupplier s = () -> { return l; }; } void matchingTypeArgumentsToMarkedInterface(List l) { 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..42718e3763 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodLambdaOrMethodRefArgTests.java @@ -231,7 +231,7 @@ static void implicitParameter(Box> nested) { static void implicitParameterNonNull(Box> nested) { var flat = nested.flatMap(box -> box); - // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String acceptsNullable(flat); } @@ -1337,7 +1337,7 @@ void testNegative() { receiver(makeCancelable(this::target)); } void testPositive() { - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Object> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object receiver(makeCancelable(this::targetNonNullParam)); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java index 3ef81452f2..e4a97dbabf 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -958,7 +958,7 @@ static void testLocalAssign() { Foo<@Nullable Object> f5 = Foo.makeNonNull(null); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required Foo f6 = Foo.makeNonNull(null); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo<@Nullable Object> f7 = Foo.makeNonNull(new Object()); Foo f8 = Foo.makeNonNull(new Object()); } @@ -1013,7 +1013,7 @@ static class Foo { static void test(Foo<@Nullable Object> f1, Foo f2) { // no error expected Foo<@Nullable Object> result = Foo.create(null, f1); - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo<@Nullable Object> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo<@Nullable Object> result2 = Foo.create(null, f2); } } @@ -1100,9 +1100,9 @@ abstract class Foo { } static void test(Foo f) { Foo> fooNonNull_1 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer Foo<@Nullable Integer, ArrayList> fooNonNull_3 = f.nonNullTest(); Foo> fooNull_1 = f.nullTest(); Foo> fooNull_2 = f.nullTest(); @@ -1144,7 +1144,7 @@ static void testLocalAssign() { Foo[]> f3 = Foo.test1Null(null); Foo[]> f4 = Foo.test1Null(null); Foo[]> f5 = Foo.test1Nonnull(new Object()); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo[]> f6 = Foo.test1Nonnull(new Object()); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required Foo[]> f7 = Foo.test1Nonnull(null); @@ -1156,7 +1156,7 @@ static void testLocalAssign() { Foo[] f11 = Foo.test2Null(null); Foo<@Nullable Object>[] f12 = Foo.test2Null(null); Foo[] f13 = Foo.test2Nonnull(new Object()); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object Foo<@Nullable Object>[] f14 = Foo.test2Nonnull(new Object()); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required Foo[] f15 = Foo.test2Nonnull(null); @@ -1180,7 +1180,7 @@ abstract class TestCase { static class Bar {} abstract Bar make(Bar other); void test(Bar> other) { - // BUG: Diagnostic contains: incompatible types: Bar> cannot be converted to Bar> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Bar> unused = make(other); } } @@ -1293,7 +1293,7 @@ void testNegative(Function<@Nullable String, @Nullable String> f) { this.foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types this.foo(f); } void testPositive2(Function<@Nullable String, @Nullable String> f) { @@ -1456,7 +1456,7 @@ static Foo makeNullInvalid() { return Foo.makeNonNull(null); } static Foo<@Nullable Object> makeNonNullInvalid2() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object return Foo.makeNonNull(new Object()); } static Foo makeNonNullValid() { @@ -1498,7 +1498,7 @@ static void testCalls() { handleFooNullable(Foo.makeNonNull(null)); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required handleFooNonNull(Foo.makeNonNull(null)); - // BUG: Diagnostic contains: incompatible types: Foo + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object handleFooNullable(Foo.makeNonNull(new Object())); handleFooNonNull(Foo.makeNonNull(new Object())); } @@ -1515,7 +1515,7 @@ static void testVarargsCalls() { handleFooNullableVarargs(Foo.makeNonNull(null)); // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required handleFooNonNullVarargs(Foo.makeNonNull(null)); - // BUG: Diagnostic contains: incompatible types: Foo + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object handleFooNullableVarargs(Foo.makeNonNull(new Object())); handleFooNonNullVarargs(Foo.makeNonNull(new Object())); } @@ -1928,7 +1928,7 @@ static class Foo {} } Foo foo1 = make(new String[] { "hello", "world" }); Foo<@Nullable String> foo2 = make(new @Nullable String[] { "hello", null, "world" }); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo foo3 = make(new @Nullable String[] { "hello", null, "world" }); Foo<@Nullable String> foo4 = make(new String[] { "hello", "world" }); } @@ -2030,7 +2030,7 @@ void test(String[] arr, @Nullable String[] arr2) { String s2 = f(arr, "hi"); // legal s2.hashCode(); - // BUG: Diagnostic contains: incompatible types: @Nullable String [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String stringField = f(arr2, "hi"); } } @@ -2237,6 +2237,19 @@ static void testParam() { @Test public void capturedTypeAtNullUnmarkedBoundary() { makeHelper() + .expectErrorMessage( + "CAPTURE_FROM_UNMARKED", + message -> + message.contains( + """ + incompatible nullability: found @Nullable Object, required Object + found: Foo + ^^^^^^^^^^^^ + required: Foo + ^ + path: Foo type argument T -> wildcard upper bound + note: the source wildcard is the type argument for type parameter T of Box, and Box is unannotated + """)) .addSourceLines( "Test.java", """ @@ -2262,7 +2275,7 @@ static Foo convert(Box box) { static Foo getReturnType() { var returnType = Api.convert(Api.wildcard()); - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object; source wildcard is the type argument for type variable T of Box) + // BUG: Diagnostic matches: CAPTURE_FROM_UNMARKED return returnType; } } @@ -2273,6 +2286,19 @@ static Foo getReturnType() { @Test public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { makeHelper() + .expectErrorMessage( + "CAPTURE_FROM_MARKED", + message -> + message.contains( + """ + incompatible nullability: found @Nullable Object, required Object + found: Foo<@Nullable capture of ?> + ^^^^^^^^^^^^^^^^^^^^^^ + required: Foo + ^^^^^^ + path: Foo type argument T -> wildcard upper bound + note: the source wildcard is the type argument for type parameter T of Holder + """)) .addSourceLines( "Test.java", """ @@ -2290,7 +2316,7 @@ static class Holder { } static Foo test(Holder holder) { - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable capture of ?> cannot be converted to Foo (target wildcard upper bound is Object; source wildcard upper bound is @Nullable Object; source wildcard is the type argument for type variable T of Holder) + // BUG: Diagnostic matches: CAPTURE_FROM_MARKED return holder.value; } } @@ -2426,7 +2452,7 @@ class Test { class Box {} void swapBoxes(Box box1, Box box2) {} void testPositive(Box box1, Box<@Nullable String> box2) { - // BUG: Diagnostic contains: incompatible types: Test.Box<@Nullable String> cannot be converted to Test.Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String swapBoxes(box1, box2); } void TestNegative(Box<@Nullable String> box1, Box<@Nullable String> box2) { @@ -2521,7 +2547,7 @@ Supplier make2() { } // tests that our repair computes a consistent substitution for the type variables void test2() { - // BUG: Diagnostic contains: incompatible types: Supplier cannot be converted to Supplier<@Nullable OuterT> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found OuterT, required @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2653,7 +2679,7 @@ static class Foo { .or(new Foo<@Nullable String>()); // a true positive case - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String static Foo WRONG = Foo.of(new Foo<@Nullable String>()).or(new Foo<@Nullable String>()); } @@ -2709,7 +2735,7 @@ class Test { static class Box {} static void accept(Box<@Nullable T> box) {} void test(Box> box) { - // BUG: Diagnostic contains: incompatible types: Box> cannot be converted to Box<@Nullable CompletableFuture> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found CompletableFuture, required @Nullable CompletableFuture accept(box); } } @@ -3322,9 +3348,9 @@ class GInner { return x; } void nullableQualifier(Outer<@Nullable String> o) { - // BUG: Diagnostic contains: incompatible types: Outer<@Nullable String>.Inner cannot be converted to Outer.Inner + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String id(o.new Inner("")); - // BUG: Diagnostic contains: incompatible types: Outer<@Nullable String>.GInner cannot be converted to Outer.GInner + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String id(o.new GInner("")); } void nonNullQualifier(Outer o) { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java index 77026ab230..77896df833 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericVoidReturnTests.java @@ -93,7 +93,7 @@ void invalidLambdaArgument(@Nullable String value) { exec(() -> requiresNonNull(value), "x"); } void incompatibleLambdaTypeArguments(List<@Nullable Void> values) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void execList(() -> values, "x"); } void substitutedVoidLambdaReturn(@Nullable Void value) { @@ -119,7 +119,7 @@ Void invalidArgument(@Nullable String value) { return requiresNonNull(value); } List incompatibleTypeArguments(List<@Nullable Void> values) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Void, required Void return values; } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java index b8f9a0b6fb..683e715402 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericsTests.java @@ -52,7 +52,7 @@ static void testBadNonNull(NonNullTypeParam t) { // BUG: Diagnostic contains: Generic type parameter testBadNonNull(new NonNullTypeParam<@Nullable String>()); testBadNonNull( - // BUG: Diagnostic contains: incompatible types: NonNullTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String new NonNullTypeParam< // BUG: Diagnostic contains: Generic type parameter @Nullable String>()); @@ -229,7 +229,7 @@ class Test { static class Holder {} static void typeArguments() { Holder other = new Holder<@Other String>(); - // BUG: Diagnostic contains: incompatible types: Holder<@Nullable String> cannot be + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Holder otherThenNullable = new Holder<@Other @Nullable String>(); } } @@ -288,17 +288,17 @@ abstract class Fn { static void param(Wrapper.@Nullable Fn p) {} static void positiveParam() { Wrapper<@Nullable String>.Fn x = null; - // BUG: Diagnostic contains: incompatible types: Test.Wrapper<@Nullable String>.Fn + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Test.Wrapper<@Nullable String>.Fn, required Test.Wrapper.@Nullable Fn param(x); } static void positiveAssign() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible types: Test.Wrapper<@Nullable String>.Fn cannot be converted to Test.Wrapper.Fn + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Wrapper.Fn p2 = p1; } static Wrapper.@Nullable Fn positiveReturn() { Wrapper<@Nullable String>.Fn p1 = null; - // BUG: Diagnostic contains: incompatible types: Test.Wrapper<@Nullable String>.Fn + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Test.Wrapper<@Nullable String>.Fn, required Test.Wrapper.@Nullable Fn return p1; } static void negativeParam() { @@ -349,13 +349,13 @@ void callOnResult() { } public void testPositive() { addCallback( - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer new Callback() { @Override public void onResult(Integer value) { - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer Callback<@Nullable Integer> self = this; } void callOnResult() { @@ -457,7 +457,7 @@ public void genericsChecksForAssignments() { class Test { static class NullableTypeParam {} static void testPositive(NullableTypeParam<@Nullable String> t1) { - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableTypeParam t2 = t1; } static void testNegative(NullableTypeParam<@Nullable String> t1) { @@ -480,7 +480,7 @@ class Test { static class NullableTypeParam {} static void testNoWarningForMismatch(NullableTypeParam<@Nullable String> t1) { // we still get an error here as we are not forcing use of JSpecify's @Nullable - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableTypeParam t2 = t1; } static void testNegative(NullableTypeParam<@Nullable String> t1) { @@ -503,7 +503,7 @@ class Test { static class SampleClass {} static class SampleClassMultipleArguments {} static void testPositive() { - // BUG: Diagnostic contains: incompatible types: SampleClassMultipleArguments> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String SampleClassMultipleArguments>, String> t1 = new SampleClassMultipleArguments>, String>(); } @@ -528,7 +528,7 @@ class Test { interface Fn

{} class FnImpl implements Fn<@Nullable String, @Nullable String> {} void testPositive() { - // BUG: Diagnostic contains: incompatible types: Test.FnImpl + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Fn<@Nullable String, String> f = new FnImpl(); } void testNegative() { @@ -552,7 +552,7 @@ interface Fn1 {} interface Fn2

{} class FnImpl implements Fn1<@Nullable String, @Nullable String>, Fn2 {} void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Fn2<@Nullable String> f = new FnImpl(); } void testNegative() { @@ -579,7 +579,7 @@ class FnImpl1 extends SubClassA {} class FnImpl2 extends SubClassA<@Nullable String> {} void testPositive() { SuperClassC<@Nullable String> f; - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String f = new FnImpl1(); } void testNegative() { @@ -604,9 +604,9 @@ class Test { class D

{} class B

extends D

{} void testPositive(B<@Nullable String> b) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String D f1 = new B<@Nullable String>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String D f2 = b; } void testNegative(B b) { @@ -634,7 +634,7 @@ void testNegative() { Super<@Nullable String, String> s = new Sub(); } void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types Super<@Nullable String, String> s2 = new Sub<@Nullable String, String>(); } } @@ -656,11 +656,11 @@ class B

extends D

{} class C

{} class A, P extends @Nullable Object> {} void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String D> f1 = new B>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A, String> f2 = new A, @Nullable String>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found Test.@Nullable C, required Test.C D> f3 = new B<@Nullable C>(); } void testNegative() { @@ -1008,7 +1008,7 @@ public String function(T1 o) { } } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: B cannot be converted to A<@Nullable Object> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object A<@Nullable Object> p = new B<>(); } static void testNegative() { @@ -1030,11 +1030,11 @@ public void genericFunctionReturnTypeNewClassTree() { class Test { static class A { } static A testPositive1() { - // BUG: Diagnostic contains: incompatible types: A<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String return new A(); } static A<@Nullable String> testNegative() { @@ -1056,7 +1056,7 @@ public void genericFunctionReturnTypeNormalTree() { class Test { static class A { } static A testPositive(A<@Nullable String> a) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return a; } static A<@Nullable String> testNegative(A<@Nullable String> a) { @@ -1079,7 +1079,7 @@ class Test { static class A { } static A testPositive(A<@Nullable String> a, int num) { if (num % 2 == 0) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return a; } else { return new A(); @@ -1225,15 +1225,15 @@ static A sampleMethod2(A> a1, A a2) { static void sampleMethod3(A<@Nullable String> a1) { } static void testPositive1(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: A> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String sampleMethod3(a1); } static void testNegative(A> a1, A a2) { @@ -1258,7 +1258,7 @@ void foo(A a) {} void bar(A a) { foo(a); this.foo(a); } } static void test(A<@Nullable String> p, A q) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String p.foo(q); // this one is fine p.foo(p); @@ -1282,9 +1282,9 @@ static class A { } return new A<@Nullable String>(); } static void testPositive(A<@Nullable String> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A<@Nullable String> b = sampleMethodWithVarArgs(a1); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A<@Nullable String> b2 = sampleMethodWithVarArgs(a2, a1); } static void testNegative(A a1, A a2) { @@ -1310,7 +1310,7 @@ static class A { } return new A<@Nullable String>(); } static void testPositive(A<@Nullable String>[] arr) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A<@Nullable String> b = sampleMethodWithVarArgs(arr); } static void testNegative(A[] arr) { @@ -1391,9 +1391,9 @@ public void nestedGenericTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String A[]> var1 = new A[]>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A[]> var2 = new A[]>(); } static void testNegative() { @@ -1416,7 +1416,7 @@ public void nestedGenericTypeAssignment2() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A[]> var2 = new A[]>(); } } @@ -1435,7 +1435,7 @@ public void genericPrimitiveArrayTypeAssignment() { class Test { static class A { } static void testPositive() { - // BUG: Diagnostic contains: incompatible types: A + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found int [], required int @Nullable [] A x = new A(); } static void testNegative() { @@ -1793,7 +1793,7 @@ class D extends A.B {} void test() { C<@Nullable String> c1 = new C<>(); A<@Nullable String>.B<@Nullable String> ok1 = c1.new D<@Nullable String>(); - // BUG: Diagnostic contains: incompatible types: Test.C<@Nullable String>.D<@Nullable String> cannot be converted to Test.A.B<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String A.B<@Nullable String> bad = c1.new D<@Nullable String>(); C c2 = new C<>(); A.B<@Nullable String> ok2 = c2.new D<@Nullable String>(); @@ -2057,28 +2057,28 @@ void staticSubclassWithNullableOuterMatches(NullableInner input) { Outer<@Nullable String>.Inner result = input; } void staticSubclassWithNullableOuterMismatches(NullableInner input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Outer.Inner result = input; } void staticSubclassWithNonNullOuterMatches(NonNullInner input) { Outer.Inner result = input; } void staticSubclassWithNonNullOuterMismatches(NonNullInner input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Outer<@Nullable String>.Inner result = input; } void unrelatedEnclosingTypeMatches(Unrelated.Derived input) { Outer<@Nullable String>.Inner result = input; } void unrelatedEnclosingTypeMismatches(Unrelated.Derived input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Outer.Inner result = input; } void lexicalOuterMismatchDoesNotRejectMatchingSupertype(Cross.Derived input) { Outer<@Nullable String>.Inner result = input; } void lexicalOuterMatchDoesNotAcceptMismatchingSupertype(Cross.Derived input) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Outer.Inner result = input; } } @@ -3138,7 +3138,7 @@ void testNegative(Function<@Nullable V, @Nullable V> f) { foo(f); } void testPositive(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types foo(f); } abstract void takesArray(Function<@Nullable V, @Nullable V>[] f); @@ -3146,7 +3146,7 @@ void testNegativeArray(Function<@Nullable V, @Nullable V>[] f) { takesArray(f); } void testPositiveArray(Function[] f) { - // BUG: Diagnostic contains: incompatible types: Function [] cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types takesArray(f); } } @@ -3168,11 +3168,11 @@ public abstract class Generics { abstract void foo( Function<@NonNull V, @NonNull V> f); void testPositive(Function<@Nullable String, @Nullable String> f) { - // BUG: Diagnostic contains: incompatible types: Function<@Nullable String, @Nullable String> cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types this.foo(f); } } @@ -3196,15 +3196,15 @@ void testNegative(Function f) { foo(f); } void testPositive1(Function<@Nullable V, V> f) { - // BUG: Diagnostic contains: incompatible types: Function<@Nullable V, V> + // BUG: Diagnostic contains: incompatible nullability: 2 mismatches between source and target types foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found V, required @Nullable V foo(f); } void testPositive3(Function<@Nullable V, @Nullable V> f) { - // BUG: Diagnostic contains: incompatible types: Function<@Nullable V, @Nullable V> cannot be converted to + // BUG: Diagnostic contains: incompatible nullability: found @Nullable V, required V foo(f); } } @@ -3286,7 +3286,7 @@ static class Inner { void bar(Function f) { // no error since foo is in @NullUnmarked code foo = f; - // BUG: Diagnostic contains: incompatible types: Function + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Function, required @Nullable Function<@Nullable String, @Nullable String> bar = f; } } @@ -3371,7 +3371,7 @@ private static class Inner { Inner identity() { return this; } } Inner<@Nullable Object> mThing = new Inner<@Nullable Object>().identity(); - // BUG: Diagnostic contains: incompatible types: Inner<@Nullable Object> cannot be converted to Inner + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Inner mNonNullThing = new Inner<@Nullable Object>().identity(); } """) @@ -3440,7 +3440,7 @@ private static class A { } private static class B extends A<@Nullable Object> { B(List l) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object super(l); } } @@ -3678,9 +3678,9 @@ class A {} class B extends A<@Nullable T> {} class C extends A<@NonNull T> {} void test() { - // BUG: Diagnostic contains: incompatible types: Test.B cannot be converted to Test.A (Test.B is a subtype of Test.A<@Nullable Object>) + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object A a = new B(); - // BUG: Diagnostic contains: incompatible types: Test.C<@Nullable Object> cannot be converted to Test.A<@Nullable Object> (Test.C<@Nullable Object> is a subtype of Test.A) + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Object, required @Nullable Object A<@Nullable Object> a2 = new C<@Nullable Object>(); } } @@ -3711,10 +3711,10 @@ interface MaybeNull { static void accept(MaybeNull nonNullThing) {} static void test(MaybeNull<@Nullable String> nullable, MaybeNull nonNull) { accept(nullable.asNonNull()); - // BUG: Diagnostic contains: incompatible types: MaybeNull<@Nullable String> cannot be converted to MaybeNull + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String accept(nonNull.asNullable()); MaybeNull<@Nullable String> m1 = nonNull.asNullable(); - // BUG: Diagnostic contains: incompatible types: MaybeNull<@Nullable String> cannot be converted to MaybeNull + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String MaybeNull m2 = nonNull.asNullable(); } } @@ -3737,11 +3737,11 @@ static class Foo { Foo<@NonNull T> nonNullField = new Foo<>(); Foo<@Nullable T> nullableField = new Foo<>(); static void test(Foo<@Nullable String> nullableFoo, Foo<@NonNull String> nonnullFoo) { - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found String, required @Nullable String Foo<@Nullable String> f1 = nullableFoo.nonNullField; Foo f2 = nullableFoo.nonNullField; Foo<@Nullable String> f3 = nonnullFoo.nullableField; - // BUG: Diagnostic contains: incompatible types: Foo<@Nullable String> cannot be converted to Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo f4 = nonnullFoo.nullableField; } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java index 814b2a7b26..53361729f0 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionBoundNarrowingTests.java @@ -54,12 +54,12 @@ Result acceptsExplicitNonNullLastComponent(LastNonNull source) { } Result rejectsAllNullableFirstComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable A & @Nullable B, required A return source.result(); } Result rejectsAllNullableLastComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable A & @Nullable B, required B return source.result(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java index ba2cc617b8..7fc6cb6e78 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/JSpecifyArrayTests.java @@ -454,7 +454,7 @@ static void passNonNullElements(Test[] array) { takesParameterized(array); } static void passNullableElements(@Nullable Test[] array) { - // BUG: Diagnostic contains: incompatible types: @Nullable Test [] cannot be converted to Test [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Test, required Test takesParameterized(array); } static Test[] returnNonNullElements(Test[] array) { @@ -462,7 +462,7 @@ static Test[] returnNonNullElements(Test[] array) { return array; } static Test[] returnNullableElements(@Nullable Test[] array) { - // BUG: Diagnostic contains: incompatible types: @Nullable Test [] cannot be converted to Test [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Test, required Test return array; } static void assignNonNullElements(Test[] array) { @@ -470,7 +470,7 @@ static void assignNonNullElements(Test[] array) { Test[] assigned = array; } static void assignNullableElements(@Nullable Test[] array) { - // BUG: Diagnostic contains: incompatible types: @Nullable Test [] cannot be converted to Test [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Test, required Test Test[] assigned = array; } static void passNonNullElementsThroughTernary(boolean b, Test[] array) { @@ -558,7 +558,7 @@ static void test(@Nullable Integer[] nullableIntArr, Integer[] nonnullIntArr) { @Nullable Integer[] x2 = nullableIntArr; // legal (covariant array subtypes) x2 = nonnullIntArr; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] cannot be converted to Integer [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer x1 = nullableIntArr; } } @@ -582,7 +582,7 @@ static void test() { @Nullable Integer[] x2 = new Integer[0]; // legal x2 = new @Nullable Integer[0]; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] cannot be converted to Integer [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer x1 = new @Nullable Integer[0]; } } @@ -604,12 +604,12 @@ static void test() { // dimension of the creation expression @Nullable Integer[][] x1 = new @Nullable Integer[3][4]; @Nullable Integer[][][] x2 = new @Nullable Integer[1][2][3]; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[][] x3 = new @Nullable Integer[3][4]; // an array creation with an initializer has no explicit dimension expressions, but // still creates a single-dimension array @Nullable Integer[] x4 = new @Nullable Integer[]{null}; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] cannot be converted to Integer [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[] x5 = new @Nullable Integer[]{null}; // the reverse direction is legal by covariant array subtyping @Nullable Integer[] y1 = new Integer[3]; @@ -647,13 +647,13 @@ static void test( // the declared type and the type computed for the creation expression made // CheckIdenticalNullabilityVisitor#visitArrayType bail out, so the innermost // element types were never compared - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] cannot be converted to Integer @Nullable [] [] + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found @Nullable Integer [], required Integer @Nullable [] Integer[] @Nullable [] y4 = new @Nullable Integer[3][4]; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[][] y1 = nullableElems2D; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] [] cannot be converted to Integer [] [] [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Integer, required Integer Integer[][][] y2 = nullableElems3D; - // BUG: Diagnostic contains: incompatible types: Integer @Nullable [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability: found Integer @Nullable [], required Integer [] Integer[][] y3 = nullableInner; } } @@ -673,7 +673,7 @@ public void arraysAndGenerics() { class Test { void foo(List<@Nullable Integer[]> l) {} void testPositive(List p) { - // BUG: Diagnostic contains: incompatible types: List + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Integer, required @Nullable Integer foo(p); } void testNegative(List<@Nullable Integer[]> p) { @@ -697,7 +697,7 @@ static class Foo {} static class Bar { Foo[] getFoosPositive() { @Nullable Foo[] result = new Foo[0]; - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo return result; } Foo[] getFoosNegative() { @@ -706,7 +706,7 @@ Foo[] getFoosNegative() { } void takeFoos(Foo[] foos) {} void callTakeFoosPositive(@Nullable Foo[] p) { - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo takeFoos(p); } void callTakeFoosNegative(Foo[] p) { @@ -716,9 +716,9 @@ void takeFoosVarargs(Foo[]... foos) {} void callTakeFoosVarargsPositive(@Nullable Foo[] p, Foo[] p2) { // Under the hood, a @Nullable Foo[][] is passed, which is not a subtype // of the formal parameter type Foo[][] - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo takeFoosVarargs(p); - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Foo, required Foo takeFoosVarargs(p2, p); } void callTakeFoosVarargsNegative(Foo[] p) { @@ -1390,7 +1390,7 @@ static void nullableExplicitArrayStore() { static void nullableTypeArgumentRejectedFromNonNullBoundedWildcardArray( CompletableFuture[] futures, CompletableFuture<@Nullable String> value) { - // BUG: Diagnostic contains: incompatible types: CompletableFuture<@Nullable String> cannot be converted to CompletableFuture + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String futures[0] = value; } } @@ -1772,7 +1772,7 @@ void writeNullIntoNonNullElementOfVarLoopVariableOverNestedLocalArray() { } void assignNullableTypeArgumentElementOfLocalArray() { List<@Nullable String>[] local = new List[1]; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String List l = local[0]; } void assignMatchingTypeArgumentElementOfLocalArray() { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java index 696efa68e6..b6d8ffdf20 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/NullnessOperatorTests.java @@ -11,13 +11,15 @@ * Fails when NullAway changes how it treats a value whose type is a type variable, or a wildcard * captured against one. * - *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. Wherever the same type - * variable {@code T}, or a capture of {@code ? super T}, is expected, it is accepted: as an - * argument, a return, a field or array store, and a field initializer. An argument is not accepted - * where a library model requires a non-null one. A type variable that the value's type reaches only - * through a {@code @Nullable} bound does not accept it. It stays unsafe to dereference while that - * type variable has a nullable upper bound. An explicit {@code @Nullable}, declared on the member - * or supplied by a library model, overrides that and is reported at every sink. + *

Such a value carries the JSpecify {@code NO_CHANGE} nullness operator. It is accepted where + * the expected type is the value's own type (for example the capture of {@code ? extends T}), a + * type variable that the value's type reaches through non-nullable bounds (for example {@code T}), + * or a capture of {@code ? super} either of those types: as an argument, a return, a field or array + * store, and a field initializer. An argument is not accepted where a library model requires a + * non-null one. A type variable that the value's type reaches only through a {@code @Nullable} + * bound does not accept it. It stays unsafe to dereference while that type variable has a nullable + * upper bound. An explicit {@code @Nullable}, declared on the member or supplied by a library + * model, overrides that and is reported at every sink. * *

The tests that expect a diagnostic pin where the value stays nullable: a dereference, * unboxing, a target of a concrete type such as {@code Object}, a {@code @NonNull T} target or @@ -1161,6 +1163,25 @@ interface Box { // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' f.apply(box.get()); } + static void nonNullChain( + Box box, Function f) { + f.apply(box.get()); + } + static void superOfAChainVariable( + Box box, Function f) { + f.apply(box.get()); + } + static void nullableChain( + Box box, Function f) { + // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' + f.apply(box.get()); + } + static + void nullableChainTwoBoundsDeep( + Box box, Function f) { + // BUG: Diagnostic contains: passing @Nullable parameter 'box.get()' + f.apply(box.get()); + } } """) .doTest(); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java index 6b613bce45..8c9f6a04bd 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/PolyNullLibraryModelsTests.java @@ -103,7 +103,7 @@ void test(List nonNull, List<@Nullable Object> nullable) { PolyNullMethods.first(nonNull, nonNull).hashCode(); // Without PolyNull, both parameters retain their declared List types. - // BUG: Diagnostic contains: incompatible types: List<@Nullable Object> cannot be converted to List + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object PolyNullMethods.first(nullable, nullable); } } @@ -1438,6 +1438,101 @@ Object test(Object value) { .doTest(); } + @Test + public void anArgumentWhoseTypeVariableHasANullableBoundMakesThePolyNullLocationsNullable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import com.uber.lib.unannotated.PolyNullMethods; + import java.util.Map; + import java.util.Optional; + import java.util.function.Function; + import java.util.function.Supplier; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + + @NullMarked + class Test { + void lambdaArgument(T t) { + // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.genericObject(t, () -> "x")' is @Nullable + PolyNullMethods.genericObject(t, () -> "x").toString(); + T first = PolyNullMethods.genericFirst(t, () -> "x"); + } + static void accept(X x) {} + void typeVariableResultPassedToAGenericMethod(T t) { + accept(PolyNullMethods.genericFirst(t, () -> "x")); + } + void lambdaParameter(T t) { + // BUG: Diagnostic contains: dereferenced expression 'value' is @Nullable + PolyNullMethods.withMapper(t, value -> value.toString()); + } + void supplierOfTheTypeVariable(Optional optional, Supplier supplier) { + // BUG: Diagnostic contains: dereferenced expression 'optional.orElseGet(supplier)' is @Nullable + optional.orElseGet(supplier).hashCode(); + } + void functionReturningTheTypeVariable(Map map, Function f) { + // BUG: Diagnostic contains: dereferenced expression 'map.computeIfAbsent("key", f)' is @Nullable + map.computeIfAbsent("key", f).hashCode(); + } + void nonNullSupplier(Optional optional, Supplier supplier) { + optional.orElseGet(supplier).hashCode(); + } + void typeVariableWhoseBoundExcludesNull( + Optional optional, S fallback) { + // BUG: Diagnostic contains: dereferenced expression 'optional.orElseGet(() -> fallback)' is @Nullable + optional.orElseGet(() -> fallback).hashCode(); + } + void explicitlyNullableTypeArgumentForAnExplicitlyNullableBound(T t) { + // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.<@Nullable T, String>genericFirst(t, () -> "x")' is @Nullable + PolyNullMethods.<@Nullable T, String>genericFirst(t, () -> "x").hashCode(); + } + @NullUnmarked + static class Unmarked { + @NullMarked + void explicitlyNullableTypeArgument(X x) { + if (x != null) { + PolyNullMethods.<@Nullable X, String>genericFirst(x, () -> "x").hashCode(); + } + } + } + } + """) + .doTest(); + } + + @Test + public void aCaptureWhoseBoundAdmitsNullKeepsItsTypeAtAPolyNullLocation() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import com.uber.lib.unannotated.PolyNullMethods; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static U first(List list) { + return list.get(0); + } + T typeVariableResult(List list) { + return PolyNullMethods.genericFirst(first(list), () -> "x"); + } + static void accept(X x) {} + void typeVariableResultPassedToAGenericMethod(List list) { + accept(PolyNullMethods.genericFirst(first(list), () -> "x")); + } + void classTypeResult(List list) { + // BUG: Diagnostic contains: dereferenced expression 'PolyNullMethods.genericObject(first(list), () -> "x")' is @Nullable + PolyNullMethods.genericObject(first(list), () -> "x").hashCode(); + } + } + """) + .doTest(); + } + private CompilationTestHelper makeHelper() { return makeTestHelperWithArgs( JSpecifyJavacConfig.withJSpecifyModeArgs(List.of("-XepOpt:NullAway:OnlyNullMarked=true"))); diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java index b307333e28..8bc51c1f1a 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/SharedIntersectionTimeoutTests.java @@ -152,7 +152,7 @@ void argumentWithNonObjectBound() { return comparableSibling(); } void siblingWithNullableBoundAndMismatch() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String NullableSibling x = nullableSibling(); } void siblingWithNullableNonObjectBound() { diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java index 4cc4e960d2..5b47f86248 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/StreamNullabilityPropagatorTests.java @@ -281,7 +281,7 @@ public void unrelatedFilterDoesNotRefineStreamElementType() { @NullMarked class Test { static List filterDoesNotProveNonNull(List<@Nullable String> values) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return values.stream().filter(value -> true).toList(); } @@ -302,7 +302,7 @@ static List mapAfterNullRejectingFilterCanStillReturnNullable( return values.stream() .filter(Objects::nonNull) .map(Test::maybeNull) - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String .toList(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java index e3ea7319dd..1cc46f8fc1 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/VarDeclaredLocalTests.java @@ -247,7 +247,7 @@ void rejectsIncompatibleTypeArgument( boolean b, String s, Box nonNull, Box<@Nullable String> nullable) { s.length(); var x = b ? nonNull : nonNull; - // BUG: Diagnostic contains: incompatible types: Box<@Nullable String> cannot be converted to Box + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String x = id(nullable); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java index 743a79a682..7f28b82277 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -5,6 +5,7 @@ import com.uber.nullaway.generics.JSpecifyJavacConfig; import java.util.Arrays; import java.util.List; +import org.junit.Assume; import org.junit.Test; public class WildcardTests extends NullAwayTestsBase { @@ -319,7 +320,7 @@ void testNegative(Foo<@Nullable String> f, Foo f2) { } void testPositive(Foo<@Nullable String> f, Foo f2) { // not legal since the wildcard upper bound is non-null - // BUG: Diagnostic contains: incompatible types: Test.Foo<@Nullable String> cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); // legal String s2 = nonnullWildcard(f2); @@ -348,7 +349,7 @@ void testNegative(Foo<@Nullable String> f) { } void testPositive(Foo<@Nullable String> f) { // not legal since the wildcard upper bound is non-null - // BUG: Diagnostic contains: incompatible types: Test.Foo<@Nullable String> cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -379,7 +380,7 @@ void testNegative(Foo> f) { s.hashCode(); } void testPositive(Foo> f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo> cannot be converted to Test.Foo> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -411,7 +412,7 @@ void testNegative(Foo>> f) { s.hashCode(); } void testPositive(Foo>> f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo>> cannot be converted to Test.Foo>> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -443,7 +444,7 @@ void testNegative(Foo<@Nullable Bar>> f) { s.hashCode(); } void testPositive(Foo<@Nullable Bar>> f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo>> cannot be converted to Test.Foo>> + // BUG: Diagnostic contains: incompatible nullability: found Test.@Nullable Bar>, required Test.Bar> String s = nonnullWildcard(f); s.hashCode(); } @@ -473,7 +474,7 @@ void testNegative(Foo f) { s.hashCode(); } void testPositive(Foo f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String String s = nonnullWildcard(f); s.hashCode(); } @@ -496,22 +497,22 @@ class Foo {} Foo nullableField; Test(Foo f) { nullableField = f; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String nonnullField = f; } Foo nullableReturn(Foo f) { return f; } Foo nonnullReturn(Foo f) { - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return f; } void testLocal(Foo f) { Foo ok = f; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo bad = f; var f2 = f; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Foo bad2 = f2; } } @@ -566,11 +567,11 @@ void testLocals( Foo fromNonnullSuper = nonnullSuperFoo; Foo fromNullableSuper = nullableSuperFoo; Foo fromUnbounded = unboundedFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Foo badFromNonnullSuper = nonnullSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Foo badFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Foo badFromUnbounded = unboundedFoo; } } @@ -595,7 +596,7 @@ void testLocals( NonNullBoundFoo nonnullSuperStringFoo) { NonNullBoundFoo fromNonnull = nonnullObjectFoo; NonNullBoundFoo fromNonnullExtends = nonnullExtendsObjectFoo; - // BUG: Diagnostic contains: incompatible types: Test.NonNullBoundFoo cannot be converted to Test.NonNullBoundFoo + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object NonNullBoundFoo fromNullableExtends = nullableExtendsObjectWithNonnullBoundFoo; NonNullBoundFoo fromSuper = nonnullSuperStringFoo; } @@ -621,13 +622,13 @@ static void nonNullFirstArgument(Pair pair) { static void nullableFirstArgument(Pair<@Nullable String, ?> pair) { Pair<@Nullable String, ? extends @Nullable String> target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String Pair<@Nullable String, ? extends String> invalid = pair; } static void capturedFirstArgument(Pair pair) { Pair target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object Pair invalid = pair; } @@ -636,7 +637,7 @@ static class UnmarkedPair {} static void capturedFirstArgumentFromUnmarkedCode(UnmarkedPair pair) { UnmarkedPair target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object UnmarkedPair invalid = pair; } } @@ -915,18 +916,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String return local.wildcardUpperTypeVariable(); } @@ -960,18 +961,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object return local.wildcardUpperTypeVariable(); } @@ -1479,7 +1480,7 @@ public Foo or(Foo other) { } // We report an error here since we do not infer Foo<@Nullable Void> as the type of the Foo.of call; // javac itself has a similar inference limitation, see https://godbolt.org/z/Y875ahYMx - // BUG: Diagnostic contains: incompatible types: Foo cannot be converted to Foo<@Nullable Void> + // BUG: Diagnostic contains: incompatible nullability: a type argument must match exactly; found Void, required @Nullable Void static final Foo<@Nullable Void> FOO = Foo.of(new Foo<@Nullable Void>()).or(new Foo<@Nullable Void>()); // This works due to the explicit type argument @@ -2079,7 +2080,7 @@ static void nullableSuperBounded(NullableNode node) { } static void superBoundedNullableElements(ListNode> node) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String takesList(node.get()); } } @@ -2127,4 +2128,2506 @@ private CompilationTestHelper makeHelper() { JSpecifyJavacConfig.withJSpecifyModeArgs( Arrays.asList("-XepOpt:NullAway:OnlyNullMarked=true"))); } + + @Test + public void aTypeVariableIsJudgedByItsBoundAgainstAConcreteWildcardRequirement() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void takeNullable(Box b) {} + static void takeAny(Box b) {} + static void takeNonNullList(List l) {} + static void nullableBoundIntoNonNull(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + takeNonNull(b); + } + static void nonNullBoundIntoNonNull(Box b) { + takeNonNull(b); + } + static void nullableBoundIntoNullable(Box b) { + takeNullable(b); + } + static void nullableBoundIntoUnbounded(Box b) { + takeAny(b); + } + static class NonNullParameter {} + static void takeAnyNonNullParameter(NonNullParameter b) {} + static void takeNonNullOfNonNullParameter(NonNullParameter b) {} + static void takeExplicitlyNonNullOfNonNullParameter( + NonNullParameter b) {} + // NonNullParameter is not a well-formed type here, which is a check of its own (#1946) + static void nullableBoundIntoUnboundedNonNullParameter( + NonNullParameter b) { + takeAnyNonNullParameter(b); + } + static void nullableBoundIntoNonNullParameterBound( + NonNullParameter b) { + takeNonNullOfNonNullParameter(b); + takeExplicitlyNonNullOfNonNullParameter(b); + } + static void nullableBoundIntoUnannotatedNonNullRequirement( + List l) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + takeNonNullList(l); + } + static boolean nullableBoundIntoClassOfAnything( + Class other, Class type) { + return other.isAssignableFrom(type); + } + } + """) + .doTest(); + } + + @Test + public void nullnessWrittenOnATypeVariableUseOverridesItsBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void takeNullable(Box b) {} + static void nullableUseIntoNonNull(Box<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required Object + takeNonNull(b); + } + static void nullableUseIntoNullable(Box<@Nullable T> b) { + takeNullable(b); + } + static void nonNullUseIntoNonNull(Box<@NonNull T> b) { + takeNonNull(b); + } + } + """) + .doTest(); + } + + @Test + public void aBoundReachedThroughAnotherVariableOrAWildcardDecidesAgainstAConcreteRequirement() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void variableOverNullableBound( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required Object + takeNonNull(b); + } + static void variableOverNonNullBound(Box b) { + takeNonNull(b); + } + static + void nonNullVariableOverNullableBound(Box b) { + takeNonNull(b); + } + static void wildcardOverNullableBound(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + takeNonNull(b); + } + static void wildcardOverNonNullBound(Box b) { + takeNonNull(b); + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableDeclaredInUnannotatedCodeAdmitsNullOnlyWhenItsBoundSaysSo() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + @NullUnmarked + static class Unannotated { + @NullMarked + void unannotatedDeclarationIntoNonNull(Box b) { + takeNonNull(b); + } + @NullMarked + void variableOverADefaultBound(Box b) { + takeNonNull(b); + } + } + @NullUnmarked + static class UnannotatedNullableBound { + @NullMarked + void explicitNullableBoundIntoNonNull(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + takeNonNull(b); + } + @NullMarked + void variableOverAnExplicitNullableBound(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required Object + takeNonNull(b); + } + } + static class Annotated { + void annotatedDeclarationIntoNonNull(Box b) { + takeNonNull(b); + } + } + @NullUnmarked + static class UnannotatedNonNullBound { + @NullMarked + void explicitNonNullBoundIntoNonNull(Box b) { + takeNonNull(b); + } + @NullMarked + void variableOverAnExplicitNonNullBound(Box b) { + takeNonNull(b); + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableIsJudgedByItsBoundAgainstAWildcardWithALowerBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + void set(E e) {} + } + static class NullableBound { + void takeSuperT(Box b, T t) { + b.set(t); + } + void nonNullArgument(Box b, T t) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeSuperT(b, t); + } + void nonNullLowerBound(Box b, T t) { + // BUG: Diagnostic contains: incompatible types: Box cannot be converted to Box + takeSuperT(b, t); + } + void sameVariable(Box b, T t) { + takeSuperT(b, t); + } + void nullableUse(Box<@Nullable T> b, T t) { + takeSuperT(b, t); + } + void nullableArgument(Box<@Nullable Object> b, T t) { + takeSuperT(b, t); + } + } + static class NonNullBound { + void takeSuperT(Box b, T t) { + b.set(t); + } + void nonNullArgument(Box b, T t) { + takeSuperT(b, t); + } + void nonNullLowerBound(Box b, T t) { + takeSuperT(b, t); + } + } + } + """) + .doTest(); + } + + @Test + public void theTypeArgumentsOfATypeVariableBoundAreComparedAgainstAConcreteRequirement() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNullElements(Box> b) {} + static > void nullableElements(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required String + takeNonNullElements(b); + } + static > void nonNullElements(Box b) { + takeNonNullElements(b); + } + } + """) + .doTest(); + } + + @Test + public void anIntersectionAdmitsNullOnlyWhereEveryElementDoes() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.io.Serializable; + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static void takeNonNull(Box b) {} + static void everyElementNullable( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object & @Nullable Serializable, required Object + takeNonNull(b); + } + static void oneElementNonNull(Box b) { + takeNonNull(b); + } + static void takeNonNullList(List l) {} + static void leastUpperBound(boolean c, List integers, List strings) { + var either = c ? integers : strings; + takeNonNullList(either); + } + @NullUnmarked + static class Unannotated { + @NullMarked + static void everyElementNullable( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object & @Nullable Serializable, required Object + takeNonNull(b); + } + @NullMarked + static void oneElementNonNull( + Box b) { + takeNonNull(b); + } + @NullMarked + static void oneElementBare(Box b) { + takeNonNull(b); + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableIsComparedAsWrittenAgainstAWildcardBoundedByATypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class NullableBound { + void takeExtendsT(Box b) {} + Box sameVariable(Box b) { + return b; + } + void variableThatExtendsIt(Box b) { + takeExtendsT(b); + } + void nullableUse(Box<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T + takeExtendsT(b); + } + void variableThatAdmitsNullBeyondIt(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T + takeExtendsT(b); + } + void variableReachingItThroughANullableLink( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required T + takeExtendsT(b); + } + void variableReachingItThroughANonNullLink(Box b) { + takeExtendsT(b); + } + void nonNullUseOfAVariableThatAdmitsNull(Box<@NonNull S> b) { + takeExtendsT(b); + } + void nullableLinkAboveANonNullLink( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required T + takeExtendsT(b); + } + void takeExtendsNullableT(Box b) {} + void nullableUseIntoNullableProjection(Box<@Nullable T> b) { + takeExtendsNullableT(b); + } + @NullUnmarked + class Unannotated { + @NullMarked + void variableDeclaredInUnannotatedCode(Box b) { + takeExtendsT(b); + } + } + @NullUnmarked + class UnannotatedNullableLink { + @NullMarked + void explicitNullableLinkDeclaredInUnannotatedCode(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T + takeExtendsT(b); + } + } + @NullUnmarked + class UnannotatedNonNullLink { + @NullMarked + void explicitNonNullLinkDeclaredInUnannotatedCode(Box b) { + takeExtendsT(b); + } + } + } + static class NonNullBound { + void takeExtendsT(Box b) {} + void variableThatAdmitsNull(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T + takeExtendsT(b); + } + void variableThatAdmitsNoNull(Box b) { + takeExtendsT(b); + } + void nullableLinkAboveANonNullLink( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required T + takeExtendsT(b); + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableThatMayBeNullFailsANonNullProjectionOfATypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class NullableBound { + void takeExtendsNonNullT(Box b) {} + void bareUse(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T + takeExtendsNonNullT(b); + } + void wildcardUse(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T + takeExtendsNonNullT(b); + } + } + static class NonNullBound { + void takeExtendsNonNullT(Box b) {} + void bareUse(Box b) { + takeExtendsNonNullT(b); + } + } + @NullUnmarked + static class UnannotatedDefaultBound { + @NullMarked + Box bareUse(Box b) { + return b; + } + } + @NullUnmarked + static class UnannotatedNullableBound { + @NullMarked + Box bareUse(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T + return b; + } + } + @NullUnmarked + static class UnannotatedNonNullBound { + @NullMarked + Box bareUse(Box b) { + return b; + } + } + } + """) + .doTest(); + } + + /** + * Taken from Caffeine's {@code CacheLoader.asyncReload}: {@code CompletableFuture.supplyAsync} + * infers {@code CompletableFuture} against {@code CompletableFuture}. + */ + @Test + public void aTypeVariableMeetsAWildcardBoundedByThatSameTypeVariableUnderInference() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.concurrent.CompletableFuture; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + interface Test { + V load(); + CompletableFuture loadFuture(); + default CompletableFuture asyncLoad() { + return CompletableFuture.supplyAsync(() -> load()); + } + default CompletableFuture nonNullFuture() { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + return loadFuture(); + } + } + """) + .doTest(); + } + + @Test + public void anInferredTypeArgumentMeetsAWildcardBoundedByTheSameTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.Collection; + import java.util.Collections; + import java.util.HashSet; + import java.util.List; + import java.util.Set; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List copyOf(Collection c) { + throw new UnsupportedOperationException(); + } + static List copyNonNull( + Collection c) { + throw new UnsupportedOperationException(); + } + void genericMethod(List in) { + List copy = copyOf(in); + } + void writtenNonNullProjection(List in) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T + List copy = copyNonNull(in); + } + void diamond(List in) { + Set set = new HashSet<>(in); + } + static void methodTypeVariable(List in) { + List copy = new ArrayList<>(in); + List view = Collections.unmodifiableList(in); + } + } + """) + .doTest(); + } + + @Test + public void inferenceAddsNoReportAgainstAConcreteWildcard() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.Map; + import java.util.concurrent.CompletableFuture; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + Box(E e) {} + } + static U id(U u) { + return u; + } + static void takeWithValue(U u, Box b) {} + List nonNullElements() { + throw new UnsupportedOperationException(); + } + Map nonNullValues() { + throw new UnsupportedOperationException(); + } + List elements() { + throw new UnsupportedOperationException(); + } + List captureThroughGenericMethod() { + return id(nonNullElements()); + } + List noCaptureThroughGenericMethod() { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + return id(elements()); + } + Box> captureThroughDiamond() { + return new Box<>(nonNullElements()); + } + CompletableFuture> captureThroughLambda() { + return CompletableFuture.supplyAsync(() -> nonNullValues()); + } + static void boundInferredFromAnotherArgument(Box b) { + takeWithValue("x", b); + } + } + """) + .doTest(); + } + + @Test + public void anInferenceVariableFixedByTheTargetExcludesNullAndOneLeftToTheArgumentDoesNot() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static Box idBox(Box b) { + return b; + } + static void variableFixedByAWildcardTarget(Box b) { + // not reported, a known false negative (#1945): the target fixes U as non-null, and + // the argument Box is compared with Box<@NonNull U> by annotation only + Box x = idBox(b); + } + static U first(Box b) { + throw new UnsupportedOperationException(); + } + static Object variableFixedByTheReturnTarget(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T + return first(b); + } + static void variableLeftToTheArgumentThenDereferenced( + Box b) { + first(b).toString(); + } + static void variableFixedByTheTarget(List in) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + List copy = new ArrayList<>(in); + } + static void variableLeftToTheArgument(List in) { + List copy = new ArrayList<>(in); + } + } + """) + .doTest(); + } + + @Test + public void anInferenceResultFixedNonNullKeepsNullOutOfALowerBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E e; + Box(E e) { this.e = e; } + void set(E e) { this.e = e; } + E get() { return e; } + } + static Box id(Box box) { + return box; + } + static Box wrap(E e) { + return new Box<>(e); + } + static void leastSolutionOfANonNullArgument() { + var inferred = wrap(new Object()); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + sink.set(null); + inferred.get().toString(); + } + static void fixedByTheArgument(Box original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + sink.set(null); + original.get().toString(); + } + void fixedByAProjection(Box<@NonNull T> original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + } + } + """) + .doTest(); + } + + /** + * Where javac infers a type argument as a type variable in scope, as {@code E := T} in {@code var + * inferred = id(original)}, the result is judged by the declared bound of {@code T}, which admits + * null. Otherwise a null written through {@code sink} would reach the {@code Box} passed in, + * which holds no null when {@code T} is {@code Object}. + */ + @Test + public void anInferenceResultLeftToATypeVariableIsJudgedAsThatTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + void set(E e) {} + } + static Box id(Box box) { + return box; + } + static Box> nest(Box box) { + throw new UnsupportedOperationException(); + } + void intoTheSameTypeVariable(Box original) { + var inferred = id(original); + Box sink = inferred; + Box source = inferred; + } + void intoANullableLowerBound(Box original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible types + Box sink = inferred; + sink.set(null); + } + void intoANonNullUpperBound(Box original) { + var inferred = id(original); + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + Box source = inferred; + } + void throughADiamond(List original) { + var inferred = new ArrayList<>(original); + List sink = inferred; + // BUG: Diagnostic contains: incompatible types + List nullableSink = inferred; + } + void inANestedTypeArgument(Box original) { + var inferred = nest(original); + Box> sink = inferred; + // BUG: Diagnostic contains: incompatible types + Box> nullableSink = inferred; + } + void ofACapturedWildcard(Box original) { + var inferred = id(original); + Box sink = inferred; + } + } + """) + .doTest(); + } + + /** + * Where javac inferred a class type, such as {@code Object} for the least upper bound of {@code + * T} and {@code String}, an inference variable that a {@code T} whose bound admits null reached + * is {@code @Nullable}: no other nullness of {@code Object} holds a null {@code T}. Every reader + * of the result sees the same {@code @Nullable}, so a list that accepts a null through {@code + * sink} also reports the null read back from it. Where javac inferred {@code T} itself, the + * result is {@code T} and is dereferenced without a report, as {@code t} is (#1727). A + * {@code @NonNull} written on the variable's use keeps that use non-null. + */ + @Test + public void anInferenceResultInferredAsAClassTypeHoldsTheNullOfTheTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static @NonNull U pickNonNull(U a, U b) { + throw new UnsupportedOperationException(); + } + static List<@NonNull U> ofNonNull(U a, U b) { + throw new UnsupportedOperationException(); + } + static void takeObjects(List objects) {} + void throughALocal(T t) { + var inferred = of(t, "x"); + List sink = inferred; + sink.add(null); + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + List source = inferred; + // BUG: Diagnostic contains: dereferenced expression 'inferred.get(0)' is @Nullable + inferred.get(0).toString(); + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + takeObjects(inferred); + } + void throughTheCall(T t) { + List sink = of(t, "x"); + // BUG: Diagnostic contains: dereferenced expression 'pick(t, "x")' is @Nullable + pick(t, "x").toString(); + // BUG: Diagnostic contains: dereferenced expression 'of(t, "x").get(0)' is @Nullable + of(t, "x").get(0).toString(); + } + void explicitlyNonNull(T t) { + pickNonNull(t, "x").toString(); + ofNonNull(t, "x").get(0).toString(); + } + void inferredAsTheTypeVariable(T t) { + pick(t, t).toString(); + } + } + """) + .doTest(); + } + + /** + * The {@code @Nullable} inferred for a class-type result reaches a lambda parameter, an + * enhanced-for variable, and the receiver of a call on the result, which read the inferred type + * rather than the call's return nullness. + */ + @Test + public void aClassTypeResultIsNullableInLambdasLoopsAndReceivers() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Consumer; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static Box wrap(E e) { + throw new UnsupportedOperationException(); + } + static void with(U a, U b, Consumer c) {} + void lambdaParameter(T t) { + with(t, "x", u -> { + // BUG: Diagnostic contains: dereferenced expression 'u' is @Nullable + u.toString(); + }); + } + void loopVariable(T t) { + for (Object o : of(t, "x")) { + // BUG: Diagnostic contains: dereferenced expression 'o' is @Nullable + o.hashCode(); + } + } + void receiver(T t) { + // BUG: Diagnostic contains: dereferenced expression 'wrap(pick(t, "x")).get()' is @Nullable + wrap(pick(t, "x")).get().toString(); + } + } + """) + .doTest(); + } + + /** + * The {@code @Nullable} inferred for a class-type result reaches a wildcard in the result type + * and a wildcard that a member of a diamond's class returns, where javac's type carries a capture + * or a wildcard bound that the inferred nullness was never substituted into. + */ + @Test + public void aClassTypeResultIsNullableInsideAWildcard() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + Box(E a, E b) {} + Box self() { + throw new UnsupportedOperationException(); + } + Box sink() { + throw new UnsupportedOperationException(); + } + E get() { + throw new UnsupportedOperationException(); + } + void set(E e) {} + } + static Box wrap(U a, U b) { + throw new UnsupportedOperationException(); + } + static Box sinkOf(U a, U b) { + throw new UnsupportedOperationException(); + } + void f(T t) { + // BUG: Diagnostic contains: dereferenced expression 'wrap(t, "x").get()' is @Nullable + wrap(t, "x").get().toString(); + sinkOf(t, "x").set(null); + var box = new Box<>(t, "x"); + // BUG: Diagnostic contains: dereferenced expression 'box.self().get()' is @Nullable + box.self().get().toString(); + box.sink().set(null); + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + Box nonNull = box.self(); + } + } + """) + .doTest(); + } + + /** + * A class-type result is {@code @Nullable} only where the bound of the type variable that reached + * it and the bound of the inference variable itself are explicitly nullable, directly or through + * another type variable. Elsewhere it is non-null, the least solution: a type variable from + * unannotated code and an unannotated callee are read optimistically, and a {@code @NonNull} + * written in unannotated code still excludes null. + */ + @Test + public void aClassTypeResultIsNullableOnlyThroughExplicitlyNullableBounds() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static List ofThroughAVariable(E a, E b) { + throw new UnsupportedOperationException(); + } + static List ofThroughANonNullVariable(E a, E b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static List nonNullOf(E a, E b) { + throw new UnsupportedOperationException(); + } + @NullUnmarked + static class Lib { + static List unannotatedOf(E a, E b) { + throw new UnsupportedOperationException(); + } + static List nonNullOf(E a, E b) { + throw new UnsupportedOperationException(); + } + } + static void boundNullableThroughAVariable(T t) { + // BUG: Diagnostic contains: dereferenced expression 'ofThroughAVariable(t, "x").get(0)' is @Nullable + ofThroughAVariable(t, "x").get(0).toString(); + } + static void inferredTypeVariableWhoseBoundExcludesNull( + T t, R r) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, r)' is @Nullable + pick(t, r).toString(); + } + static void inferredTypeVariableWhoseBoundAdmitsNull( + T t, R r) { + // a false negative: R takes no synthetic annotation, and dataflow reads it as non-null (#1727) + pick(t, r).toString(); + } + static void boundNonNullThroughAVariable(T t) { + ofThroughANonNullVariable(t, "x").get(0).toString(); + } + static void ownBoundExcludesNull(T t) { + nonNullOf(t, "x").get(0).toString(); + } + static void unannotatedCallee(T t) { + Lib.unannotatedOf(t, "x").get(0).toString(); + var inferred = Lib.nonNullOf(t, "x"); + inferred.get(0).toString(); + // BUG: Diagnostic contains: incompatible types + List sink = inferred; + } + @NullUnmarked + static class Unmarked { + @NullMarked + void unannotatedTypeVariable(T t) { + var inferred = of(t, "x"); + inferred.get(0).toString(); + // BUG: Diagnostic contains: incompatible types + List sink = inferred; + } + @NullMarked + void nullableBoundInsideUnannotatedOutside(N n, T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(pick(n, "x"), t)' is @Nullable + pick(pick(n, "x"), t).toString(); + } + @NullMarked + void unannotatedInsideNullableBoundOutside(N n, T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(pick(t, "x"), n)' is @Nullable + pick(pick(t, "x"), n).toString(); + } + } + } + """) + .doTest(); + } + + @Test + public void aNullableTypeVariableFlowsThroughADeclaredBoundToAnotherInferenceVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Function; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static R direct(R a, R b) { + return a; + } + static R viaBound(U a, U b) { + return a; + } + static R viaBoundOne(U a) { + return a; + } + static Q deep(U a, U b) { + return a; + } + static R viaNullableBound(U a) { + throw new UnsupportedOperationException(); + } + static R viaNonNullBound(U a) { + return a; + } + static U viaBoundReturningU(U a, R r) { + return a; + } + void sameVariable(T t) { + // BUG: Diagnostic contains: dereferenced expression 'direct(t, "x")' is @Nullable + direct(t, "x").hashCode(); + } + void throughABound(T t) { + // BUG: Diagnostic contains: dereferenced expression 'viaBound(t, "x")' is @Nullable + viaBound(t, "x").hashCode(); + } + static R directOne(R a) { + return a; + } + void inferredAsTheTypeVariable(T t) { + // false negatives: javac infers T for R, and dataflow reads T as non-null (#1727) + directOne(t).hashCode(); + viaBoundOne(t).hashCode(); + } + void throughAChainOfBounds(T t) { + // BUG: Diagnostic contains: dereferenced expression 'deep(t, "x")' is @Nullable + deep(t, "x").hashCode(); + } + void explicitNullThroughABound() { + // BUG: Diagnostic contains: dereferenced expression 'viaBoundOne(null)' is @Nullable + viaBoundOne(null).hashCode(); + } + void explicitNullThroughANullableBound() { + viaNullableBound(null).hashCode(); + } + void explicitNullThroughANonNullBound() { + // BUG: Diagnostic contains: passing @Nullable parameter + viaNonNullBound(null).hashCode(); + } + Object throughABoundIntoANonNullTarget() { + // BUG: Diagnostic contains: inference failure: type variable U constrained to be both @NonNull and @Nullable + return viaBoundOne(null); + } + void notUpward(T t) { + viaBoundReturningU("x", t).hashCode(); + } + static R fromNonNull(U u, List v) { + return u; + } + void throughABoundFromAVariableFixedNonNull(T t, List v) { + // a null t still reaches R: passing t where U is @NonNull Object is not reported (#1727) + // BUG: Diagnostic contains: dereferenced expression 'fromNonNull(t, v)' is @Nullable + fromNonNull(t, v).hashCode(); + } + static R map( + U u, List v, Function f) { + return f.apply(u); + } + void throughALambdaFromAVariableFixedNonNull(T t, List v) { + // BUG: Diagnostic contains: dereferenced expression 'map(t, v, x -> x)' is @Nullable + map(t, v, x -> x).hashCode(); + } + static V throughNonNullBound( + U a, U b, Function f) { + return f.apply(a); + } + static V directNonNullBound( + R a, R b, Function f) { + return f.apply(a); + } + void throughAVariableWhoseBoundExcludesNull(T t) { + // BUG: Diagnostic contains: dereferenced expression 'directNonNullBound(t, "x", x -> x)' is @Nullable + directNonNullBound(t, "x", x -> x).hashCode(); + // BUG: Diagnostic contains: dereferenced expression 'throughNonNullBound(t, "x", x -> x)' is @Nullable + throughNonNullBound(t, "x", x -> x).hashCode(); + } + static R viaNonNullAnnotatedBound(U a) { + return a; + } + Object explicitNullThroughANonNullAnnotatedBound() { + // BUG: Diagnostic contains: passing @Nullable parameter 'null' + return viaNonNullAnnotatedBound(null); + } + static > R nestedBound( + U u, R r) { + throw new UnsupportedOperationException(); + } + static R nestedArgument(List l, R r) { + throw new UnsupportedOperationException(); + } + void throughABoundThatNestsTheVariable(List l) { + // BUG: Diagnostic contains: dereferenced expression 'nestedArgument(l, "x")' is @Nullable + nestedArgument(l, "x").hashCode(); + // a false negative: inference takes no constraint from a bound that nests R (#2192) + nestedBound(l, "x").hashCode(); + } + Object throughAnUnmarkedBound() { + // inference reads no U <: R where U is declared in unannotated code + return Legacy.choose("fallback", null); + } + } + """) + .addSourceLines( + "ModeledDeclaredBound.java", + """ + package com.uber; + import org.jspecify.annotations.NullMarked; + @NullMarked + class ModeledDeclaredBound { + // The test library model makes the bound of U nullable, so inference reads no U <: R. + static R choose(R r, U u) { + return r; + } + Object throughAModeledBound() { + return choose("fallback", null); + } + } + """) + .addSourceLines( + "Legacy.java", + """ + import org.jspecify.annotations.NullUnmarked; + @NullUnmarked + class Legacy { + static R choose(R r, U unused) { + return r; + } + } + """) + .doTest(); + } + + /** + * A generic method reference and a generic constructor are judged against the types javac + * inferred for them, as a generic method call is, so the {@code @Nullable} inferred for {@code U} + * on the referenced method and on the constructor is the one its parameters are checked with. + */ + @Test + public void aGenericMethodReferenceAndAGenericConstructorTakeTheInferredClassType() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Consumer; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + Box(Box input, U hint) {} + } + static class Taker { + Taker(U a, U b, Consumer c) {} + } + class InnerTaker { + InnerTaker(U a, U b) {} + } + static class Holder { + Holder(E a, E b, Function> function) {} + } + static void use(U a, U b, Function> function) {} + static List singleton(V value) { + throw new UnsupportedOperationException(); + } + static List nonNullSingleton(V value) { + throw new UnsupportedOperationException(); + } + void methodReference(T t) { + use(t, new Object(), Test::singleton); + } + static class GenericConstructor { + GenericConstructor(W w) {} + } + static R map(U a, U b, Function function) { + throw new UnsupportedOperationException(); + } + void constructorReference(T t) { + // W takes no inference constraint from a constructor reference, so it stays non-null + // (#1468) + // BUG: Diagnostic contains: parameter w of referenced method is @NonNull, but parameter in functional interface method java.util.function.Function.apply(@Nullable Object) is @Nullable + map(t, new Object(), GenericConstructor::new); + } + void methodReferenceToANonNullVariable(T t) { + // BUG: Diagnostic contains: parameter value of referenced method is @NonNull + use(t, new Object(), Test::nonNullSingleton); + } + void lambdaPassedToAConstructor(T t) { + new Taker<>(t, "x", u -> { + // BUG: Diagnostic contains: dereferenced expression 'u' is @Nullable + u.toString(); + }); + } + void anonymousSubclassOfAnInnerClass(T t) { + this.new InnerTaker<>(t, "x") {}; + } + void methodReferenceIntoADiamond(T t) { + var holder = new Holder<>(t, new Object(), Test::singleton); + } + void constructor(Box input) { + var result = new Box<>(input, new Object()); + } + static class ListAndElement { + ListAndElement(List ws, W w, E e) {} + } + static class Mapped { + Mapped(W w, Function f) {} + } + static U identity(U u) { + return u; + } + void constructorTakingAListOfNullableElements(List<@Nullable String> l) { + var c = + new ListAndElement<>( + l, + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + null, + "x"); + } + void constructorTakingAGenericMethodReference(@Nullable String s) { + var c = + new Mapped<>( + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 's' where @NonNull is required + s, + Test::identity); + } + void methodReferenceOutsideACall() { + Function> f = Test::singleton; + f = (Test::singleton); + } + static class TwoLists { + TwoLists(U a, U b) {} + } + static V nonNullIdentity(V v) { + return v; + } + void takeFn(X x, Function, List<@Nullable T>> f) {} + void genericConstructorAtADiamondTakingTwoLists(List a, List<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T + var c = new TwoLists<>(a, b); + } + void genericMethodReferenceUnderAGenericCall() { + // BUG: Diagnostic contains: referenced method returns List, but functional interface method returns List<@Nullable T> + takeFn("x", Test::nonNullIdentity); + } + } + """) + .doTest(); + } + + @Test + public void aClassTypeResultIsNullableThroughNestedCallsOfOneMethod() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + final E value; + Box(E value) { + this.value = value; + } + E get() { + return value; + } + } + static U pick(U a, U b) { + return a; + } + void nestedDiamonds(T t) { + new Box<>(new Box<>(t)).get().toString(); + } + void nestedCallsOfOneMethod(T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(pick(t, "x"), "y")' is @Nullable + pick(pick(t, "x"), "y").toString(); + } + } + """) + .doTest(); + } + + /** + * Dataflow reads a {@code T} whose bound admits null as non-null whether or not the code checked + * it (#1727), so inference cannot tell a checked {@code t} from an unchecked one, and a + * class-type result is {@code @Nullable} after a null check or {@code requireNonNull} too. These + * are false positives; an explicit type argument skips inference and avoids them. + */ + @Test + public void aNullCheckOfATypeVariableDoesNotReachInference() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.Objects; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static U pick(U a, U b) { + return a; + } + void nullCheck(T t) { + if (t != null) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, "x")' is @Nullable + pick(t, "x").toString(); + } + } + void requireNonNull(T t) { + T checked = Objects.requireNonNull(t); + // BUG: Diagnostic contains: dereferenced expression 'pick(checked, "x")' is @Nullable + pick(checked, "x").toString(); + } + void explicitTypeArgument(T t) { + if (t != null) { + Test.pick(t, "x").toString(); + } + } + } + """) + .doTest(); + } + + /** + * Where javac inferred an intersection type, such as the least upper bound of two classes that + * implement {@code Runnable} and {@code Serializable}, the result carries no annotation, since + * the root of an intersection takes the nullness of its elements, so it stays non-null even where + * a {@code T} that admits null reached it. + */ + @Test + public void aClassTypeResultInferredAsAnIntersectionStaysNonNull() { + // on JDK 17, javac refuses to annotate an intersection type, and NullAway fails on this source + // whether or not this change is applied + Assume.assumeTrue(Runtime.version().feature() > 17); + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.io.Serializable; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class A implements Runnable, Serializable { + public void run() {} + } + static class B implements Runnable, Serializable { + public void run() {} + } + static E pick(E a, E b) { + return a; + } + void intersection(T t) { + pick(t, new B()).run(); + } + void classType(T t) { + // BUG: Diagnostic contains: dereferenced expression 'pick(t, new A())' is @Nullable + pick(t, new A()).run(); + } + } + """) + .doTest(); + } + + /** + * Without wildcard handling, a capture flows into an inference variable as a type variable, so a + * capture whose bound admits null is as parametric as a type variable {@code T} whose bound + * admits null, and the call keeps it as javac inferred it. + */ + @Test + public void aCaptureWhoseBoundAdmitsNullStaysAsInferredWithWildcardHandlingDisabled() { + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + Arrays.asList( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:HandleWildcardGenerics=false"))) + .addSourceLines( + "Test.java", + """ + import java.util.function.BiPredicate; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + interface Action { + R run() throws Exception; + } + static R call(Action action) { + throw new UnsupportedOperationException(); + } + interface Seq extends Iterable { + Seq seq(); + default boolean corresponds( + Iterable that, BiPredicate predicate) { + return true; + } + } + static U first(Iterable elements) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + Seq anySeq() { + throw new UnsupportedOperationException(); + } + Seq seqOfT() { + throw new UnsupportedOperationException(); + } + Seq<@Nullable String> nullableStrings() { + throw new UnsupportedOperationException(); + } + void castToAWildcardType() { + call((Action) () -> { + throw new Exception(); + }); + } + void receiverOfAWildcardType(Seq self, Seq that) { + self.seq().corresponds(that.seq(), (a, b) -> true); + } + void unboundedWildcard() { + first(anySeq()).hashCode(); + } + void wildcardBoundedByATypeVariable() { + T t = first(seqOfT()); + } + void wildcardBoundedByATypeVariableIntoAClassTypeResult() { + // BUG: Diagnostic contains: dereferenced expression 'pick(first(seqOfT()), "x")' is @Nullable + pick(first(seqOfT()), "x").toString(); + } + void nullableTypeArgument() { + // BUG: Diagnostic contains: dereferenced expression 'first(nullableStrings())' is @Nullable + first(nullableStrings()).hashCode(); + } + } + """) + .doTest(); + } + + /** + * A value read through {@code ? extends T}, where the bound of {@code T} admits null, may be + * null. A generic call that javac infers to return the capture of that wildcard returns such a + * value too, as reading the element directly does. + */ + @Test + public void aCallReturningACaptureOfAWildcardBoundedByATypeVariableMayReturnNull() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class NullableBox implements Iterable { + public java.util.Iterator iterator() { + throw new UnsupportedOperationException(); + } + } + static class NonNullBox implements Iterable { + public java.util.Iterator iterator() { + throw new UnsupportedOperationException(); + } + } + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static U first(Iterable it) { + throw new UnsupportedOperationException(); + } + static U get(Box b) { + throw new UnsupportedOperationException(); + } + static U getThroughWildcard(Box b) { + throw new UnsupportedOperationException(); + } + static U firstNonNull(Iterable it) { + throw new UnsupportedOperationException(); + } + void readDirectly(Box b, List l) { + // BUG: Diagnostic contains: dereferenced expression 'b.get()' is @Nullable + b.get().toString(); + // BUG: Diagnostic contains: dereferenced expression 'l.get(0)' is @Nullable + l.get(0).toString(); + } + void throughAContainerWhoseParameterAdmitsNull(NullableBox b) { + // BUG: Diagnostic contains: dereferenced expression 'first(b)' is @Nullable + first(b).toString(); + } + void throughAContainerWhoseParameterExcludesNull(NonNullBox b) { + // BUG: Diagnostic contains: dereferenced expression 'first(b)' is @Nullable + first(b).toString(); + } + void throughTheSameContainer(Box b) { + // BUG: Diagnostic contains: dereferenced expression 'get(b)' is @Nullable + get(b).toString(); + } + void throughAWildcardParameter(Box b) { + // BUG: Diagnostic contains: dereferenced expression 'getThroughWildcard(b)' is @Nullable + getThroughWildcard(b).toString(); + } + void intoAVariableWhoseBoundExcludesNull(NullableBox b) { + // the call that passes b for U goes unchecked (#2189), and the value still reads + // through ? extends T + // BUG: Diagnostic contains: dereferenced expression 'firstNonNull(b)' is @Nullable + firstNonNull(b).toString(); + } + void theTypeVariableItself(Box b, NullableBox n) { + get(b).toString(); + first(n).toString(); + } + void aWildcardWhoseBoundExcludesNull(Box b) { + get(b).toString(); + } + } + """) + .doTest(); + } + + @Test + public void + aCallResultTypedAsACaptureOfAWildcardBoundedByATypeVariablePassesWhereThatCaptureIsExpected() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static class Holder { + Holder(W w) {} + } + static class Sink { + void take(X x) {} + } + static U first(List list) { + throw new UnsupportedOperationException(); + } + static U get(Box b) { + throw new UnsupportedOperationException(); + } + static U getThroughWildcard(Box b) { + throw new UnsupportedOperationException(); + } + static void accept(X x) {} + static X ret(X x) { + return x; + } + @SafeVarargs + static void acceptAll(X... xs) {} + static void acceptTwo(X a, X b) {} + static B apply( + A a, Function f) { + return f.apply(a); + } + static void acceptNonNull(X x) {} + static V identity(V v) { + return v; + } + void fromAList(List list) { + accept(first(list)); + } + void fromTheSameContainer(Box b) { + accept(get(b)); + } + void fromAWildcardParameter(Box b) { + accept(getThroughWildcard(b)); + } + void intoAGenericMethodWhoseResultIsUnused(List list) { + ret(first(list)); + } + void throughTwoNestedCalls(List list) { + accept(ret(ret(first(list)))); + } + void intoAnInstanceMethod(Sink sink, List list) { + sink.take(first(list)); + } + void intoVarargs(List list) { + acceptAll(first(list)); + } + void twoCapturesOfOneWildcardType(List a, List b) { + acceptTwo(first(a), first(b)); + } + void intoADiamondConstructor(List list) { + new Holder<>(first(list)); + } + void besideAMethodReference(List list) { + apply(first(list), Test::identity); + } + void returnedAsTheTypeVariable(List list) { + accept(returnFirst(list)); + } + T returnFirst(List list) { + return first(list); + } + void readByAMemberCall(Box b) { + accept(b.get()); + } + void intoAVariableWhoseBoundExcludesNull(List list) { + // BUG: Diagnostic contains: passing @Nullable parameter 'first(list)' + acceptNonNull(first(list)); + } + void dereferenced(List list) { + // BUG: Diagnostic contains: dereferenced expression 'ret(first(list))' is @Nullable + ret(first(list)).toString(); + } + } + """) + .doTest(); + } + + /** + * The JSpecify JDK models decide the bound of the inference variable: {@code Arrays.asList} + * admits null and {@code List.of} does not. + */ + @Test + public void aClassTypeResultFromTheJdkFollowsTheModelsBound() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.Arrays; + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + void f(T t) { + // BUG: Diagnostic contains: dereferenced expression 'Arrays.asList(t, "x").get(0)' is @Nullable + Arrays.asList(t, "x").get(0).toString(); + List.of(t, "x").get(0).toString(); + } + } + """) + .doTest(); + } + + @Test + public void inferenceCannotFitATypeVariableWhoseBoundAdmitsNullIntoANonNullVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.ArrayList; + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static U nonNullVariable(Box b) { + throw new UnsupportedOperationException(); + } + static U nullableVariable(Box b) { + throw new UnsupportedOperationException(); + } + static U intoAWildcardOfAFixedType( + Box b, U u) { + return u; + } + static V pair(Box b, V v) { + throw new UnsupportedOperationException(); + } + static U nonNullVariableWithValue(Box b, U u) { + return u; + } + static void intoNonNullVariable(Box b) { + // BUG: Diagnostic contains: inference failure: type variable U of Test.nonNullVariable is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends U admits null, since T of Test.intoNonNullVariable has a @Nullable upper bound + Object o = nonNullVariable(b); + } + static void intoNonNullVariableThroughAWildcard( + Box b) { + // a false negative: a wildcard bounded by T is not checked against the bound of U (#2189) + Object o = nonNullVariable(b); + } + static class Holder { + Box wildBox() { + throw new UnsupportedOperationException(); + } + List wildList() { + throw new UnsupportedOperationException(); + } + } + static void intoNonNullVariableThroughACapture( + Holder h) { + // a false negative: a capture bounded by T is not checked against the bound of U (#2189) + Object o = nonNullVariable(h.wildBox()); + } + static class BoundedByANullableVariable { + Box box() { + throw new UnsupportedOperationException(); + } + } + static void captureOfATypeParameterBoundedByANullableVariable( + BoundedByANullableVariable h) { + // a false negative: a capture whose bound reaches T is not checked against the bound of U (#2189) + Object o = nonNullVariable(h.box()); + } + static class Set { + void copyOf(java.util.Collection in) { + // BUG: Diagnostic contains: type variable E of java.util.Set.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument E passed for ? extends E admits null, since E of Test$Set.copyOf has a @Nullable upper bound + java.util.Set copy = java.util.Set.copyOf(in); + } + } + static void intoJdkCopyOfThroughACapture(Holder h) { + // a false negative: a capture bounded by T is not checked against the bound of E (#2189) + List copy = List.copyOf(h.wildList()); + } + static class Base {} + static class Sub extends Base {} + static class NonNullList extends ArrayList {} + static void intoBase(Base b) {} + static void wildcardOfASubclassWhoseTypeParameterExcludesNull( + Sub s) { + intoBase(s); + } + static void wildcardOfANonNullListIntoJdkCopyOf( + NonNullList nl) { + List copy = List.copyOf(nl); + } + static class Pair {} + static void intoSelfPair(Pair p) {} + static void wildcardOfAPairWhoseSiblingIsNonNull( + Pair p) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable S, required S + intoSelfPair(p); + } + static void wildcardOfAPairWhoseSiblingAdmitsNull( + Pair p) { + // a false negative: a wildcard bounded by X is not checked against the bound of U (#2189) + intoSelfPair(p); + } + static void intoNullableVariable(Box b) { + nullableVariable(b).toString(); + } + static void intoAWildcardThatIsNotAnInferenceVariable( + Box b) { + Object o = intoAWildcardOfAFixedType(b, "x"); + } + static void nonNullBoundIntoNonNullVariable(Box b) { + Object o = nonNullVariable(b); + } + static B apply( + A a, java.util.function.Function f) { + throw new UnsupportedOperationException(); + } + static void intoJdkCopyOfThroughAMethodReference( + List in) { + // a false negative: T reaches copyOf through another generic call (#1947) + List copy = apply(in, List::copyOf); + } + static void intoJdkCopyOfInsideALambda(List in) { + // a false negative: T reaches copyOf through another generic call (#1947) + List copy = apply(in, l -> List.copyOf(l)); + } + static void bareTypeVariableIntoJdkListOf(T t) { + // a false negative: only a ? extends U formal constrains U against a T that admits null (#1932) + List list = List.of(t); + } + static List copy(Box b) { + throw new UnsupportedOperationException(); + } + static void intoNullableVariableThatTheContextMakesNonNull( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + List c = copy(b); + } + static void intoNonNullVariableByAnExplicitTypeArgument( + Box b) { + // a false negative: only a type argument annotated @Nullable is checked against the bound of U (#1946) + Object o = Test.nonNullVariable(b); + } + static void nonNullTypeVariableIntoNonNullVariable( + Box<@NonNull T> b) { + Object o = nonNullVariable(b); + } + static void failureDiscardsTheOtherVariablesOfTheCall( + Box b) { + // BUG: Diagnostic contains: inference failure: type variable U of Test.pair is constrained to be @Nullable + pair(b, + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + null) + .hashCode(); + } + @NullUnmarked + static class Legacy { + static List identity(List xs) { + return xs; + } + } + static void intoJdkCopyOfThroughAnUnmarkedCall( + List in) { + var inferred = Legacy.identity(in); + // BUG: Diagnostic contains: inference failure: type variable E of List.copyOf is constrained to be @Nullable + List copy = List.copyOf(inferred); + } + static void intoJdkCopyOfNestingAnUnmarkedCall( + List in) { + // a false negative: the unmarked call's result reaches copyOf without a local (#1947) + List copy = List.copyOf(Legacy.identity(in)); + } + static List markedIdentity(List xs) { + return xs; + } + static void intoJdkCopyOfNestingAMarkedCall( + List in) { + // a false negative: the marked call's result reaches copyOf without a local (#1947) + List copy = List.copyOf(markedIdentity(in)); + } + static void intoJdkCopyOfThroughADiamond(List in) { + // a false negative: the diamond's result reaches copyOf without a local (#1947) + List copy = List.copyOf(new ArrayList<>(in)); + } + static void intoNonNullVariableFixedByAnotherArgument( + Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + Object o = nonNullVariableWithValue(b, new Object()); + } + static void intoJdkCopyOf(List in) { + // BUG: Diagnostic contains: inference failure: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument T passed for ? extends E admits null, since T of Test.intoJdkCopyOf has a @Nullable upper bound + List copy = List.copyOf(in); + } + static void sameNameAsTheVariableOfCopyOf(List in) { + // BUG: Diagnostic contains: type variable E of List.copyOf is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument E passed for ? extends E admits null, since E of Test.sameNameAsTheVariableOfCopyOf has a @Nullable upper bound + List copy = List.copyOf(in); + } + static void genericMethodOfAnAnonymousClass() { + new Object() { + void copy(List in) { + // BUG: Diagnostic contains: since E of Test$1.copy has a @Nullable upper bound + List copy = List.copyOf(in); + } + }; + } + static class GenericConstructor { + GenericConstructor(Box b) {} + } + static void intoAGenericConstructor(Box b) { + // BUG: Diagnostic contains: type variable W of the constructor of GenericConstructor is constrained to be @Nullable + GenericConstructor c = new GenericConstructor<>(b); + } + } + """) + .doTest(); + } + + @Test + public void anInferenceFailureNamesTheTypeVariableWhoseBoundIsNullable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + void classTypeVariable(List in) { + // BUG: Diagnostic contains: the type argument T passed for ? extends E admits null, since T of Test has a @Nullable upper bound + List copy = List.copyOf(in); + } + static void boundedByATypeVariable( + List in) { + // BUG: Diagnostic contains: the type argument S passed for ? extends E admits null, since S of Test.boundedByATypeVariable extends R of Test.boundedByATypeVariable, which has a @Nullable upper bound + List copy = List.copyOf(in); + } + static + void boundedThroughTwoTypeVariables(List in) { + // BUG: Diagnostic contains: since S of Test.boundedThroughTwoTypeVariables extends Q of Test.boundedThroughTwoTypeVariables, which has a @Nullable upper bound + List copy = List.copyOf(in); + } + void boundedByTheClassTypeVariable(List in) { + // BUG: Diagnostic contains: since S of Test.boundedByTheClassTypeVariable extends T of Test, which has a @Nullable upper bound + List copy = List.copyOf(in); + } + static void boundedByANonNullUse( + List in) { + List copy = List.copyOf(in); + } + static class Source { + static class Box { + static List copy(List in) { + throw new UnsupportedOperationException(); + } + } + } + static class Target { + static class Box { + static void copy(List in) { + // BUG: Diagnostic contains: type variable U of Test$Source$Box.copy is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument U passed for ? extends U admits null, since U of Test$Target$Box.copy extends R of Test$Target$Box.copy, which has a @Nullable upper bound + List copy = Source.Box.copy(in); + } + } + } + static class Witness { + static class Box { + static void copy(List in) { + // BUG: Diagnostic contains: type variable U of Test$Source$Box.copy is constrained to be @Nullable, but its upper bound requires it to be @NonNull; the type argument S passed for ? extends U admits null, since S of Test$Witness$Box.copy extends U of Test$Witness$Box.copy, which has a @Nullable upper bound + List copy = Source.Box.copy(in); + } + } + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableWithANullableBoundChangesNoReportWithJSpecifyModeAlone() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG)) + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.Objects; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static U pick(U a, U b) { + return a; + } + static List of(E a, E b) { + throw new UnsupportedOperationException(); + } + static class C { + C(U a, U b) {} + } + static void m(U a, U b) {} + static V identity(V v) { + return v; + } + void takeFn(X x, Function, List<@Nullable T>> f) {} + static class Mapped { + Mapped(W w, Function f) {} + } + static class ListAndElement { + ListAndElement(List ws, W w, E e) {} + } + static U nullableIdentity(U u) { + return u; + } + static void apply(A a, Function f) {} + static R viaBound(U a, U b) { + return a; + } + static R viaBoundOne(U a) { + return a; + } + void typeVariable(T t) { + pick(t, "x").toString(); + } + void typeVariableThroughADeclaredBound(T t) { + viaBound(t, "x").toString(); + } + void nullThroughADeclaredBound() { + viaBoundOne(null).toString(); + } + void typeVariableAfterRequireNonNull(T t) { + T checked = Objects.requireNonNull(t); + pick(checked, "x").toString(); + } + void typeVariableInAnEnhancedFor(T t) { + for (Object o : of(t, "x")) { + o.toString(); + } + } + void nullableArgument(@Nullable String s) { + // BUG: Diagnostic contains: dereferenced expression 'pick(s, "x")' is @Nullable + pick(s, "x").toString(); + } + void genericConstructorAtADiamond(List a, List<@Nullable T> b) { + var c = new C<>(a, b); + } + void genericMethod(List a, List<@Nullable T> b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable T, required T + m(a, b); + } + void genericMethodReferenceUnderAGenericCall() { + takeFn("x", Test::identity); + } + void genericMethodReferenceTakingANullableArgument(@Nullable String s) { + apply(s, Test::nullableIdentity); + } + void genericConstructorTakingAListOfNullableElements(List<@Nullable String> l) { + var c = + new ListAndElement<>( + // a false positive that JSpecifyExperimental removes + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required W + l, + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 'null' where @NonNull is required + null, + "x"); + } + void genericMethodReferenceUnderADiamond(@Nullable String s) { + var mapped = + new Mapped<>( + // a false positive: W of a generic constructor at a diamond is not inferred + // (#1825) + // BUG: Diagnostic contains: passing @Nullable parameter 's' where @NonNull is required + s, + // a false positive that JSpecifyExperimental removes + // BUG: Diagnostic contains: parameter u of referenced method is @NonNull + Test::nullableIdentity); + } + } + """) + .doTest(); + } + + @Test + public void + aCaptureOfAWildcardBoundedByATypeVariableChangesNoReportWithoutJSpecifyExperimental() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG, + "-XepOpt:NullAway:HandleWildcardGenerics=true")) + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box { + E get() { + throw new UnsupportedOperationException(); + } + } + static U first(List list) { + throw new UnsupportedOperationException(); + } + static X ret(X x) { + return x; + } + static void accept(X x) {} + static void nonNullParameter(Object o) {} + void callResultThroughAGenericCallDereferenced(List list) { + ret(first(list)).toString(); + } + void callResultIntoAGenericParameter(List list) { + accept(first(list)); + } + void memberCallResultIntoAGenericParameter(Box b) { + accept(b.get()); + } + Object memberCallResultReturnedThroughAGenericCall(Box b) { + return ret(b.get()); + } + T memberCallResultReturnedAsTheTypeVariable(Box b) { + return ret(b.get()); + } + void memberCallResultIntoANonNullParameter(Box b) { + // BUG: Diagnostic contains: passing @Nullable parameter 'b.get()' + nonNullParameter(b.get()); + } + } + """) + .doTest(); + } + + @Test + public void aTypeVariableWithANullableBoundFailsNoInferenceWithoutJSpecifyExperimental() { + makeTestHelperWithArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + JSpecifyJavacConfig.JSPECIFY_MODE_FLAG, + JSpecifyJavacConfig.ADD_TYPE_ANNOTATIONS_FLAG, + "-XepOpt:NullAway:HandleWildcardGenerics=true", + "-XepOpt:NullAway:WarnOnGenericInferenceFailure=true")) + .addSourceLines( + "Test.java", + """ + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static U nonNullVariable(Box b) { + throw new UnsupportedOperationException(); + } + static U pick(U a, U b) { + return a; + } + static class GenericConstructor { + GenericConstructor(Box b) {} + } + static class NullableGenericConstructor { + NullableGenericConstructor(Box b) {} + } + static class Sink { + Sink(java.util.List target) {} + } + void typeVariableIntoADiamondWhoseVariableAdmitsNull(Box b) { + var c = new NullableGenericConstructor<>(b); + var s = new Sink<>(new java.util.ArrayList()); + } + void typeVariable(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required T + Object o = nonNullVariable(b); + } + void typeVariableIntoADiamond(Box b) { + // not reported, a known false negative: NullAway infers no W for a generic + // constructor without JSpecifyExperimental (#1585) + var c = new GenericConstructor<>(b); + } + void nullableTypeArgumentIntoADiamond(Box<@Nullable String> b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required W + var c = new GenericConstructor<>(b); + } + static R viaBound(U a, U b) { + return a; + } + static R viaBoundOne(U a) { + return a; + } + void typeVariableIntoAClassTypeResult(T t) { + pick(t, "x").toString(); + } + void typeVariableThroughADeclaredBound(T t) { + viaBound(t, "x").toString(); + } + void nullThroughADeclaredBound() { + viaBoundOne(null).toString(); + } + void nullableTypeArgument(Box<@Nullable String> b) { + // BUG: Diagnostic contains: inference failure + Object o = nonNullVariable(b); + } + } + """) + .doTest(); + } + + @Test + public void aCaptureIsJudgedByItsWildcardBoundOutsideTheInferredTypeOfAGenericCall() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.Map; + import java.util.Set; + import java.util.concurrent.CompletableFuture; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static U id(U u) { + return u; + } + interface ConcreteRequirement { + Box get(); + Box getNonNull(); + default Box passCall() { + // BUG: Diagnostic contains: found: Box + return get(); + } + default Box passVariable(Box b) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable Object, required Object + return b; + } + default void assignCall() { + // BUG: Diagnostic contains: found: Box + Box x = get(); + } + default Box passNonNullCall() { + return getNonNull(); + } + default Box passNonNullCallThroughInference() { + return id(getNonNull()); + } + default Box passParenthesizedNonNullCallThroughInference() { + return (id(getNonNull())); + } + default Box passNonNullCallThroughAVarLocal() { + var v = id(getNonNull()); + return v; + } + // a capture javac made while inferring id's type has lost any annotation on its + // bound, so a bound written bare is not reported either (#2195) + default Box passCallThroughInference() { + return id(get()); + } + } + static class RunnableBox {} + interface IntersectionRequirement { + RunnableBox loadAll(); + // the capture's bound is V & @Nullable Runnable, an intersection; inference drops + // the @NonNull as in NonNullProjectionRequirement.asyncLoadAll (#1585) + default CompletableFuture> async() { + return CompletableFuture.supplyAsync(() -> loadAll()); + } + } + interface IntersectionDirectRequirement { + RunnableBox loadAll(); + // the capture's bound is V & @Nullable Runnable, and neither element excludes null + default RunnableBox pass() { + // BUG: Diagnostic contains: found: RunnableBox + return loadAll(); + } + } + interface IntersectionToItsElement { + RunnableBox loadAll(); + // the capture's bound V & @Nullable Runnable reaches V through its element V + default RunnableBox pass() { + return loadAll(); + } + } + interface AllInterfaceIntersection { + RunnableBox load(); + // the capture's bound @Nullable AutoCloseable & @Nullable Runnable has no element + // that excludes null; javac adds an implicit Object element that is not written + default RunnableBox pass() { + // BUG: Diagnostic contains: found: RunnableBox + return load(); + } + } + interface IntersectionReachingNoElement< + W extends @Nullable Object, V extends @Nullable W> { + RunnableBox loadAll(); + // V reaches W only through the nullable link V extends @Nullable W + default RunnableBox pass() { + // BUG: Diagnostic contains: found: RunnableBox + return loadAll(); + } + } + interface BareRequirement { + Map loadAll(); + default Map pass() { + return loadAll(); + } + } + interface NonNullProjectionOfAnIntermediateVariable< + V extends @Nullable Object, S extends @Nullable V> { + Map loadAll(); + default CompletableFuture> loadAllAsync() { + return CompletableFuture.supplyAsync(() -> loadAll()); + } + } + interface NonNullProjectionRequirement { + Map loadAll(Set keys); + default CompletableFuture> asyncLoadAll( + Set keys) { + return CompletableFuture.supplyAsync(() -> loadAll(keys)); + } + } + } + """) + .doTest(); + } + + @Test + public void aGenericMethodOverrideMeetsAWildcardBoundedByTheOverriddenMethodTypeVariable() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.function.Function; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + interface Mapper { + Mapper map(Function f); + Box wrap(V v); + Box get(); + Box getWildcard(); + } + abstract static class Impl implements Mapper { + @Override + public abstract Mapper map( + Function f); + @Override + public abstract Box wrap(V v); + } + abstract static class NonNullProjection implements Mapper { + @Override + public abstract Mapper map( + // BUG: Diagnostic contains: mismatched type parameter nullability + Function f); + @Override + public abstract Box wrap(V v); + } + abstract static class Narrowed implements Mapper { + @Override + // BUG: Diagnostic contains: Method type variable R has a non-null upper bound + public abstract + // a report on the parameter's own line would fail the test as unexpected + Mapper map( + Function f); + @Override + public abstract Box wrap(V v); + @Override + // BUG: Diagnostic contains: Method type variable U has a non-null upper bound + public abstract + // a report on the method name's line would fail the test as unexpected + Box + get(); + @Override + // BUG: Diagnostic contains: Method type variable U has a non-null upper bound + public abstract + Box + getWildcard(); + } + } + """) + .doTest(); + } + + @Test + public void anUninferredTypeVariableRejectsOnlyAnExplicitlyNullableTypeArgument() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import java.util.function.Consumer; + import java.util.function.Function; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + static class Box {} + static class NullableConsumer { + NullableConsumer(Box input) {} + } + static class GenericNullableConsumer { + GenericNullableConsumer(Box input) {} + } + static class StrictConsumer { + StrictConsumer(Box input) {} + } + static class Copier { + Copier(List source, List target) {} + } + interface Sink { + void accept(List elements); + } + static List singleton(U value) { + use(Test::singleton); + throw new UnsupportedOperationException(); + } + static void take(Box input) {} + static void takeAny(Box input) {} + static void takeNonNull(List elements) {} + static void use(Function> f) {} + static void useBoxes(Consumer> c) {} + static void useSink(Sink sink) {} + void aTypeVariableWhoseBoundAdmitsNull(Box input) { + new NullableConsumer(input); + new GenericNullableConsumer(input); + new NullableConsumer(input) {}; + new NullableConsumer(input); + use(Test::singleton); + } + void aTypeVariableWhoseBoundAdmitsNullIntoOneThatExcludesIt(Box input) { + // not reported, a known false negative: NullAway infers no U for a generic + // constructor called without a diamond (#2191) + new StrictConsumer(input); + } + void anExplicitlyNullableTypeArgument( + Box<@Nullable String> nullable, List<@Nullable String> source, List target) { + // BUG: Diagnostic contains: incompatible nullability: found @Nullable String, required U + new StrictConsumer(nullable); + // BUG: Diagnostic contains: found: List<@Nullable String> + new Copier(source, target); + // BUG: Diagnostic contains: parameter type of referenced method is Box + useBoxes(Test::take); + } + void explicitMethodReferenceTypeArguments() { + useBoxes(Test::<@Nullable String>takeAny); + // BUG: Diagnostic contains: parameter type of referenced method is Box + useBoxes(Test::takeAny); + } + void aTypeVariableOfAGenericFunctionalInterfaceMethodKeepsItsBound() { + // BUG: Diagnostic contains: parameter type of referenced method is List + useSink(Test::takeNonNull); + } + void aTypeVariableInScope(Box box) { + // BUG: Diagnostic contains: found: Box + Box nonNull = box; + } + void referencedBeforeItsDeclaration() { + use(Test::boxed); + } + static List boxed(U value) { + Box box = new Box<>(); + // BUG: Diagnostic contains: found: Box + Box nonNull = box; + throw new UnsupportedOperationException(); + } + void constructedBeforeItsDeclaration(Box input) { + new Checked(input); + } + static class Checked { + Checked(Box input) { + Box box = new Box<>(); + // BUG: Diagnostic contains: found: Box + Box nonNull = box; + } + } + } + """) + .doTest(); + } + + @Test + public void anOverrideReturnTypeMustKeepANonNullProjection() { + makeHelper() + .addSourceLines( + "Test.java", + """ + import java.util.List; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + interface Test { + List get(); + static Test widened() { + return new Test<>() { + // BUG: Diagnostic contains: Method returns List, but overridden method returns List, which has mismatched type parameter nullability + @Override public List get() { + throw new UnsupportedOperationException(); + } + }; + } + static Test kept() { + return new Test<>() { + @Override public List<@NonNull V> get() { + throw new UnsupportedOperationException(); + } + }; + } + } + """) + .doTest(); + } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java new file mode 100644 index 0000000000..62a78be896 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -0,0 +1,212 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A caret marks, in both printed types, the smallest node that differs in nullness, and no node the + * target accepts as it is. + */ +public class CaretTests extends MismatchMessageTestBase { + + @Test + public void onlyTheInnermostDifferingNodeIsMarkedInsideAWildcardBound() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List> + ^^^^^^^^^^^^^^^^ + required: List> + ^^^^^^ + path: List type argument E -> wildcard upper bound -> List type argument E + """, + """ + static void take(List> l) {} + void test(List> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void caretSkipsATypeArgumentTheTargetAccepts() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V -> wildcard upper bound + """, + """ + static void take(Map m) {} + void accepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void caretNamesTheConcreteArgumentWhenEveryWildcardIsAccepted() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + """ + static void take(Map m) {} + void accepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void caretMarksTheFailingArgumentWhereTheTargetRepeatsAType() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Three + ^^^^^^^^^^^^^^^^ + required: Three + ^^^^^^ + path: Three type argument C + """, + """ + static class Three {} + static void take(Three t) {} + void test(Three t) { + // BUG: Diagnostic matches: MESSAGE + take(t); + } + """); + } + + @Test + public void onlyTheFailingArgumentIsNamedBesideAWildcardTheTargetAccepts() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Three + ^^^^^^^^^^^^^^^^ + required: Three + ^^^^^^ + path: Three type argument C + """, + """ + static class Three {} + static void take(Three t) {} + void test(Three t) { + // BUG: Diagnostic matches: MESSAGE + take(t); + } + """); + } + + @Test + public void bothPositionsAreMarkedWhereOneInstanceFillsTwoTypeArguments() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source wildcard is the type argument for type parameter E of List + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source wildcard is the type argument for type parameter E of List + """, + """ + static Map duplicate(List x) { + throw new RuntimeException(); + } + static void take(Map m) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(duplicate(l)); + } + """); + } + + @Test + public void aMismatchInsideAnArrayElementTypeArgumentIsMarked() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + required: List [] + ^^^^^^ + path: array element -> List type argument E + """, + """ + static void take(List[] l) {} + void test(List<@Nullable String>[] l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aNullableArrayComponentTypeIsMarkedInsideATypeArgument() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List<@Nullable String []> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + path: List type argument E -> array element + """, + """ + static void take(List l) {} + void test(List<@Nullable String[]> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aNullableArrayTypeIsMarkedInsideATypeArgument() { + assertMessage( + """ + incompatible nullability: found String @Nullable [], required String [] + found: List + ^^^^^^^^^^^^^^^^^^^ + required: List + ^^^^^^^^^ + path: List type argument E + """, + """ + static void take(List l) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java new file mode 100644 index 0000000000..673fc09bb9 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/FallbackMessageTests.java @@ -0,0 +1,63 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * Where the search for differing positions finds none, as for a difference in a lower bound, the + * message falls back to the {@code incompatible types:} form, with no carets and no {@code path:} + * line. A raw source has no type arguments to compare and draws no message at all. + */ +public class FallbackMessageTests extends MismatchMessageTestBase { + + @Test + public void aLowerBoundDifferenceFallsBackToThePlainIncompatibleTypesMessage() { + assertMessage( + """ + incompatible types: List cannot be converted to List + """, + """ + static void takeNonNullLower(List l) {} + static void takeNullableLower(List l) {} + void nullableSourceLowerBound(List l) { + takeNonNullLower(l); + } + void nonNullSourceLowerBound(List l) { + // BUG: Diagnostic matches: MESSAGE + takeNullableLower(l); + } + """); + } + + @Test + public void theFallbackMessageStatesTheSubtypeRelationBetweenTheTwoTypes() { + assertMessage( + """ + incompatible types: Sub cannot be converted to Base (Sub is a subtype of Base) + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base b) {} + void test(Sub s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aRawSourceTypeIsAcceptedWithNoMismatchToReport() { + makeHelper() + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + @SuppressWarnings("rawtypes") + void test(List raw) { + List typed = raw; + typed.hashCode(); + } + """)) + .doTest(); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java new file mode 100644 index 0000000000..4374e52696 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -0,0 +1,94 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.NullAwayTestsBase; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.List; +import java.util.function.Predicate; + +/** + * Compiles a {@code @NullMarked} class in JSpecify mode and compares the whole text of the generic + * nullability diagnostic reported at one line of it. + * + *

The comparison is exact, so an expected message also states which lines the diagnostic does + * not carry, such as a {@code did you mean} line or a {@code consider changing the required type} + * line. A failure prints the expected message beside every diagnostic the compilation reported. + */ +abstract class MismatchMessageTestBase extends NullAwayTestsBase { + + /** Returns a helper that runs NullAway in JSpecify mode over {@code @NullMarked} code only. */ + CompilationTestHelper makeHelper() { + return makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs(List.of("-XepOpt:NullAway:OnlyNullMarked=true"))); + } + + /** + * Compiles {@code members} as the body of {@code @NullMarked class Test} and expects the line + * after {@code // BUG: Diagnostic matches: MESSAGE} to report exactly {@code expected}. + * + *

The class imports {@code java.util.*} and the JSpecify annotations {@code NonNull}, {@code + * NullMarked}, {@code NullUnmarked}, and {@code Nullable}. Every other line of {@code members} + * must compile without a NullAway diagnostic. + * + * @param expected the message without the {@code [NullAway]} prefix and the link line, ending in + * a line break + * @param members the declarations of {@code class Test}, one line of which carries the marker + */ + void assertMessage(String expected, String members) { + makeHelper() + .expectErrorMessage("MESSAGE", messageIs(expected)) + .addSourceLines("Test.java", nullMarkedClass(members)) + .doTest(); + } + + /** + * Returns the source of {@code @NullMarked class Test} with the given body and the imports {@link + * #assertMessage} documents. + */ + static String nullMarkedClass(String members) { + return """ + import java.util.*; + import org.jspecify.annotations.NonNull; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.NullUnmarked; + import org.jspecify.annotations.Nullable; + @NullMarked + class Test { + %s} + """ + .formatted(members); + } + + /** + * Returns a matcher for a diagnostic whose text, without the {@code [NullAway]} prefix and the + * link line, equals {@code expected}. + */ + static Predicate messageIs(String expected) { + return new MessageIs(expected); + } + + /** + * Matches one diagnostic text exactly. Error Prone prints the matcher when no diagnostic on the + * marked line matches it, so {@link #toString} is the expected message. + */ + private record MessageIs(String expected) implements Predicate { + + private static final String PREFIX = "[NullAway] "; + private static final String LINK_LINE = " (see http://t.uber.com/nullaway )"; + + @Override + public boolean test(String message) { + if (!message.startsWith(PREFIX) || !message.endsWith(LINK_LINE)) { + return false; + } + return message + .substring(PREFIX.length(), message.length() - LINK_LINE.length()) + .equals(expected); + } + + @Override + public String toString() { + return "the message\n" + expected; + } + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java new file mode 100644 index 0000000000..194ee810dd --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java @@ -0,0 +1,146 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code note:} line says where the source takes a nullness its printed form does not show: the + * bound an unbounded or lower-bounded wildcard inherits, the type parameter a captured wildcard + * instantiates, or the declared bound of a type variable written without nullness. A source that + * prints its own nullness gets no note. + */ +public class NoteTests extends MismatchMessageTestBase { + + // A List passed to Collection.addAll, as issue #1822 reported it. The message used to print + // the + // two types and that List is a subtype of Collection, which read as a contradiction. + @Test + public void anUnboundedWildcardNamesTheTypeParameterItsBoundIsInheritedFrom() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List + ^ + required: Collection + ^^^^^^ + path: Collection type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List? + """, + """ + Collection copy(List list) { + List result = new ArrayList<>(); + // BUG: Diagnostic matches: MESSAGE + result.addAll(list); + return result; + } + Collection copyNonNull(List list) { + List result = new ArrayList<>(); + result.addAll(list); + return result; + } + static void takeNullable(Collection c) {} + void nullableTarget(List list) { + takeNullable(list); + } + """); + } + + @Test + public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundIsInheritedFrom() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List + ^^^^^^^^^^^^^^ + required: Collection + ^^^^^^ + path: Collection type argument E -> wildcard upper bound + note: the source ? super String has no explicit upper bound, so its upper bound is inherited from + type parameter E of List + """, + """ + static void take(Collection c) {} + void test(List list) { + // BUG: Diagnostic matches: MESSAGE + take(list); + } + """); + } + + @Test + public void anExplicitlyWrittenNullableBoundDrawsNoInheritedBoundNote() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + path: List type argument E -> wildcard upper bound + """, + """ + static void take(List l) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aTypeVariableWithANullableBoundIsReportedBesideAMismatchingSibling() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Pair + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Pair + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Pair type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source T has no nullness of its own, so it takes the nullness of its declared upper + bound + \s + 2. path: Pair type argument B + found: @Nullable String + required: String + """, + """ + static class Pair {} + static void take(Pair p) {} + static void test(Pair p) { + // BUG: Diagnostic matches: MESSAGE + take(p); + } + """); + } + + @Test + public void noInheritedBoundNoteWhereTheUseStatesItsOwnNullness() { + assertMessage( + """ + incompatible nullability: found @Nullable T, required Object + found: Box<@Nullable T> + ^^^^^^^^^^^ + required: Box + ^^^^^^ + path: Box type argument T -> wildcard upper bound + """, + """ + static class Box {} + static void takeNonNull(Box b) {} + static void theBoundAloneIsAccepted(Box b) { + takeNonNull(b); + } + static void test(Box<@Nullable T> b) { + // BUG: Diagnostic matches: MESSAGE + takeNonNull(b); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java new file mode 100644 index 0000000000..071bed2e08 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -0,0 +1,135 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code path:} line names the position of a difference in words: one step per type argument, + * wildcard bound, array element, or enclosing type, each type argument named by the type parameter + * its declaration declares. + */ +public class PathTests extends MismatchMessageTestBase { + + @Test + public void pathNamesTheTypeParameterTheDeclarationDeclared() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Result + ^^^^^^^^^^^^^^^^ + required: Result + ^^^^^^ + path: Result type argument Failure + """, + """ + static class Result {} + static void take(Result r) {} + void test(Result r) { + // BUG: Diagnostic matches: MESSAGE + take(r); + } + """); + } + + @Test + public void pathRepeatsTheTypeParameterNameAtEveryLevelThatSharesIt() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: List>> + ^^^^^^^^^^^^^^^^ + required: List>> + ^^^^^^ + path: List type argument E -> Collection type argument E -> List type argument E + """, + """ + static void take(List>> l) {} + void test(List>> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void pathKeepsTheEnclosingTypeApartFromTheInnerType() { + assertMessage( + """ + incompatible nullability: found @Nullable Integer, required Integer + found: Outer.Inner<@Nullable Integer> + ^^^^^^^^^^^^^^^^^ + required: Outer.Inner + ^^^^^^^ + path: Inner type argument U + """, + """ + static class Outer { + class Inner {} + } + static void take(Outer.Inner i) {} + void test(Outer.Inner<@Nullable Integer> i) { + // BUG: Diagnostic matches: MESSAGE + take(i); + } + """); + } + + @Test + public void twoMismatchesInsideOneTypeArgumentSharePathPrefix() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + required: Map> + ^^^^^^ ^^^^^^^ + 1 2 + \s + 1. path: Map type argument V -> Map type argument K + found: @Nullable String + required: String + \s + 2. path: Map type argument V -> Map type argument V + found: @Nullable Integer + required: Integer + """, + """ + static void take(Map> m) {} + void test(Map> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map<@Nullable String, List>> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + required: Map>> + ^^^^^^ ^^^^^^^ + 1 2 + \s + 1. path: Map type argument K + found: @Nullable String + required: String + \s + 2. path: Map type argument V -> List type argument E -> wildcard upper bound + -> Collection type argument E + found: @Nullable Integer + required: Integer + """, + """ + static void take(Map>> m) {} + void test( + Map<@Nullable String, List>> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java new file mode 100644 index 0000000000..430bfa9ae3 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/RequiredTypeRepairTests.java @@ -0,0 +1,170 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code consider changing the required type to:} line offers the required type with the nullness + * of the source. It appears where the diagnostic points at the declaration that writes the required + * type, a local variable declaration, and not at a call, an assignment, or a return, whose required + * type is written somewhere else. It is also withheld where printing it would drop a type-use + * annotation. + */ +public class RequiredTypeRepairTests extends MismatchMessageTestBase { + + @Test + public void suggestsTheRequiredTypeAtAVariableDeclaration() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + consider changing the required type to: + Map + """, + mapWithNullableValuesReaching( + "Map declared = m; return declared;")); + } + + @Test + public void noSuggestedRequiredTypeAtACallSite() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapWithNullableValuesReaching("take(m); return existing;")); + } + + @Test + public void noSuggestedRequiredTypeAtAnAssignmentToAnExistingVariable() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapWithNullableValuesReaching("existing = m; return existing;")); + } + + @Test + public void noSuggestedRequiredTypeAtAReturnStatement() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapWithNullableValuesReaching("return m;")); + } + + @Test + public void theSuggestedRequiredTypeIsTheDeclaredTypeNotAnInstantiatedSupertype() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: List + ^^^^^^ + path: List type argument E + consider changing the required type to: + List<@Nullable String> + """, + """ + static class Sub extends ArrayList {} + void test(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: MESSAGE + List l = s; + l.hashCode(); + } + """); + } + + @Test + public void aRequiredTypeWithNoOtherTypeUseAnnotationGetsTheRepair() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + consider changing the required type to: + Map + """, + mapDeclaredWithKeysOfType("String")); + } + + // The printer drops @Tainted from both printed types, so the message differs from the one in + // aRequiredTypeWithNoOtherTypeUseAnnotationGetsTheRepair only by the missing repair lines. + @Test + public void noSuggestedRequiredTypeWhereItsPrintedFormWouldDropAnnotations() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Map + ^^^^^^^^^^^^^^^^ + required: Map + ^^^^^^ + path: Map type argument V + """, + mapDeclaredWithKeysOfType("@Tainted String")); + } + + /** + * Returns the members of a class whose method {@code test} holds a {@code Map m} and runs {@code statements} on the marked line, where {@code Map} is required. The local {@code existing} and the method {@code take} + * hold and accept that required type, and the method {@code repairedTypeIsAccepted} shows that + * the repaired type accepts {@code m}. + */ + private static String mapWithNullableValuesReaching(String statements) { + return """ + static void take(Map m) {} + static Map existingMap() { + throw new RuntimeException(); + } + void repairedTypeIsAccepted(Map m) { + Map repaired = m; + } + Map test(Map m) { + Map existing = existingMap(); + // BUG: Diagnostic matches: MESSAGE + %s + } + """ + .formatted(statements); + } + + /** + * Returns the members of a class that declares a {@code Map} initialized from a + * {@code Map}. {@code keyType} may carry the type-use annotation + * {@code @Tainted}, which the class declares. + */ + private static String mapDeclaredWithKeysOfType(String keyType) { + return """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + void test(Map<%1$s, @Nullable String> m) { + // BUG: Diagnostic matches: MESSAGE + Map<%1$s, String> declared = m; + declared.hashCode(); + } + """ + .formatted(keyType); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java new file mode 100644 index 0000000000..67d0bde26c --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SourceRepairTests.java @@ -0,0 +1,427 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code did you mean} line offers the source type rewritten with explicit wildcard upper bounds. + * It appears only where the rewritten type repairs every difference and prints without losing a + * type-use annotation. + */ +public class SourceRepairTests extends MismatchMessageTestBase { + + @Test + public void suggestionRewritesEveryMismatchingWildcard() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter V of Map + \s + did you mean Map? + """, + """ + static void take(Map m) {} + void suggestedFormIsAccepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void suggestionLeavesAWildcardTheTargetAllowsToBeNullable() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + did you mean Map? + """, + """ + static void take(Map m) {} + void suggestedFormIsAccepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void suggestionSurvivesAMismatchInTheHarmlessDirection() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Box + ^ + required: Box + ^^^^^^ + path: Box type argument T -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter T of Box + did you mean Box? + """, + """ + static class Box {} + static void take(Box b) {} + void test(Box b) { + // BUG: Diagnostic matches: MESSAGE + take(b); + } + void suggestedFormIsAccepted(Box b) { + take(b); + } + """); + } + + @Test + public void suggestionSurvivesASuperBoundedArgumentTheTargetAlsoDeclaresSuper() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + did you mean Map? + """, + """ + static void take(Map m) {} + void suggestedFormIsAccepted(Map m) { + take(m); + } + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void unboundedWildcardSuggestionInsideAnArrayElement() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List [] + ^ + required: Collection [] + ^^^^^^ + path: array element -> Collection type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List []? + """, + """ + static void takeArray(Collection[] c) {} + void suggestedFormIsAccepted(List[] lists) { + takeArray(lists); + } + void test(List[] lists) { + // BUG: Diagnostic matches: MESSAGE + takeArray(lists); + } + """); + } + + @Test + public void unboundedWildcardSuggestionInsideANestedTypeArgument() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List> + ^ + required: Collection> + ^^^^^^ + path: Collection type argument E -> wildcard upper bound -> List type argument E + -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List>? + """, + """ + static void takeNested(Collection> c) {} + void suggestedFormIsAccepted(List> lists) { + takeNested(lists); + } + void test(List> lists) { + // BUG: Diagnostic matches: MESSAGE + takeNested(lists); + } + """); + } + + @Test + public void unboundedWildcardSuggestionInAnEnclosingTypeArgument() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Outer.Inner + ^ + required: Outer.Inner + ^^^^^^ + path: enclosing type -> Outer type argument T -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter T of Outer + did you mean Outer.Inner? + """, + """ + static class Outer { + class Inner {} + } + static void take(Outer.Inner inner) {} + void suggestedFormIsAccepted(Outer.Inner inner) { + take(inner); + } + void test(Outer.Inner inner) { + // BUG: Diagnostic matches: MESSAGE + take(inner); + } + """); + } + + @Test + public void theSourceRepairIsStillOfferedWhereTheRequiredTypeIsNotEditable() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: List + ^ + required: Collection + ^^^^^^ + path: Collection type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + did you mean List? + """, + """ + static void take(Collection c) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void noSuggestionWhenAnExplicitBoundMismatchRemains() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + """, + """ + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void noSuggestionWhenAConcreteTypeArgumentAlsoMismatches() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V + found: @Nullable String + required: String + """, + """ + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void noSuggestionWhenOneMismatchCannotBeRewritten() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map + ^ ^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + \s + 2. path: Map type argument V -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? super String has no explicit upper bound, so its upper bound is inherited + from type parameter V of Map + """, + """ + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void noSuggestionWhenBoundsDifferBelowTheTopLevel() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Holder + ^ + required: Holder> + ^^^^^^ + path: Holder type argument E -> wildcard upper bound -> List type argument E + """, + """ + static class Holder> {} + static void take(Holder> h) {} + void test(Holder h) { + // BUG: Diagnostic matches: MESSAGE + take(h); + } + """); + } + + @Test + public void noSuggestionWhenTheRewrittenTypeHoldsACapture() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map, capture of ?> + ^ + required: Map, ?> + ^^^^^^ + path: Map type argument K -> wildcard upper bound -> List type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of List + """, + """ + static Map, T> make(List l) { + throw new RuntimeException(); + } + static void take(Map, ?> m) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(make(l)); + } + """); + } + + @Test + public void aSourceWithNoOtherTypeUseAnnotationGetsTheRepair() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + did you mean Map? + """, + mapWithValuesOfType("String")); + } + + // The printer drops @Tainted from both printed types, so the message differs from the one in + // aSourceWithNoOtherTypeUseAnnotationGetsTheRepair only by the missing repair line. + @Test + public void noSourceRepairWhereItsPrintedFormWouldDropAnnotations() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Map + ^ + required: Map + ^^^^^^ + path: Map type argument K -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter K of Map + """, + mapWithValuesOfType("@Tainted String")); + } + + /** + * Returns the members of a class that passes {@code Map} where {@code Map} is required. The key wildcard is the one mismatch; {@code valueType} may carry + * the type-use annotation {@code @Tainted}, which the class declares. + */ + private static String mapWithValuesOfType(String valueType) { + return """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + static void take(Map m) {} + void test(Map m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """ + .formatted(valueType); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java new file mode 100644 index 0000000000..0447afc74d --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -0,0 +1,184 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Test; + +/** + * The first line of a generic nullability message states the one difference between the two types, + * or how many there are. Where there are several, each gets a numbered entry, five at most, and a + * line after them counts the rest. A type argument that the source states outright has to match + * exactly, and the first line says so where the source is the less nullable side. + */ +public class SummaryAndNumberingTests extends MismatchMessageTestBase { + + @Test + public void listsAtMostFiveMismatchesAndSaysHowManyMoreThereAre() { + assertMessage( + """ + incompatible nullability: 6 mismatches between source and target types + found: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + required: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: Args type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter A of Args + \s + 2. path: Args type argument B -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter B of Args + \s + 3. path: Args type argument C -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter C of Args + \s + 4. path: Args type argument D -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter D of Args + \s + 5. path: Args type argument E -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of Args + \s + and 1 more, not listed + \s + did you mean Args? + """, + wildcardsWhereNonNullBoundsAreRequired(6)); + } + + @Test + public void listsFiveMismatchesWithoutSayingThereAreMore() { + assertMessage( + """ + incompatible nullability: 5 mismatches between source and target types + found: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + required: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: Args type argument A -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter A of Args + \s + 2. path: Args type argument B -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter B of Args + \s + 3. path: Args type argument C -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter C of Args + \s + 4. path: Args type argument D -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter D of Args + \s + 5. path: Args type argument E -> wildcard upper bound + found: @Nullable Object + required: Object + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter E of Args + \s + did you mean Args? + """, + wildcardsWhereNonNullBoundsAreRequired(5)); + } + + @Test + public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { + assertMessage( + """ + incompatible nullability: 2 mismatches between source and target types + found: Map<@Nullable String, @Nullable String> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + required: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: Map type argument K + found: @Nullable String + required: String + \s + 2. path: Map type argument V + found: @Nullable String + required: String + """, + """ + static void take(Map m) {} + void test(Map<@Nullable String, @Nullable String> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void invariantTypeArgumentIsReportedWhenTheSourceIsLessNullableThanRequired() { + assertMessage( + """ + incompatible nullability: a type argument must match exactly; found String, required @Nullable String + found: List + ^^^^^^ + required: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + path: List type argument E + """, + """ + void test(List source) { + // BUG: Diagnostic matches: MESSAGE + List<@Nullable String> target = source; + target.hashCode(); + } + """); + } + + /** + * Returns the members of a class that passes {@code Args} where {@code Args} is required. Every type parameter of {@code Args} has a {@code @Nullable Object} + * bound, so each of the {@code count} wildcards is one mismatch. + */ + private static String wildcardsWhereNonNullBoundsAreRequired(int count) { + List parameters = new ArrayList<>(); + for (int i = 0; i < count; i++) { + parameters.add((char) ('A' + i) + " extends @Nullable Object"); + } + return """ + static class Args<%s> {} + static void take(Args<%s> args) {} + void test(Args<%s> args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """ + .formatted( + String.join(", ", parameters), + String.join(", ", Collections.nCopies(count, "? extends Object")), + String.join(", ", Collections.nCopies(count, "?"))); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java new file mode 100644 index 0000000000..45ee3dac13 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java @@ -0,0 +1,201 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * Where the source is compared as a supertype of another class, the {@code path:} line names the + * position in that supertype. A caret goes under the node of the type the reader wrote where the + * substitution carried that node into the view. Where the node at fault is not in the written type, + * the message prints the view on a {@code found as:} line and draws the source carets under it. + */ +public class ViewedSourceTests extends MismatchMessageTestBase { + + @Test + public void aCarriedOverNodeInsideAWildcardBoundIsMarkedOnTheWrittenSource() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub> + ^^^^^^^^^^^^^^^^ + required: Base> + ^^^^^^ + path: Base type argument T -> wildcard upper bound -> List type argument E + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base> b) {} + void test(Sub> s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aCarriedOverNodeInsideAnArrayElementIsMarkedOnTheWrittenSource() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub<@Nullable String []> + ^^^^^^^^^^^^^^^^ + required: Base + ^^^^^^ + path: Base type argument T -> array element + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base b) {} + void test(Sub<@Nullable String[]> s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aCarriedOverCaptureIsMarkedOnTheWrittenSourceAndKeepsItsProvenance() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Sub + ^^^^^^^^^^^^ + required: Base + ^^^^^^ + path: Base type argument T -> wildcard upper bound + note: the source wildcard is the type argument for type parameter T of Sub + """, + """ + static class Base {} + static class Sub extends Base {} + static void take(Base b) {} + static Sub make() { + throw new RuntimeException(); + } + void test() { + // BUG: Diagnostic matches: MESSAGE + take(make()); + } + """); + } + + @Test + public void aNodeFromTheSubclassDeclarationIsMarkedOnTheViewedSource() { + assertMessage( + """ + incompatible nullability: found @Nullable String, required String + found: Sub + found as: Base> + ^^^^^^^^^^^^^^^^ + required: Base> + ^^^^^^ + path: Base type argument T -> List type argument E + """, + """ + static class Base {} + static class Sub extends Base> {} + static void take(Base> b) {} + void test(Sub s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aWildcardFromTheSubclassDeclarationGetsANoteThatStatesItsBoundOnly() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Sub + found as: Base> + ^ + required: Base> + ^^^^^^ + path: Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound + note: the source wildcard has an implicit @Nullable Object upper bound + """, + """ + static class Base {} + static class Sub extends Base> {} + static void take(Base> b) {} + void test(Sub s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { + assertMessage( + """ + incompatible nullability: found @Nullable Object, required Object + found: Indirect + ^ + required: Base> + ^^^^^^ + path: Base type argument B -> wildcard upper bound -> List type argument E -> wildcard upper bound + note: the source ? has no explicit upper bound, so its upper bound is inherited from type + parameter X of Indirect + did you mean Indirect? + """, + """ + static class Base {} + static class Indirect extends Base> {} + static void take(Base> b) {} + void test(Indirect i) { + // BUG: Diagnostic matches: MESSAGE + take(i); + } + """); + } + + // b.Result extends a.Result, so the call reaches NullAway and both sides print as + // "Result". + @Test + public void aSubclassOfTheSameSimpleNameIsMarkedOnTheWrittenSource() { + makeHelper() + .addSourceLines( + "a/Result.java", + """ + package a; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + public class Result {} + """) + .addSourceLines( + "b/Result.java", + """ + package b; + import org.jspecify.annotations.NullMarked; + import org.jspecify.annotations.Nullable; + @NullMarked + public class Result extends a.Result {} + """) + .expectErrorMessage( + "MESSAGE", + messageIs( + """ + incompatible nullability: found @Nullable String, required String + found: Result<@Nullable String> + ^^^^^^^^^^^^^^^^ + required: Result + ^^^^^^ + path: Result type argument T + """)) + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + static void take(a.Result r) {} + void test(b.Result<@Nullable String> r) { + // BUG: Diagnostic matches: MESSAGE + take(r); + } + """)) + .doTest(); + } +} diff --git a/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java b/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java index 4659ee798e..5b753f1a6f 100644 --- a/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java +++ b/test-library-models/src/main/java/com/uber/nullaway/testlibrarymodels/TestLibraryModels.java @@ -367,6 +367,7 @@ public ImmutableSetMultimap methodTypeVariablesWithNullableU 0) .put(methodRef("com.uber.lib.unannotated.ProviderNullMarkedViaModel", "of(U)"), 0) .put(methodRef("com.uber.ModeledIntersectionBounds", "identity(T)"), 0) + .put(methodRef("com.uber.ModeledDeclaredBound", "choose(R,U)"), 1) .put( methodRef( "com.uber.lib.unannotated.NestedAnnots", "genericMethod(java.lang.Class)"),