diff --git a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java index 45936877e4..f280fe17c0 100644 --- a/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java +++ b/jdk-annotations/jdk-integration-test/src/test/java/com/uber/nullaway/jdkannotations/JDKIntegrationTest.java @@ -293,9 +293,9 @@ class Test { void testCall() { ParameterAnnotation.takesNullableArray(nonNullArray); ParameterAnnotation.takesNullableArray(nullableArray); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String ParameterAnnotation.takesNullableArray(nullableElements); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String ParameterAnnotation.takesNullableArray(nullableArrayAndElements); ParameterAnnotation.takesNullableElements(nonNullArray); ParameterAnnotation.takesNullableElements(nullableElements); @@ -339,12 +339,12 @@ void test() { } int nullableElementsLength = ReturnAnnotation.returnNullableElements().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String[] nullableElements = ReturnAnnotation.returnNullableElements(); // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableArrayAndElements()' is @Nullable int nullableArrayAndElementsLength = ReturnAnnotation.returnNullableArrayAndElements().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String @Nullable [] nullableArrayAndElements = ReturnAnnotation.returnNullableArrayAndElements(); } @@ -381,7 +381,7 @@ void test() { int nullableComponentArraysLength = ReturnAnnotation.returnNullableComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has String @Nullable [] where target requires String [] String[][] nullableComponentArrays = ReturnAnnotation.returnNullableComponentArrays2D(); // TODO: This should report a nullable dereference. NullAway currently loses the @@ -391,7 +391,7 @@ void test() { // BUG: Diagnostic contains: dereferenced expression 'ReturnAnnotation.returnNullableOuterAndComponentArrays2D()' is @Nullable int nullableOuterAndComponentArraysLength = ReturnAnnotation.returnNullableOuterAndComponentArrays2D().length; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has String @Nullable [] where target requires String [] String @Nullable [][] nullableOuterAndComponentArrays = ReturnAnnotation.returnNullableOuterAndComponentArrays2D(); } @@ -656,21 +656,21 @@ public void loadLibraryModuleMethodReturnTypeNestedAnnotation() { class Test { void testCall() { // -- Type argument nullability - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String List typeArg1 = ReturnAnnotation.nestedAnnotTypeArg(); List<@Nullable String> typeArg2 = ReturnAnnotation.nestedAnnotTypeArg(); // -- Array Element nullability - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String[] arrayElement1 = ReturnAnnotation.nestedAnnotArrayElement(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable String where target requires String String @Nullable [] arrayElement2 = ReturnAnnotation.nestedAnnotArrayElement(); @Nullable String [] arrayElement3 = ReturnAnnotation.nestedAnnotArrayElement(); // -- mixed type nullability - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable List<@Nullable Integer> where target requires List List[] mixed1 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: source has @Nullable Integer where target requires Integer @Nullable List[] mixed2 = ReturnAnnotation.nestedAnnotMixed(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable List<@Nullable Integer> where target requires List<@Nullable Integer> List<@Nullable Integer>[] mixed3 = ReturnAnnotation.nestedAnnotMixed(); @Nullable List<@Nullable Integer>[] mixed4 = ReturnAnnotation.nestedAnnotMixed(); } @@ -718,11 +718,11 @@ void testCall() { @Nullable List[] nonNullTypeArgMixed = (@Nullable List[]) new List[3]; // === test calls ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nullableMixed); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String ParameterAnnotation.nestedAnnotations(nonNullTypeArg, nullableArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nonNullArray, nullableMixed); ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullArrayMixed); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer ParameterAnnotation.nestedAnnotations(nullableTypeArg, nullableArray, nonNullTypeArgMixed); } } diff --git a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java index 50b36cbf10..9719d735f5 100755 --- a/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java +++ b/nullaway/src/main/java/com/uber/nullaway/ErrorBuilder.java @@ -219,18 +219,9 @@ private Description createErrorDescriptionImpl( @Nullable Symbol nonNullTarget, @Nullable ExpressionTree nullableExpression) { Description.Builder builder = descriptionBuilder.setMessage(errorMessage.message); - String checkName = CORE_CHECK_NAME; - if (errorMessage.messageType.equals(GET_ON_EMPTY_OPTIONAL)) { - checkName = OPTIONAL_CHECK_NAME; - } else if (errorMessage.messageType.equals(FIELD_NO_INIT) - || errorMessage.messageType.equals(METHOD_NO_INIT) - || errorMessage.messageType.equals(NONNULL_FIELD_READ_BEFORE_INIT)) { - checkName = INITIALIZATION_CHECK_NAME; - } - - // Mildly expensive state.getPath() traversal, occurs only once per potentially - // reported error. - if (hasPathSuppression(state.getPath(), checkName)) { + // Mildly expensive state.getPath() traversal. A reporter whose message costs more to build, + // as for a generic nullability mismatch, runs it once more before building the message. + if (isSuppressed(errorMessage.messageType, state)) { return Description.NO_MATCH; } @@ -315,6 +306,23 @@ private Description createErrorDescriptionImpl( ((JCTree) nullableExpression).pos().getStartPosition()); } + /** + * Returns whether an error of {@code messageType} at {@code state.getPath()} is suppressed, so + * that {@link #createErrorDescription} would drop it. A reporter whose message is costly to build + * asks first. + */ + public boolean isSuppressed(ErrorMessage.MessageTypes messageType, VisitorState state) { + String checkName = CORE_CHECK_NAME; + if (messageType.equals(GET_ON_EMPTY_OPTIONAL)) { + checkName = OPTIONAL_CHECK_NAME; + } else if (messageType.equals(FIELD_NO_INIT) + || messageType.equals(METHOD_NO_INIT) + || messageType.equals(NONNULL_FIELD_READ_BEFORE_INIT)) { + checkName = INITIALIZATION_CHECK_NAME; + } + return hasPathSuppression(state.getPath(), checkName); + } + private static boolean canHaveSuppressWarningsAnnotation(Tree tree) { return tree instanceof MethodTree || (tree instanceof ClassTree classTree && classTree.getSimpleName().length() != 0) 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..8750fa1e28 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/CheckIdenticalNullabilityVisitor.java @@ -25,6 +25,10 @@ *

Performance: a visitor caches successful wildcard containment checks for its lifetime. Reuse * the instance to share those results across checks, as long as the types and their annotations * have not changed. + * + *

A visitor given a {@link NullabilityMismatches} records every comparison it rejects there, and + * goes on comparing after a rejection rather than returning at the first, so that a diagnostic can + * name each position the check rejects. Its result is the same as without one. */ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor { private final VisitorState state; @@ -32,13 +36,17 @@ public class CheckIdenticalNullabilityVisitor extends Types.DefaultTypeVisitor successfulWildcardComparisons; /** - * Checks in progress or passed during the current outermost wildcard comparison. Every nested - * check must pass for the outermost check to pass, so a repeat can return true while the first - * check finishes. Save these results only if the outermost check succeeds; otherwise discard + * Checks in progress or finished during the current outermost wildcard comparison. Every nested + * check must pass for the outermost check to pass, so a repeat can return true: a check still in + * progress decides the outermost result when it finishes, and a finished one that failed has + * already failed it. Save these results only if the outermost check succeeds; otherwise discard * them. */ private @Nullable Set provisionalWildcardComparisons; @@ -102,10 +110,93 @@ private record ContainmentKey( CheckIdenticalNullabilityVisitor( VisitorState state, GenericsChecks genericsChecks, Config config, Handler handler) { + this(state, genericsChecks, config, handler, null); + } + + /** + * Creates a visitor that, where {@code mismatches} is not {@code null}, records in it each + * comparison it rejects. A wildcard comparison met again within the same outermost wildcard + * comparison, whether still in progress or already done, is taken to hold the second time; it is + * recorded where it was first made. + */ + CheckIdenticalNullabilityVisitor( + VisitorState state, + GenericsChecks genericsChecks, + Config config, + Handler handler, + @Nullable NullabilityMismatches mismatches) { this.state = state; this.genericsChecks = genericsChecks; this.config = config; this.handler = handler; + this.mismatches = mismatches; + } + + /** + * Returns whether {@code rhsType} may be assigned to {@code lhsType} as far as the nullability of + * their type arguments goes. The nullness of the two types themselves is not compared. An array + * is covariant in the nullness of its elements at every dimension, so an array of non-null + * references is a subtype of an array of {@code @Nullable} ones; see jspecify/jspecify#65. + * + * @param lhsType type for the lhs of the assignment + * @param rhsType type for the rhs of the assignment + */ + boolean isSubtype(Type lhsType, Type rhsType) { + if (lhsType.isRaw()) { + return true; + } + if (lhsType instanceof Type.ArrayType lhsArrayType + && rhsType instanceof Type.ArrayType rhsArrayType) { + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterArrayElement(lhsArrayType, rhsArrayType); + try { + Type lhsComponentType = lhsArrayType.getComponentType(); + Type rhsComponentType = rhsArrayType.getComponentType(); + // an array of @Nullable references is _not_ a subtype of an array of @NonNull references + if (genericsChecks.isNullableAnnotated(rhsComponentType) + && !genericsChecks.isNullableAnnotated(lhsComponentType)) { + reject(NullabilityMismatches.Relation.SUBTYPE, lhsComponentType, rhsComponentType); + return false; + } + if (lhsComponentType instanceof Type.ArrayType + && rhsComponentType instanceof Type.ArrayType) { + // covariance applies at every dimension of a multi-dimensional array. An array nested + // inside a type argument is compared by visitArrayType, since generics are not covariant + return isSubtype(lhsComponentType, rhsComponentType); + } + return haveIdenticalNestedNullability(lhsComponentType, rhsComponentType); + } finally { + restore(saved); + } + } + return haveIdenticalNestedNullability(lhsType, rhsType); + } + + /** + * Returns whether the type arguments of {@code lhsType} and {@code rhsType} have identical + * nullability, without comparing the nullness of the two types themselves. + */ + @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality check + private boolean haveIdenticalNestedNullability(Type lhsType, Type rhsType) { + if (lhsType == rhsType) { + return true; + } + return lhsType.accept(this, rhsType); + } + + /** Records a rejected comparison, where this visitor records them. */ + private void reject(NullabilityMismatches.Relation relation, Type lhsNode, Type rhsNode) { + if (mismatches != null) { + mismatches.reject(relation, lhsNode, rhsNode); + } + } + + /** Puts back the frame an {@code enter} method of {@link #mismatches} returned. */ + private void restore(NullabilityMismatches.@Nullable Frame saved) { + if (mismatches != null && saved != null) { + mismatches.restore(saved); + } } /** @@ -137,7 +228,15 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { // Bail out if resolving the upper bound did not produce a usable concrete bound. return true; } - rhsType = rhsUpperBound; + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterUpperBounds(null, lhsType, rhsType, rhsUpperBound); + try { + return visitClassType(lhsType, rhsUpperBound); + } finally { + restore(saved); + } } if (lhsType.isIntersection()) { return handleIntersectionType((Type.IntersectionClassType) lhsType, rhsType); @@ -164,33 +263,46 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { throw new RuntimeException( "Number of types arguments in " + rhsTypeAsSuper + " does not match " + lhsType); } + Type.ClassType rhsClassTypeAsSuper = (Type.ClassType) rhsTypeAsSuper; List lhsUpperBounds = lhsTypeArguments; List rhsUpperBounds = rhsTypeArguments; ParameterizationKey lhsParameterization = null; ParameterizationKey rhsParameterization = null; if (config.handleWildcardGenerics()) { lhsParameterization = new ParameterizationKey(lhsType); - rhsParameterization = new ParameterizationKey((Type.ClassType) rhsTypeAsSuper); + rhsParameterization = new ParameterizationKey(rhsClassTypeAsSuper); lhsUpperBounds = GenericsUtils.effectiveUpperBoundsForTypeArguments(lhsType, state, config, handler); rhsUpperBounds = GenericsUtils.effectiveUpperBoundsForTypeArguments( - (Type.ClassType) rhsTypeAsSuper, state, config, handler); + rhsClassTypeAsSuper, state, config, handler); } + NullabilityMismatches.Frame savedOutside = + mismatches == null ? null : mismatches.enterClassComparison(rhsType, rhsClassTypeAsSuper); + boolean contained = true; for (int i = 0; i < lhsTypeArguments.size(); i++) { Type lhsTypeArgument = lhsTypeArguments.get(i); Type lhsUpperBound = lhsUpperBounds.get(i); Type rhsTypeArgument = rhsTypeArguments.get(i); Type rhsUpperBound = rhsUpperBounds.get(i); - if (!typeArgumentContainedBy( - lhsTypeArgument, - rhsTypeArgument, - lhsUpperBound, - rhsUpperBound, - i, - lhsParameterization, - rhsParameterization)) { - return false; + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterTypeArgument(i, lhsType, rhsClassTypeAsSuper); + try { + if (!typeArgumentContainedBy( + lhsTypeArgument, + rhsTypeArgument, + lhsUpperBound, + rhsUpperBound, + i, + lhsParameterization, + rhsParameterization)) { + if (mismatches == null) { + return false; + } + contained = false; + } + } finally { + restore(saved); } } // If there is an enclosing type (for non-static inner classes), its type argument nullability @@ -198,14 +310,31 @@ public Boolean visitClassType(Type.ClassType lhsType, Type rhsType) { // object, which gets handled by the fallback visitType() method // We use rhsTypeAsSuper here rather than rhsType, since rhsType may be a captured type // variable, whose getEnclosingType() returns null. - return lhsType.getEnclosingType().accept(this, rhsTypeAsSuper.getEnclosingType()); + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterEnclosingType(lhsType, rhsClassTypeAsSuper); + try { + return lhsType.getEnclosingType().accept(this, rhsTypeAsSuper.getEnclosingType()) + && contained; + } finally { + restore(saved); + // the loop above returns early only without a recorder, so this is the one exit to undo + restore(savedOutside); + } } /** Check identical nullability for every type in the intersection */ private Boolean handleIntersectionType( Type.IntersectionClassType intersectionType, Type rhsType) { - return intersectionType.getBounds().stream() - .allMatch(type -> ((Type) type).accept(this, rhsType)); + boolean contained = true; + for (Type bound : intersectionType.getExplicitComponents()) { + if (!bound.accept(this, rhsType)) { + if (mismatches == null) { + return false; + } + contained = false; + } + } + return contained; } @Override @@ -219,7 +348,13 @@ public Boolean visitArrayType(Type.ArrayType lhsType, Type rhsType) { return true; } Type rhsComponentType = rhsArrayType.getComponentType(); - return haveIdenticalNullability(lhsComponentType, rhsComponentType); + NullabilityMismatches.Frame saved = + mismatches == null ? null : mismatches.enterArrayElement(lhsType, rhsArrayType); + try { + return haveIdenticalNullability(lhsComponentType, rhsComponentType); + } finally { + restore(saved); + } } @Override @@ -303,6 +438,7 @@ private boolean haveIdenticalNullability(Type lhsType, Type rhsType) { boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType); boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType); if (isLHSNullableAnnotated != isRHSNullableAnnotated) { + reject(NullabilityMismatches.Relation.SAME, lhsType, rhsType); return false; } return lhsType.accept(this, rhsType); @@ -346,7 +482,7 @@ private boolean wildcardContains( Set activeRhsArguments = active.get(lhsWildcard); if ((activeRhsArguments != null && activeRhsArguments.contains(rhsTypeArgument)) || !provisional.add(key)) { - // This check is in progress or has already passed. Any later failure still fails the outer + // This check is in progress or has already been made. A failure of either fails the outer // check. return true; } @@ -358,11 +494,14 @@ private boolean wildcardContains( try { boolean result = switch (lhsWildcard.kind) { - case UNBOUND, EXTENDS -> typeArgumentSubtype(lhsUpperBound, rhsUpperBound); + case UNBOUND, EXTENDS -> + upperBoundContains(lhsWildcard, lhsUpperBound, rhsTypeArgument, rhsUpperBound); case SUPER -> superWildcardContains(lhsWildcard, rhsTypeArgument); }; // A nested success may rely on an unfinished check, so cache results only after the outer - // check passes. A failure ends the traversal immediately; there is no failed result to reuse. + // check passes. A failed result is not cached: without a recorder the failure ends the + // check, and with one the provisional entry keeps the traversal from entering the same + // comparison twice within the outer check, so recording stays linear in the bound graph. if (outermost && result) { if (successfulWildcardComparisons == null) { successfulWildcardComparisons = new HashSet<>(); @@ -381,6 +520,27 @@ private boolean wildcardContains( } } + /** + * Returns whether the upper bound of the actual type argument on the right is a subtype of the + * upper bound of the formal {@code ? extends S} or {@code ?} on the left. + */ + private boolean upperBoundContains( + Type.WildcardType lhsWildcard, Type lhsUpperBound, Type rhsTypeArgument, Type rhsUpperBound) { + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterUpperBounds( + lhsWildcard, + lhsUpperBound, + GenericsUtils.asWildcard(rhsTypeArgument) == null ? null : rhsTypeArgument, + rhsUpperBound); + try { + return typeArgumentSubtype(lhsUpperBound, rhsUpperBound); + } finally { + restore(saved); + } + } + /** * 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,24 +559,40 @@ private boolean superWildcardContains(Type.WildcardType lhsWildcard, Type rhsTyp return true; } Type rhsBound = castToNonNull(rhsWildcard.getSuperBound()); - return typeArgumentSubtype(rhsBound, lhsBound); + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterLowerBounds(lhsWildcard, lhsBound, rhsTypeArgument, rhsBound); + try { + return typeArgumentSubtype(rhsBound, lhsBound); + } finally { + restore(saved); + } + } + NullabilityMismatches.Frame saved = + mismatches == null + ? null + : mismatches.enterLowerBounds(lhsWildcard, lhsBound, null, rhsTypeArgument); + try { + return typeArgumentSubtype(rhsTypeArgument, lhsBound); + } finally { + restore(saved); } - return typeArgumentSubtype(rhsTypeArgument, 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. + * the top level of the type argument, then compares the nested nullability with {@link + * #isSubtype}. */ private boolean typeArgumentSubtype(Type lhsType, Type rhsType) { boolean isLHSNullableAnnotated = genericsChecks.isNullableAnnotated(lhsType); boolean isRHSNullableAnnotated = genericsChecks.isNullableAnnotated(rhsType); if (isRHSNullableAnnotated && !isLHSNullableAnnotated) { + reject(NullabilityMismatches.Relation.SUBTYPE, lhsType, rhsType); return false; } - return genericsChecks.subtypeParameterNullability(lhsType, rhsType, state, this); + return isSubtype(lhsType, rhsType); } } 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..12f299a53a 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericTypePrettyPrintingVisitor.java @@ -2,17 +2,27 @@ import static java.util.stream.Collectors.joining; +import com.google.common.base.Preconditions; 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.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. + * A visitor that pretty prints a generic type for use in error messages, writing {@code @Nullable} + * for a type-use annotation whose simple name is {@code Nullable} and dropping every other type-use + * annotation. + * + *

Nodes named by {@link TypePath} may be marked, in which case each printed form is bracketed by + * {@link #MARK_START}, the index of every path that reaches it, {@link #MARK_TEXT}, 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} @@ -20,58 +30,161 @@ final class GenericTypePrettyPrintingVisitor extends Types.DefaultTypeVisitor { + /** + * Opens the printed form of a marked node, followed by one digit for each requested path that + * reaches the node. The marker 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'; + + /** Ends the digits of a marked node and starts its printed form. */ + static final char MARK_TEXT = '\u0003'; + + /** Ends the printed form of a marked node. */ + static final char MARK_END = '\u0002'; + private final VisitorState state; + /** How many paths a printer may mark: an index is printed as one digit. */ + static final int MAX_MARKED_PATHS = 10; + + /** + * The positions whose printed form is bracketed, in the order the caller numbers them. At most + * {@link #MAX_MARKED_PATHS}. Two entries may reach one node, which is then bracketed once with + * both indices. 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(); + + /** + * Whether the type being printed is a part of the node at {@link #currentPath}, such as a + * component of an intersection or the wildcard a capture captured, printed at that node's path. + * The node takes the one bracket for its path, so a part is not bracketed. + */ + private boolean printingPart = false; + GenericTypePrettyPrintingVisitor(VisitorState state) { + this(state, List.of()); + } + + GenericTypePrettyPrintingVisitor(VisitorState state, List<@Nullable TypePath> markedPaths) { + Preconditions.checkArgument( + markedPaths.size() <= MAX_MARKED_PATHS, + "%s marked paths; a mark index is printed as one digit, so at most %s are supported", + markedPaths.size(), + MAX_MARKED_PATHS); this.state = state; + this.markedPaths = markedPaths; + } + + /** + * Brackets {@code printed} when the node being printed sits at one of the requested paths and is + * not a part of another node printed at that path. + */ + private String mark(String printed) { + if (printingPart) { + return printed; + } + StringBuilder indices = new StringBuilder(); + for (int i = 0; i < markedPaths.size(); i++) { + TypePath markedPath = markedPaths.get(i); + if (markedPath != null && markedPath.reachesSameNodeAs(currentPath)) { + indices.append(i); + } + } + return indices.length() == 0 + ? printed + : MARK_START + indices.toString() + MARK_TEXT + printed + MARK_END; + } + + /** Prints {@code child}, which {@code step} descends to from the node being printed. */ + private String descend(TypePath.Step step, Type child) { + TypePath enclosingPath = currentPath; + boolean enclosingIsPart = printingPart; + currentPath = enclosingPath.then(step); + printingPart = false; + try { + return child.accept(this, null); + } finally { + currentPath = enclosingPath; + printingPart = enclosingIsPart; + } + } + + /** + * Prints {@code part}, a part of the node being printed that no step reaches, at that node's path + * and without a bracket of its own; a node below {@code part} is bracketed as usual. + */ + private String printPart(Type part) { + boolean enclosingIsPart = printingPart; + printingPart = true; + try { + return part.accept(this, null); + } finally { + printingPart = enclosingIsPart; + } } @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( + t.kind == BoundKind.EXTENDS + ? TypePath.Step.wildcardUpperBound() + : TypePath.Step.wildcardLowerBound(), + 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(); + int index = 0; + for (Type typeArgument : t.getTypeArguments()) { + if (index > 0) { + arguments.append(", "); + } + arguments.append(descend(TypePath.Step.typeArgument(index, null), typeArgument)); + index++; + } + sb.append(arguments); sb.append(">"); } - return sb.toString(); + return mark(sb.toString()); } /** - * Appends {@code "@Nullable "} to {@code sb} if {@code t} has a type-use {@code @Nullable} - * annotation. We ignore all other type use annotations, including {@code @NonNull} as it is the - * default + * Appends {@code "@Nullable "} to {@code sb} if {@code t} has a type-use annotation whose simple + * name is {@code Nullable}. We ignore all other type use annotations, including {@code @NonNull} + * as it is the default */ private void appendNullableAnnotationIfPresent(Type t, StringBuilder sb) { for (Attribute.TypeCompound compound : t.getAnnotationMirrors()) { - String annotName = compound.type.accept(this, null); - if ("Nullable".equals(annotName)) { + if (compound.type.tsym.getSimpleName().contentEquals("Nullable")) { sb.append("@Nullable "); break; } @@ -83,13 +196,11 @@ 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) { - return t.getBounds().stream() - .map(type -> ((Type) type).accept(this, null)) - .collect(joining(" & ")); + return t.getBounds().stream().map(type -> printPart((Type) type)).collect(joining(" & ")); } @Override @@ -97,27 +208,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. The bracket + // of that node covers the annotation printed above + sb.append(printPart(t.wildcard)); + 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)); + sb.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(); + // javac reports an unresolved type before NullAway runs, so a type printed here holds none + return mark(t.tsym.getSimpleName().toString()); // diff-coverage: ignore -- javac stops first } @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..e61009a937 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsChecks.java @@ -456,190 +456,36 @@ private void reportInvalidInstantiationError( private void reportInvalidAssignmentInstantiationError( Tree tree, Type lhsType, Type rhsType, VisitorState state) { - ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - String msg = errorMessageForIncompatibleTypesAtPseudoAssignment(lhsType, rhsType, state); - ErrorMessage errorMessage = - new ErrorMessage(ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, msg); - state.reportMatch( - errorBuilder.createErrorDescription( - 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; + reportNullabilityMismatch( + tree, ErrorMessage.MessageTypes.ASSIGN_GENERIC_NULLABLE, lhsType, rhsType, state); } /** - * 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. + * Reports at {@code tree} that {@code sourceType} cannot be assigned to {@code targetType}, with + * the message {@link NullabilityMismatchMessage} builds. A suppressed error builds no message, + * since building one reruns the check. */ - 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, + private void reportNullabilityMismatch( + Tree tree, + ErrorMessage.MessageTypes messageType, + Type targetType, + Type sourceType, 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; + ErrorBuilder errorBuilder = analysis.getErrorBuilder(); + if (errorBuilder.isSuppressed(messageType, state)) { + return; } - return String.format( - "%s wildcard is the type argument for type variable %s of %s", - assignmentRole, formalTypeVariable.tsym.getSimpleName(), owner.getSimpleName()); + String message = + new NullabilityMismatchMessage(this, config, handler, state).build(targetType, sourceType); + state.reportMatch( + errorBuilder.createErrorDescription( + new ErrorMessage(messageType, message), analysis.buildDescription(tree), state, null)); } - /** - * 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)); - state.reportMatch( - errorBuilder.createErrorDescription( - errorMessage, analysis.buildDescription(tree), state, null)); + ExpressionTree tree, Type methodType, Type returnType, VisitorState state) { + reportNullabilityMismatch( + tree, ErrorMessage.MessageTypes.RETURN_NULLABLE_GENERIC, methodType, returnType, state); } private void reportMismatchedTypeForTernaryOperator( @@ -664,15 +510,12 @@ private void reportInvalidParametersNullabilityError( Type actualParameterType, ExpressionTree paramExpression, VisitorState state) { - ErrorBuilder errorBuilder = analysis.getErrorBuilder(); - ErrorMessage errorMessage = - new ErrorMessage( - ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, - errorMessageForIncompatibleTypesAtPseudoAssignment( - formalParameterType, actualParameterType, state)); - state.reportMatch( - errorBuilder.createErrorDescription( - errorMessage, analysis.buildDescription(paramExpression), state, null)); + reportNullabilityMismatch( + paramExpression, + ErrorMessage.MessageTypes.PASS_NULLABLE_GENERIC, + formalParameterType, + actualParameterType, + state); } private void reportInvalidMethodReferenceReturnTypeError( @@ -2555,80 +2398,16 @@ public void checkTypeParameterNullnessForFunctionReturnType( } /** - * Compare two types for identical type parameter nullability, recursively checking nested generic - * types. See the JSpecify - * specification and the JLS - * subtyping rules for class and interface types. - * - * @param lhsType type for the lhs of the assignment - * @param rhsType type for the rhs of the assignment - * @param visitor visitor carrying state for the recursive comparison - */ - @SuppressWarnings({"ReferenceEquality", "TypeEquals"}) // deliberate reference equality check - private boolean identicalTypeParameterNullability( - Type lhsType, Type rhsType, CheckIdenticalNullabilityVisitor visitor) { - if (lhsType == rhsType) { - return true; - } - return lhsType.accept(visitor, rhsType); - } - - /** - * Like {@link #identicalTypeParameterNullability(Type, Type, CheckIdenticalNullabilityVisitor)}, - * but allows for covariant array subtyping at every dimension of an array type. + * Returns whether {@code rhsType} may be assigned to {@code lhsType} as far as the nullability of + * their type arguments goes; see {@link CheckIdenticalNullabilityVisitor#isSubtype}. * * @param lhsType type for the lhs of the assignment * @param rhsType type for the rhs of the assignment * @param state the visitor state */ boolean subtypeParameterNullability(Type lhsType, Type rhsType, VisitorState state) { - return subtypeParameterNullability( - lhsType, - rhsType, - state, - new CheckIdenticalNullabilityVisitor(state, this, config, handler)); - } - - /** - * Continues a subtype nullability comparison with an existing visitor so recursive wildcard - * comparisons share cycle-detection state. - * - * @param lhsType type for the lhs of the assignment - * @param rhsType type for the rhs of the assignment - * @param state the visitor state - * @param visitor visitor carrying state for the recursive comparison - */ - boolean subtypeParameterNullability( - Type lhsType, Type rhsType, VisitorState state, CheckIdenticalNullabilityVisitor visitor) { - if (lhsType.isRaw()) { - return true; - } - if (lhsType.getKind().equals(TypeKind.ARRAY) && rhsType.getKind().equals(TypeKind.ARRAY)) { - // for array types we must allow covariance, i.e., an array of @NonNull references is a - // subtype of an array of @Nullable references; see - // https://github.com/jspecify/jspecify/issues/65 - Type.ArrayType lhsArrayType = (Type.ArrayType) lhsType; - Type.ArrayType rhsArrayType = (Type.ArrayType) rhsType; - Type lhsComponentType = lhsArrayType.getComponentType(); - Type rhsComponentType = rhsArrayType.getComponentType(); - boolean isLHSNullableAnnotated = isNullableAnnotated(lhsComponentType); - boolean isRHSNullableAnnotated = isNullableAnnotated(rhsComponentType); - // an array of @Nullable references is _not_ a subtype of an array of @NonNull references - if (isRHSNullableAnnotated && !isLHSNullableAnnotated) { - return false; - } - if (lhsComponentType.getKind().equals(TypeKind.ARRAY) - && rhsComponentType.getKind().equals(TypeKind.ARRAY)) { - // covariance applies at every dimension of a multi-dimensional array, not just the - // outermost one. The ARRAY check keeps array types nested inside generic type arguments - // on the invariant path below, since generics are not covariant. - return subtypeParameterNullability(lhsComponentType, rhsComponentType, state, visitor); - } - return identicalTypeParameterNullability(lhsComponentType, rhsComponentType, visitor); - } else { - return identicalTypeParameterNullability(lhsType, rhsType, visitor); - } + return new CheckIdenticalNullabilityVisitor(state, this, config, handler) + .isSubtype(lhsType, rhsType); } /** @@ -4695,9 +4474,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); } 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..35aaadd422 100644 --- a/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java +++ b/nullaway/src/main/java/com/uber/nullaway/generics/GenericsUtils.java @@ -8,6 +8,7 @@ import com.google.errorprone.suppliers.Suppliers; import com.google.errorprone.util.ASTHelpers; import com.sun.source.tree.MemberReferenceTree; +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; @@ -137,6 +138,16 @@ static Type wildcardUpperBound( wildcardType, wildcardType.bound, Map.of(), state, config, handler); } + /** + * Returns the upper bound {@code formalTypeVariable} declares, with the nullness {@link + * #wildcardUpperBound} gives an unbounded wildcard that instantiates it. + */ + static Type declaredUpperBound( + Type.TypeVar formalTypeVariable, VisitorState state, Config config, Handler handler) { + return applyDeclarationUpperBoundNullabilityIfApplicable( + formalTypeVariable.getUpperBound(), formalTypeVariable, state, config, handler); + } + /** * Returns the effective upper bound of each type argument of {@code classType}. * @@ -377,6 +388,22 @@ private static Type applyDeclarationUpperBoundNullabilityIfApplicable( return upperBound; } + /** + * Whether {@code type} is {@code @Nullable} at its top level by an annotation NullAway added + * rather than one written in the source, as {@link + * #applyDeclarationUpperBoundNullabilityIfApplicable} adds to the upper bound of a type variable + * of unannotated code that carries no nullness annotation of its own. + */ + static boolean hasSyntheticNullable(Type type, VisitorState state) { + Symbol.TypeSymbol synthetic = GenericsChecks.getSyntheticNullableAnnotType(state).tsym; + for (Attribute.TypeCompound annotation : type.getAnnotationMirrors()) { + if (annotation.type.tsym.equals(synthetic)) { + return true; + } + } + return false; + } + private static boolean hasNullnessAnnotation(Type type, Config config) { return isAnnotatedAsNonNull(type, config) || isAnnotatedAsNullable(type, config); } @@ -446,7 +473,11 @@ static boolean declaredUpperBoundIsNullable( return isAnnotatedAsNullable(upperBound, config); } - 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..543c7ce777 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatchMessage.java @@ -0,0 +1,982 @@ +package com.uber.nullaway.generics; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Verify; +import com.google.errorprone.VisitorState; +import com.google.errorprone.util.ASTHelpers; +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.sun.tools.javac.util.ListBuffer; +import com.uber.nullaway.Config; +import com.uber.nullaway.handlers.Handler; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.function.Function; +import java.util.function.Predicate; +import org.jspecify.annotations.Nullable; + +/** + * Renders the diagnostic for a pseudo-assignment whose source type does not have the nullness its + * target type requires. + * + *

For {@code take(m)} with {@code m} a {@code Map} and {@code take} requiring {@code + * Map}, the text reads: + * + *

+ * incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object
+ *     source: Map<?, String>
+ *                 ^
+ *     target: Map<? extends Object, String>
+ *                           ^^^^^^
+ *     note: the unbounded wildcard ? in Map<?, String> has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10)
+ * 
+ * + *

The message is built from the positions the check itself rejected, which {@link + * NullabilityMismatches} records while {@link CheckIdenticalNullabilityVisitor} runs, 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. + * + *

The vocabulary

+ * + *

Each line opens with a key that means the same thing wherever it appears: {@code source} is + * the source type, {@code source supertype} the supertype of it the check compared, {@code target} + * the target type, {@code path} where in the type one difference sits, and {@code note} a fact + * about the source that its printed form does not show. Java constructs are named in the terms of + * the JLS, as {@code type argument for K of Map}, {@code upper bound of wildcard}, and {@code + * component type}, and nullness in those of JSpecify. Where there are several differences, each + * gets a numbered entry with its own {@code path}, {@code source}, and {@code target}, five at + * most, and {@code and N more differing positions, not listed} counts the rest. The keys of the + * type lines are padded to one width, so the types of one message start in the same column. + * + *

The first line

+ * + *

It stands alone, since a tool may show only that line: {@code incompatible nullability in}, + * the path of the first difference, {@code and N other differing positions} where there are more, + * and then the two nodes there. 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 non-wildcard type + * argument must have the same nullability in source and target. Where the check requires the source + * node to be a supertype of the target node, the target side reads {@code a supertype of} the + * target node. That holds at the lower bound of a {@code ? super} wildcard and at the positions + * compared inside it, as for {@code List>} against {@code List>}. Inside a second {@code ? super} the relation is swapped back: the + * check again requires the source node to be a subtype of the target node, and the target side + * names the target node itself. + * + *

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 check compares the source viewed as the target's class, which is the source's own class or a + * supertype of it, and the source caret goes into the type the reader wrote. Where the view is the + * source's own class, the caret goes at the same position. Where the view is a supertype, it goes + * only under a node the substitution carried over from the written type. Viewing an {@code + * ArrayList<@Nullable String>} as a {@code List} carries the {@code @Nullable String} over; for + * {@code class Sub extends Base>}, viewing a {@code Sub} as a {@code Base} + * rebuilds the {@code List<@Nullable String>} from the declaration of {@code Sub}, which the + * written type does not hold. Where the source is viewed as a supertype at the root and a node is + * not in the written type, that view is printed as {@code source supertype} and carries the carets + * of such nodes, while a node the written type holds keeps its caret on the {@code source} line, so + * each difference is marked on one source line. The {@code source supertype} line is printed only + * where it carries a caret. Below the root, as for an element of {@code List}, no view is + * printed, and such a node gets no source caret. Two differences below one printed node share its + * caret, numbered for each. A captured wildcard and an intersection are each one node: the caret + * marks the whole, never a part of it. Numbers follow the order of the entries, which is the order + * of their positions on the target line, so on the source lines a higher number can come before a + * lower one. Where a marked node holds another marked node, as where a supertype view puts one type + * argument of the source at two positions, each node gets its own caret run, on one row per level + * of nesting with the outermost row first, and its number in a row below its run. A number starts + * under the first column of its run, and where it would run into the number before it, it goes on + * another row below, still above the carets of the next level. + * + *

A note explains itself in the entities the message already shows. Where the source wildcard is + * marked on a printed type, the type the reader wrote or the {@code source supertype} line, the + * note prints the class the wildcard is a type argument of, names the type parameter the wildcard + * takes its upper bound from, and states that bound with the class's other type arguments + * substituted, except a wildcard, whose type parameter keeps its name. Every other type argument + * whose printed form contains {@code ?} or {@code <}, such as a wildcard or a parameterized type, + * is printed as {@code ...}, so the one {@code ?} printed is the wildcard meant and a long type is + * not repeated. + * + *

A note ends by saying that the bound is {@code @Nullable} because the class of the compared + * type parameter is unannotated where three things hold. The types differ at the bound itself, not + * below it. The compared bound is {@code @Nullable} solely through NullAway's default for + * unannotated code, which it loses where capture conversion replaces it with a type argument, as + * for {@code B extends A}. The bound of the type parameter the note names is {@code @Nullable} the + * same way. A bound with a nullness annotation of its own gets no such ending. + * + *

Where the wildcard is marked on neither printed type, as below the root of a supertype view, + * the type parameter belongs to a declaration this message never prints, and the note states the + * bound and stops. + * + *

The check takes the wildcard's bound from the type parameter at its position in the class the + * check compared there, which is the class the target type names, not the class that holds the + * wildcard on the printed type (#2206). For {@code Base} and {@code + * SubL> extends Base}, a {@code SubL} compared with {@code Base>} takes the {@code @Nullable Object} bound of {@code U}, while {@code T} + * declares {@code List}. A note would attribute the compared bound to the wildcard's own + * type parameter, so there is a note only where that type parameter's declared bound prints as the + * compared bound does, {@code @Nullable} at every node included. A subtype with the same nullness, + * such as {@code @Nullable List} for {@code @Nullable Object}, gets no note. This holds for + * a written and a captured wildcard alike. A note for a captured wildcard states the upper bound + * the check compared, and names a type parameter only where the caret's position on a printed type + * is the one the capture instantiates. In {@code Map}, from a {@code + * List} passed to {@code Map duplicate(List)}, each capture instantiates {@code E} + * of {@code List} while the caret's step is {@code K} or {@code V} of {@code Map}, so the note + * names no type parameter. Where that bound would print a capture, or a type parameter of a class + * the note does not name, there is no note. 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 for the source a {@code note} says what the reader cannot see there. + */ +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. Each listed + * mismatch is a marked path, so it is at most {@link + * GenericTypePrettyPrintingVisitor#MAX_MARKED_PATHS}. + */ + private static final int MAX_LISTED_MISMATCHES = 5; + + /** + * The key of the line that prints the source type, and of the source node in a numbered entry. + */ + private static final String SOURCE_LABEL = "source"; + + /** The key of the line that prints the supertype of the source type the check compared. */ + private static final String SOURCE_SUPERTYPE_LABEL = "source supertype"; + + /** + * The key of the line that prints the target type, and of the target node in a numbered entry. + */ + private static final String TARGET_LABEL = "target"; + + /** + * The width the keys of the type lines are padded to where no viewed source is printed: the + * length of {@link #SOURCE_LABEL} and {@link #TARGET_LABEL}, which is the same. + */ + private static final int TYPE_LABEL_WIDTH = SOURCE_LABEL.length(); + + /** + * Called each time {@link #build} starts, or {@code null} where nobody listens. A test sets it to + * count the messages built, since building one reruns the nullability check over both types. + */ + @VisibleForTesting static volatile @Nullable Runnable buildListener; + + /** + * Builds the diagnostic for an assignment, a return, or an argument the nullability check + * rejected. + * + * @param targetType the type the pseudo-assignment assigns to + * @param sourceType the type of the value assigned + */ + String build(Type targetType, Type sourceType) { + Runnable listener = buildListener; + if (listener != null) { + listener.run(); + } + NullabilityMismatches recorded = + new NullabilityMismatches(targetType, sourceType, state.getTypes(), config); + new CheckIdenticalNullabilityVisitor(state, checks, config, handler, recorded) + .isSubtype(targetType, sourceType); + List mismatches = recorded.mismatches(); + // the visitor returns false only after a reject call, and the caller saw it return false + Verify.verify( + !mismatches.isEmpty(), + "the check rejected %s for %s without recording a position", + sourceType, + targetType); + 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)); + MarkedType source = + markedTypeLines( + SOURCE_LABEL, + TYPE_LABEL_WIDTH, + sourceType, + carets(listed, NullabilityMismatches.Mismatch::sourceCaret), + numbered); + Type viewedSource = sharedView(listed); + // a node the check compared can be at no position of the type the reader wrote, and then the + // view of the source the check did compare carries its caret. The view is printed only where + // it marks a node, since that is all it is printed for + MarkedType view = + viewedSource == null + ? null + : markedTypeLines( + SOURCE_SUPERTYPE_LABEL, + SOURCE_SUPERTYPE_LABEL.length(), + viewedSource, + carets(listed, mismatch -> printedViewCaret(mismatch, viewedSource)), + numbered); + int labelWidth = TYPE_LABEL_WIDTH; + Type printedView = null; + if (view == null || view.marksPlaced() == 0) { + message.append(source.lines()); + } else { + printedView = viewedSource; + labelWidth = SOURCE_SUPERTYPE_LABEL.length(); + message.append( + markedTypeLines( + SOURCE_LABEL, + labelWidth, + sourceType, + carets(listed, NullabilityMismatches.Mismatch::sourceCaret), + numbered) + .lines()); + message.append(view.lines()); + } + message.append( + markedTypeLines( + TARGET_LABEL, + labelWidth, + targetType, + carets(listed, NullabilityMismatches.Mismatch::targetCaret), + numbered) + .lines()); + for (int i = 0; i < listed.size(); i++) { + message.append(mismatchDetail(listed.get(i), numbered ? i + 1 : 0, sourceType, printedView)); + } + if (mismatches.size() > listed.size()) { + // a numbered entry stands apart from the next, so the list stays readable, and the count + // after the list stands apart from it in the same way + message.append( + String.format( + "%s\n and %d more differing position%s, not listed", + numbered ? "\n" : "", + mismatches.size() - listed.size(), + mismatches.size() - listed.size() == 1 ? "" : "s")); + } + return message.toString(); + } + + /** + * The line a reader sees first, and the only one some tools show, so it stands alone: it names + * where the first difference sits, how many other positions differ, and the pair at the first. + */ + private String summaryLine(List mismatches) { + NullabilityMismatches.Mismatch first = mismatches.get(0); + int others = mismatches.size() - 1; + String where = + others == 0 + ? first.path().describe() + : String.format( + "%s and %d other differing position%s", + first.path().describe(), others, others == 1 ? "" : "s"); + String exactly = + mustMatchExactly(first) + ? "a non-wildcard type argument must have the same nullability in source and target; " + : ""; + return String.format( + "incompatible nullability in %s: %ssource has %s where target requires %s", + where, + exactly, + GenericsChecks.prettyTypeForError(first.sourceNode(), state), + targetRequirement(first)); + } + + /** + * Whether {@code mismatch} is a non-null type argument where the target has a {@code @Nullable} + * one, which reads as a false subtype claim, since every {@code String} is a {@code @Nullable + * String}; what fails there is that a non-wildcard type argument must have the same nullability + * in source and target. + */ + private boolean mustMatchExactly(NullabilityMismatches.Mismatch mismatch) { + return mismatch.relation() == NullabilityMismatches.Relation.SAME + && checks.isNullableAnnotated(mismatch.targetNode()) + && !checks.isNullableAnnotated(mismatch.sourceNode()); + } + + /** + * Names what the target requires of the source at {@code mismatch}: the target node, or {@code a + * supertype of} it where the check requires the source node to be a supertype of it, as at the + * lower bound of a {@code ? super} wildcard and at the positions compared inside it. + */ + private String targetRequirement(NullabilityMismatches.Mismatch mismatch) { + String target = GenericsChecks.prettyTypeForError(mismatch.targetNode(), state); + return mismatch.relation() == NullabilityMismatches.Relation.SUPERTYPE + ? "a supertype of " + target + : target; + } + + /** + * Returns the view of the source that every mismatch in {@code listed} without a caret in the + * written source was compared under, or {@code null} where one of them has no view or two have + * different ones, as the components of an intersection target do. + */ + private @Nullable Type sharedView(List listed) { + Type shared = null; + for (NullabilityMismatches.Mismatch mismatch : listed) { + if (mismatch.sourceCaret() != null) { + continue; + } + Type view = mismatch.viewedSource(); + if (view == null || (shared != null && !ASTHelpers.isSameType(shared, view, state))) { + return null; + } + shared = view; + } + return shared; + } + + /** Returns the caret {@code caret} gives each mismatch, in order. */ + private static List<@Nullable TypePath> carets( + List mismatches, + Function caret) { + List<@Nullable TypePath> paths = new ArrayList<>(); + for (NullabilityMismatches.Mismatch mismatch : mismatches) { + paths.add(caret.apply(mismatch)); + } + return paths; + } + + /** + * Prints {@code type} on a line keyed {@code label}, padded to {@code labelWidth} so that the + * types of one message start in the same column, 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, int labelWidth, Type type, List<@Nullable TypePath> paths, boolean numbered) { + String printed = type.accept(new GenericTypePrettyPrintingVisitor(state, paths), null); + StringBuilder stripped = new StringBuilder(); + // marks nest where a marked node holds another, so each open mark waits on a stack for its end + ArrayDeque open = new ArrayDeque<>(); + List spans = new ArrayList<>(); + int marks = 0; + int i = 0; + while (i < printed.length()) { + char c = printed.charAt(i); + if (c == GenericTypePrettyPrintingVisitor.MARK_START) { + // one node may carry several indices, where two mismatches share its caret + List indices = new ArrayList<>(); + i++; + while (i < printed.length() + && printed.charAt(i) != GenericTypePrettyPrintingVisitor.MARK_TEXT) { + indices.add(Integer.toString(printed.charAt(i) - '0' + 1)); + i++; + } + // the loop's own i++ steps over MARK_TEXT + open.push(new OpenMark(stripped.length(), indices)); + marks += indices.size(); + } else if (c == GenericTypePrettyPrintingVisitor.MARK_END) { + // the printer closes every mark it opens, inside the mark around it + OpenMark mark = open.pop(); + spans.add(new MarkSpan(mark.start(), stripped.length(), open.size(), mark.indices())); + } else { + stripped.append(c); + } + i++; + } + // each depth of nesting, outermost first, gets a caret row and, where numbered, number rows + // under it, so a node marked inside a marked node still gets a run of its own. A label goes on + // the first number row of its depth that leaves a space before it, so two labels never run + // together, and a depth's number rows all come before the next depth's caret row + spans.sort(Comparator.comparingInt(MarkSpan::depth).thenComparingInt(MarkSpan::start)); + List rows = new ArrayList<>(); + StringBuilder carets = new StringBuilder(); + List numberRows = new ArrayList<>(); + int depth = -1; + for (MarkSpan span : spans) { + if (span.depth() != depth) { + addDepthRows(rows, carets, numberRows, numbered); + depth = span.depth(); + carets = new StringBuilder(); + numberRows = new ArrayList<>(); + } + padTo(carets, span.start()).append("^".repeat(Math.max(span.end() - span.start(), 1))); + StringBuilder numbers = null; + for (StringBuilder row : numberRows) { + if (row.length() < span.start()) { + numbers = row; + break; + } + } + if (numbers == null) { + numbers = new StringBuilder(); + numberRows.add(numbers); + } + padTo(numbers, span.start()).append(String.join(",", span.indices())); + } + addDepthRows(rows, carets, numberRows, numbered); + String prefix = " " + padTo(new StringBuilder(label + ":"), labelWidth + 1) + " "; + String line = "\n" + prefix + stripped; + for (StringBuilder row : rows) { + line += "\n" + " ".repeat(prefix.length()) + row; + } + return new MarkedType(line, marks); + } + + /** + * Adds the rows of one depth of nesting to {@code rows}: its caret row and, where {@code + * numbered}, its number rows. Adds nothing where the depth has no caret. + */ + private static void addDepthRows( + List rows, + StringBuilder carets, + List numberRows, + boolean numbered) { + if (carets.length() == 0) { + return; + } + rows.add(carets); + if (numbered) { + rows.addAll(numberRows); + } + } + + /** A mark whose start the parse has passed and whose end it has not reached yet. */ + private record OpenMark(int start, List indices) {} + + /** + * The columns of one marked node in the printed type, from {@code start} to {@code end}, the + * number of marked nodes around it, and the one-based numbers of the mismatches it marks. + */ + private record MarkSpan(int start, int end, int depth, List indices) {} + + /** + * A printed type and the number of requested positions the printer marked in it, counting a node + * that carries several of them once for each. + */ + 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; + } + + /** + * Returns where {@code mismatch} is marked on the {@code source supertype} line that prints + * {@code printedView}, or {@code null} where it is not marked there. A mismatch with a caret in + * the written source is marked on the {@code source} line only, so each mismatch is marked on one + * source line, and its note describes the node marked there. + */ + private @Nullable TypePath printedViewCaret( + NullabilityMismatches.Mismatch mismatch, @Nullable Type printedView) { + Type view = mismatch.viewedSource(); + return mismatch.sourceCaret() == null + && printedView != null + && view != null + && ASTHelpers.isSameType(view, printedView, state) + ? mismatch.viewCaret() + : null; + } + + /** + * Returns the lines that describe one mismatch below the two types: for a numbered entry its + * position and the pair the first line names only for the first entry, and for any mismatch the + * note about the source wildcard where there is one. + * + * @param sourceType the source type the {@code source} line prints + * @param printedView the view of the source the {@code source supertype} line prints, or {@code + * null} where no such line is printed + */ + private String mismatchDetail( + NullabilityMismatches.Mismatch mismatch, + int number, + Type sourceType, + @Nullable Type printedView) { + String header = number == 0 ? " " : " " + number + ". "; + String body = " ".repeat(header.length()); + StringBuilder detail = new StringBuilder(); + if (number != 0) { + detail.append("\n\n").append(header).append("path: ").append(mismatch.path().describe()); + detail.append("\n").append(body).append(SOURCE_LABEL).append(": "); + detail.append(GenericsChecks.prettyTypeForError(mismatch.sourceNode(), state)); + detail.append("\n").append(body).append(TARGET_LABEL).append(": "); + detail.append(targetRequirement(mismatch)); + if (mustMatchExactly(mismatch)) { + detail.append( + " (a non-wildcard type argument must have the same nullability in source and target)"); + } + } + String note = boundOriginNote(mismatch, sourceType, printedView); + if (note != null) { + detail.append("\n").append(body).append("note: ").append(note); + } + return detail.toString(); + } + + /** + * Says what upper bound the source wildcard has and, where the message prints the type parameter + * it comes from, names that parameter; returns {@code null} where the printed node is not a + * wildcard, its bound is written out, the check compared no bound below it, the wildcard's own + * type parameter declares a bound other than the one the check compared (#2206), or the bound + * cannot be printed without a captured type or a type parameter of a class the note does not + * name. + * + *

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 what it is reads the two bounds as a + * contradiction. Both kinds take the same decision of where the bound comes from: the type + * parameter at the wildcard's position on the printed type that marks it, which for a capture + * must also be the one the capture instantiates. Where the class's default explains the + * difference, as {@link #boundOrigin} decides, the note says that the bound is {@code @Nullable} + * because the class is unannotated: that is 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, @Nullable Type printedView) { + // 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 printedNode = mismatch.sourcePrintedNode(); + Type.WildcardType wildcard = GenericsUtils.asWildcard(printedNode); + // the note states the bound the check compared, so it has nothing to say where the check did + // not go below the wildcard + NullabilityMismatches.HiddenBound hidden = mismatch.sourceHiddenBound(); + if (wildcard == null || hidden == null) { + return null; + } + // the step that reached the wildcard in the printed type that marks it names the type parameter + // it instantiates there; javac's own link, WildcardType.bound, names a type parameter of + // whatever supertype the wildcard was last substituted into, which an unrelated earlier + // statement can change + TypePath caret = mismatch.sourceCaret(); + Type printed = sourceType; + if (caret == null) { + caret = printedViewCaret(mismatch, printedView); + printed = printedView; + } + TypePath.Step reachingStep = caret == null ? null : caret.lastStep(); + // the class the wildcard is a type argument of, printed so the reader can find that ? + PrintedHolder holder = null; + if (printed != null + && caret != null + && reachingStep != null + && reachingStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT + && nodeAt(printed, Objects.requireNonNull(caret.parent()).steps()) + instanceof Type.ClassType holderClass) { + holder = + new PrintedHolder( + holderClass, + reachingStep.index(), + reachingStep.formal(), + boundWithStatedArgumentsSubstituted(holderClass, reachingStep.index())); + } + // compared: the type parameter whose bound the check compared, recorded where it compared it. + // own: the wildcard's own type parameter, the one at its position on the printed type that + // marks it, or, where no printed type does, the one javac links the wildcard to + Type.TypeVar compared = hidden.formal(); + Type.TypeVar own = holder != null && holder.formal() != null ? holder.formal() : wildcard.bound; + if (own != null && compared != null && !boundsAgree(own, compared)) { + // the note would attribute the compared bound to a type parameter that declares another + // (#2206) + return null; + } + BoundOrigin origin = + compared == null ? null : boundOrigin(holder, compared, wildcard, printedNode, hidden); + if (printedNode instanceof Type.CapturedType) { + return capturedWildcardNote( + wildcard, holder == null ? null : holder.type(), origin, hidden.bound()); + } + if (wildcard.kind == BoundKind.EXTENDS) { + return null; // diff-coverage: ignore -- a caret goes below a written bound + } + // ? has an upper bound, Object as the JLS writes it (4.5.1), and ? super X has none of its + // own; capture conversion gives both the bound of the type parameter (5.1.10) + boolean unbounded = wildcard.kind == BoundKind.UNBOUND; + String source = + unbounded + ? "the unbounded wildcard ?" + : "the wildcard ? super " + GenericsChecks.prettyTypeForError(wildcard.type, state); + String hasBound = + unbounded ? " has the upper bound" : " has no upper bound of its own; its upper bound is"; + if (origin == null) { + // no type parameter this message prints stands behind the bound: the wildcard sits at no + // position of a printed type, as below the root of a supertype view (#2197), or the variable + // it instantiates has no named owner. The note says what the bound is and leaves where it + // came from alone. "in the source" tells it from a wildcard of the target; below the root the + // ? itself is in a declaration this message does not print + Type upperBound = hidden.bound(); + if (printsTypeVariable(upperBound, Type.CapturedType.class::isInstance)) { + return null; + } + return String.format( + "%s in the source%s %s (JLS 5.1.10)", + source, hasBound, GenericsChecks.prettyTypeForError(upperBound, state)); + } + return String.format( + "%s in %s%s %s type parameter %s, which is %s (JLS 5.1.10)%s", + source, + withOtherTypeArgumentsElided(origin.holder().type(), origin.holder().index()), + hasBound, + unbounded ? "of" : "the bound of", + origin.named(), + GenericsChecks.prettyTypeForError(origin.holder().declaredBound(), state), + origin.unannotatedEnding()); + } + + /** + * A printed class type that holds the source wildcard as a type argument. + * + * @param type the printed class type + * @param index the position of the wildcard among the type arguments of {@code type} + * @param formal the type parameter at {@code index}, where the caret's step records it + * @param declaredBound the upper bound the type parameter at {@code index} declares, with the + * type arguments of {@code type} that are neither wildcards nor captures substituted + */ + private record PrintedHolder( + Type.ClassType type, int index, Type.@Nullable TypeVar formal, Type declaredBound) {} + + /** + * The type parameter a note names as where the source wildcard takes its upper bound from. + * + * @param holder the printed class type that holds the wildcard at that type parameter's position + * @param formal the type parameter + * @param owner the class of {@code formal} + * @param unannotatedClass the class of the type parameter whose bound the check compared, where + * NullAway's default for unannotated code explains the difference, as {@link #boundOrigin} + * decides; {@code null} otherwise + */ + private record BoundOrigin( + PrintedHolder holder, + Type.TypeVar formal, + Symbol.ClassSymbol owner, + Symbol.@Nullable ClassSymbol unannotatedClass) { + + /** Names the type parameter as {@code T of Map}. */ + String named() { + return formal.tsym.getSimpleName() + " of " + owner.getSimpleName(); + } + + /** + * Returns the ending a note takes where {@link #unannotatedClass} is set, or an empty string. + */ + String unannotatedEnding() { + return unannotatedClass == null + ? "" + : String.format( + "; the bound is @Nullable because %s is unannotated", + unannotatedClass.getSimpleName()); + } + } + + /** + * Returns the type parameter of {@code holder} that the source wildcard takes its upper bound + * from, or {@code null} where no type parameter the message prints is that one: {@code holder} is + * {@code null}, its step records no type parameter, the type parameter has no named class, or + * {@code printedNode} is a capture that does not instantiate the type parameter at the caret's + * position, because javac records no type parameter for its wildcard or records another one. + * + *

The type parameter carries the class of {@code compared} as the class to call unannotated + * where three things hold: the types differ at {@code hidden.bound()} itself, not below it; that + * bound keeps the class {@code compared} declares, so capture conversion did not replace it; and + * both it and the declared bound of the named type parameter are {@code @Nullable} solely through + * the annotation NullAway adds for unannotated code. + * + * @param compared the type parameter whose bound the check compared for the wildcard, which the + * caller has found to declare the bound the type parameter of {@code holder} declares + * @param printedNode the wildcard or capture under the caret + * @param wildcard {@code printedNode} as a wildcard, the captured one for a capture + * @param hidden the bound the check compared for the wildcard, and the steps from it to the node + * where the two types differ + */ + private @Nullable BoundOrigin boundOrigin( + @Nullable PrintedHolder holder, + Type.TypeVar compared, + Type.WildcardType wildcard, + Type printedNode, + NullabilityMismatches.HiddenBound hidden) { + if (holder == null) { + return null; + } + Type.TypeVar formal = holder.formal(); + Symbol.ClassSymbol owner = typeVariableOwner(formal); + if (formal == null || owner == null) { + return null; + } + // a capture made elsewhere can stand at this position, as where duplicate(List) substitutes + // a capture of List for K of Map. WildcardType.bound names the type parameter the wildcard + // was last substituted for, which need not be the one at this position, so it only confirms + // the caret's type parameter and never names one by itself + Type.TypeVar instantiated = wildcard.bound; + if (printedNode instanceof Type.CapturedType + && (instantiated == null || !instantiated.tsym.equals(formal.tsym))) { + return null; + } + // the ending says why the compared bound is @Nullable, so that @Nullable has to be the one + // NullAway adds for unannotated code, both on the bound the check compared and on the bound of + // the type parameter the note names. NullAway adds that default only to a bound that keeps the + // class its type parameter declares; a bound capture conversion replaced, as B extends A with + // A instantiated, takes its nullness from the type argument, written or inferred. That default + // sits on the bound itself, so it explains the mismatch only where the types differ there + Type comparedBound = hidden.bound(); + Symbol.ClassSymbol comparedClass = typeVariableOwner(compared); + boolean unannotated = + comparedClass != null + && hidden.steps().isRoot() + && GenericsUtils.fromUnannotatedMethodOrClass(compared.tsym, config, handler, state) + && comparedBound.tsym.equals(compared.getUpperBound().tsym) + && GenericsUtils.hasSyntheticNullable(comparedBound, state) + && GenericsUtils.hasSyntheticNullable( + GenericsUtils.declaredUpperBound(formal, state, config, handler), state); + return new BoundOrigin(holder, formal, owner, unannotated ? comparedClass : null); + } + + /** + * Whether {@code named}, the type parameter a note would name, declares the bound the check + * compared for {@code compared}: it is {@code compared}, or its declared upper bound prints as + * the bound {@code compared} declares, {@code @Nullable} at every node included. A subtype of + * that bound does not agree, even with the same nullness at the top level. The bound of {@code + * compared} refers to the type parameters of its class, and where the class of {@code named} + * extends that class, they are replaced by the type arguments it passes, as {@code SubSelf> extends Self} passes {@code U} for the {@code T} of {@code Self>}. + */ + private boolean boundsAgree(Type.TypeVar named, Type.TypeVar compared) { + if (named.tsym.equals(compared.tsym)) { + return true; + } + Types types = state.getTypes(); + Type namedBound = GenericsUtils.declaredUpperBound(named, state, config, handler); + Type comparedBound = GenericsUtils.declaredUpperBound(compared, state, config, handler); + if (compared.tsym.owner instanceof Symbol.ClassSymbol comparedClass + && named.tsym.owner instanceof Symbol.ClassSymbol namedClass) { + Type passed = TypeSubstitutionUtils.asSuper(types, namedClass.type, comparedClass, config); + if (passed != null) { + comparedBound = + TypeSubstitutionUtils.subst( + types, + comparedBound, + comparedClass.type.getTypeArguments(), + passed.getTypeArguments(), + config); + } + } + return GenericsChecks.prettyTypeForError(namedBound, state) + .equals(GenericsChecks.prettyTypeForError(comparedBound, state)); + } + + /** + * Returns the note for a captured wildcard: its upper bound as the check compared it, and the + * type parameter it is the type argument for where {@code origin} names one; {@code null} where + * the bound cannot be printed without a capture or a type parameter the note does not name the + * class of. + * + *

The bound of a capture refers to the captures the class holds as its type arguments, its own + * included where the type parameter's bound refers to it, as in {@code Self>}. Each capture among the type arguments of {@code holder} is printed as the type + * parameter it instantiates. + * + * @param wildcard the wildcard the capture was made from + * @param holder the printed class type that holds the capture as a type argument, or {@code null} + * where the wildcard sits at no position of a printed type + * @param origin the type parameter the capture takes its bound from, or {@code null} where the + * message prints none + * @param comparedBound the upper bound of the capture the check compared + */ + private @Nullable String capturedWildcardNote( + Type.WildcardType wildcard, + Type.@Nullable ClassType holder, + @Nullable BoundOrigin origin, + Type comparedBound) { + String captured = "capture of " + GenericsChecks.prettyTypeForError(wildcard, state); + String bound = + printedCapturedBound(comparedBound, holder, origin == null ? null : origin.owner()); + if (bound == null) { + return null; + } + return origin == null + ? String.format( + "%s is a captured wildcard whose upper bound is %s (JLS 5.1.10)", captured, bound) + : String.format( + "%s is the captured type argument for %s, whose upper bound is %s (JLS 5.1.10)%s", + captured, origin.named(), bound, origin.unannotatedEnding()); + } + + /** + * Returns {@code bound} printed with each capture among the type arguments of {@code holder} + * replaced by the type parameter it instantiates, or {@code null} where the result still prints a + * capture, or prints a type parameter of {@code holder}'s class or of a class enclosing it while + * {@code namedClass} is another class or {@code null}. + * + * @param holder the printed class type whose captures are replaced, or {@code null} for none + * @param namedClass the class the note names, or {@code null} where it names none + */ + private @Nullable String printedCapturedBound( + Type bound, Type.@Nullable ClassType holder, Symbol.@Nullable ClassSymbol namedClass) { + Type printed = bound; + if (holder != null) { + ListBuffer from = new ListBuffer<>(); + ListBuffer to = new ListBuffer<>(); + Iterator formal = holder.tsym.type.getTypeArguments().iterator(); + for (Type argument : holder.getTypeArguments()) { + Type parameter = formal.next(); + if (argument instanceof Type.CapturedType) { + from.append(argument); + to.append(parameter); + } + } + // Types.subst finds a capture by identity, ignoring its annotations, and does not descend + // into its bound + printed = + TypeSubstitutionUtils.subst(state.getTypes(), bound, from.toList(), to.toList(), config); + Symbol holderClass = holder.tsym; + if (!holderClass.equals(namedClass) + && printsTypeVariable( + printed, + t -> + !(t instanceof Type.CapturedType) + && t.tsym.owner instanceof Symbol.ClassSymbol declaring + && holderClass.isEnclosedBy(declaring))) { + return null; + } + } + if (printsTypeVariable(printed, Type.CapturedType.class::isInstance)) { + return null; + } + return GenericsChecks.prettyTypeForError(printed, state); + } + + /** + * Returns whether {@code type} prints a type variable for which {@code matches} holds, a capture + * included. A type variable prints as its name, so its bounds are not searched. + */ + private static boolean printsTypeVariable(Type type, Predicate matches) { + return type.accept( + new Types.DefaultTypeVisitor() { + @Override + public Boolean visitClassType(Type.ClassType t, @Nullable Void unused) { + if (t instanceof Type.IntersectionClassType intersection) { + return anyPrints(intersection.getComponents()); + } + return anyPrints(t.getTypeArguments()) || t.getEnclosingType().accept(this, null); + } + + private boolean anyPrints(List types) { + for (Type component : types) { + if (component.accept(this, null)) { + return true; + } + } + return false; + } + + @Override + public Boolean visitWildcardType(Type.WildcardType t, @Nullable Void unused) { + return t.type.accept(this, null); + } + + @Override + public Boolean visitArrayType(Type.ArrayType t, @Nullable Void unused) { + return t.elemtype.accept(this, null); + } + + @Override + public Boolean visitTypeVar(Type.TypeVar t, @Nullable Void unused) { + return matches.test(t); + } + + @Override + public Boolean visitCapturedType(Type.CapturedType t, @Nullable Void unused) { + return matches.test(t); + } + + @Override + public Boolean visitType(Type t, @Nullable Void unused) { + return false; + } + }, + null); + } + + /** + * Returns the upper bound the type parameter at {@code index} of {@code holder}'s class declares, + * with each type argument of {@code holder} that is not a wildcard or a capture substituted for + * its type parameter. A type parameter whose argument is a wildcard or a capture keeps its name, + * as in {@code List} for the second {@code ?} of {@code Dep} where {@code Dep>}. + */ + private Type boundWithStatedArgumentsSubstituted(Type.ClassType holder, int index) { + List formals = holder.tsym.type.getTypeArguments(); + ListBuffer from = new ListBuffer<>(); + ListBuffer to = new ListBuffer<>(); + Iterator formal = formals.iterator(); + for (Type argument : holder.getTypeArguments()) { + Type parameter = formal.next(); + if (GenericsUtils.asWildcard(argument) == null && !(argument instanceof Type.CapturedType)) { + from.append(parameter); + to.append(argument); + } + } + Type declared = + GenericsUtils.declaredUpperBound((Type.TypeVar) formals.get(index), state, config, handler); + return TypeSubstitutionUtils.subst( + state.getTypes(), declared, from.toList(), to.toList(), config); + } + + /** + * Returns the node of {@code root} that {@code steps} reach, or {@code null} where one of them + * finds no such node. + */ + private static @Nullable Type nodeAt(Type root, List steps) { + Type node = root; + for (TypePath.Step step : steps) { + node = TypePath.childAt(node, step.kind(), step.index()); + if (node == null) { + return null; // diff-coverage: ignore -- the path was recorded on this type + } + } + return node; + } + + /** + * Prints {@code holder} with its type argument at {@code index} in full, and as {@code ...} every + * other type argument whose printed form contains {@code ?} or {@code <}, such as a wildcard or a + * parameterized type, as {@code BiFunction}. So the one {@code ?} printed is the + * wildcard a note means, and a long type the {@code source} line already prints is not repeated. + */ + private String withOtherTypeArgumentsElided(Type.ClassType holder, int index) { + List printed = new ArrayList<>(); + for (Type typeArgument : holder.getTypeArguments()) { + String argument = GenericsChecks.prettyTypeForError(typeArgument, state); + printed.add( + printed.size() == index || (argument.indexOf('<') < 0 && argument.indexOf('?') < 0) + ? argument + : "..."); + } + return holder.tsym.getSimpleName() + "<" + String.join(", ", printed) + ">"; + } + + /** 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; + } +} 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..dd1190acc6 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/NullabilityMismatches.java @@ -0,0 +1,603 @@ +package com.uber.nullaway.generics; + +import static com.uber.nullaway.NullabilityUtil.castToNonNull; + +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 java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import org.jspecify.annotations.Nullable; + +/** + * Records each position where {@link CheckIdenticalNullabilityVisitor} rejects the nullness of a + * source type, so that a diagnostic names the positions the check itself rejected. + * + *

The visitor reports to this class as it compares: the step it takes into each side before it + * descends, and the two nodes of every comparison it rejects. A rejected node is not descended + * into, so the recorded positions are disjoint. Two of them can still share one caret, where both + * lie below a bound the printer does not show and the caret rises to the wildcard that hides it. + * + *

Each side is followed in two ways. The steps the check took name the position for the {@code + * path} line, in the classes it compared. The type the reader wrote is where a caret goes, and the + * check does not always compare that type: it views a source {@code ArrayList<@Nullable String>} as + * the {@code List<@Nullable String>} a target {@code List} names. So every step is also + * followed in the written type. Where the written node is what the check compared, the step is + * followed by position. Where the check views a written class as a supertype, the step is followed + * in the supertype the class declares, until that reaches one of the class's own type variables: + * the view holds the written type argument for that variable there, as {@code ArrayList} hands + * {@code List} its {@code E}, and the step goes on by position in that argument. A node the + * declaration writes itself, such as the {@code List<@Nullable String>} in {@code Sub extends + * Base>} or the {@code Sub} in {@code Sub implements Base}, sits + * nowhere in the written type and gets no caret there. + */ +final class NullabilityMismatches { + + /** What the check required of the source node at a rejected position. */ + enum Relation { + /** The same nullness as the target node, as for a type argument the source states outright. */ + SAME, + /** A subtype of the target node, as under an upper bound or for the element of an array. */ + SUBTYPE, + /** + * A supertype of the target node, as at the lower bound of a {@code ? super} wildcard and at + * the positions compared inside it. + */ + SUPERTYPE; + + /** Returns the relation with the two sides swapped. */ + Relation swapped() { + return switch (this) { + case SAME -> SAME; + case SUBTYPE -> SUPERTYPE; + case SUPERTYPE -> SUBTYPE; // diff-coverage: ignore -- only SAME and SUBTYPE are rejected + }; + } + } + + /** + * One position where the check rejected the nullness of the source. + * + * @param relation what the check required of the source node + * @param path the steps the check took into the target, which the {@code path} line names + * @param targetNode the node the target has there + * @param sourceNode the node the source has there + * @param targetCaret where the target's caret goes, or {@code null} where the target gets none + * @param sourceCaret where the source's caret goes in the source as written, or {@code null} + * where the node the check compared sits nowhere in that type + * @param viewedSource the source viewed as the class the target names at the root, where the + * check compared that view rather than the written source, or {@code null} + * @param viewCaret where the source's caret goes in {@code viewedSource}, or {@code null} + * @param sourcePrintedNode the deepest node of the compared source a printer shows, which is the + * node under {@code sourceCaret} or {@code viewCaret} where there is one. It is the wildcard + * itself where the node at fault lies below a bound the wildcard leaves implicit + * @param sourceHiddenBound the upper bound the check compared for the wildcard {@code + * sourcePrintedNode} and the steps it took into that bound, where the printer does not show + * that bound; {@code null} otherwise + */ + record Mismatch( + Relation relation, + TypePath path, + Type targetNode, + Type sourceNode, + @Nullable TypePath targetCaret, + @Nullable TypePath sourceCaret, + @Nullable Type viewedSource, + @Nullable TypePath viewCaret, + Type sourcePrintedNode, + @Nullable HiddenBound sourceHiddenBound) {} + + /** + * The upper bound the check compared below a wildcard whose bound the printer does not show, and + * the steps the comparison took from that bound to the node it stands at. + * + * @param bound the upper bound, as the check compared it + * @param steps the steps from {@code bound}, named for the classes compared + * @param formal the type parameter whose declared bound the check took for the wildcard: the one + * at the wildcard's position in the class the check compared there. {@code null} where the + * check reached the wildcard by another step than into a type argument, and so took the bound + * from the type parameter javac links the wildcard to + */ + record HiddenBound(Type bound, TypePath steps, Type.@Nullable TypeVar formal) {} + + /** + * The written type a comparison is followed in, and how far it could be followed. + * + *

{@code LOCATED}: {@code node} sits at {@code path} and the printer shows it. {@code HIDDEN}: + * the comparison went below a bound the printer does not show, and {@code node} is the wildcard + * at {@code path} that hides it, which is where a caret goes for everything below. {@code + * DECLARED}: the check views {@code node}, the written class at {@code path}, as a supertype, and + * the comparison stands at {@code declared} in the supertype that class declares; a view of a + * class inside that supertype goes on in that class's own supertype, and a comparison that goes + * on below a type variable of the written class goes on from the type argument written for it, as + * a {@code LOCATED} track. {@code LOST}: the comparison reached a node the written type does not + * hold. + * + * @param declared the node of the declared supertype where the comparison stands, for {@code + * DECLARED} only + */ + private record Track(State state, Type node, TypePath path, @Nullable Type declared) { + + enum State { + LOCATED, + HIDDEN, + DECLARED, + LOST + } + + static Track located(Type node, TypePath path) { + return new Track(State.LOCATED, node, path, null); + } + + /** Returns the track where the comparison leaves the written type at {@code track}. */ + static Track lost(Track track) { + return new Track(State.LOST, track.node(), track.path(), null); + } + + /** Returns where a caret goes for this track, or {@code null} where it gets none. */ + @Nullable TypePath caret() { + return state == State.LOCATED || state == State.HIDDEN ? path : null; + } + } + + /** + * Where the comparison stands. The visitor saves one before a descent and restores it after. + * + * @param targetSteps the steps taken into the target, named for the classes compared + * @param target the target as written + * @param source the source as written + * @param viewedSource the source viewed as the target's class at the root, or {@code null} where + * that view is the written source itself + * @param view where the comparison stands in {@code viewedSource}, or {@code null} where there is + * no such view + * @param sourceShown the deepest node of the compared source a printer would show: below a bound + * the printer does not show, the wildcard that hides it + * @param hiddenBound the bound below {@code sourceShown} the comparison went into, and the steps + * it took there, or {@code null} where it has not gone below such a bound; once set, no later + * step moves {@code sourceShown} + * @param sourceFormal the type parameter of the class the check compared that the source's last + * step reached, where that step went into a type argument; {@code null} after any other step + * @param swapped whether the visitor's left side is the source, as inside the lower bound of a + * {@code ? super} wildcard, where the check asks whether that bound is a subtype of the + * source + */ + record Frame( + TypePath targetSteps, + Track target, + Track source, + @Nullable Type viewedSource, + @Nullable Track view, + Type sourceShown, + @Nullable HiddenBound hiddenBound, + Type.@Nullable TypeVar sourceFormal, + boolean swapped) {} + + private Frame frame; + + private final List mismatches = new ArrayList<>(); + + private final Types types; + private final Config config; + + /** + * Starts a record of the comparison of {@code sourceType} against {@code targetType}, as written. + */ + NullabilityMismatches(Type targetType, Type sourceType, Types types, Config config) { + this.types = types; + this.config = config; + this.frame = + new Frame( + TypePath.root(), + Track.located(targetType, TypePath.root()), + Track.located(sourceType, TypePath.root()), + null, + null, + sourceType, + null, + null, + false); + } + + /** Returns the rejected positions, in the order the check compared them. */ + List mismatches() { + return mismatches; + } + + /** Puts back a frame an {@code enter} method returned. */ + void restore(Frame saved) { + frame = saved; + } + + /** + * Notes that the check compares the left side against {@code rhsView}, the right side {@code rhs} + * viewed as the class of the left side. At the root of the source, a view of another class is + * what a caret goes into where the written source does not hold the compared node. Returns the + * frame to restore once the comparison ends. + */ + Frame enterClassComparison(Type rhs, Type rhsView) { + Frame saved = frame; + Type viewedSource = frame.viewedSource(); + Track view = frame.view(); + if (view == null + && !frame.swapped() + && frame.targetSteps().isRoot() + && !rhsView.tsym.equals(rhs.tsym)) { + viewedSource = rhsView; + view = Track.located(rhsView, TypePath.root()); + } + Track target = frame.target(); + Track source = frame.source(); + if (frame.swapped()) { + target = viewedAs(target, rhs, rhsView); + } else { + source = viewedAs(source, rhs, rhsView); + view = view == null ? null : viewedAs(view, rhs, rhsView); + } + frame = + new Frame( + frame.targetSteps(), + target, + source, + viewedSource, + view, + frame.sourceShown(), + frame.hiddenBound(), + frame.sourceFormal(), + frame.swapped()); + return saved; + } + + /** + * Returns {@code track} for a comparison that views {@code rhs}, the node {@code track} stands + * at, as {@code rhsView}: where that is another class, the comparison goes on in the supertype of + * {@code rhsView}'s class that the written class declares. A track that stands in a declared + * supertype at a node of the class of {@code rhs} goes on in that node's own supertype, so a view + * nested inside another, as {@code ArrayList} viewed as {@code List} inside {@code Sub + * implements Base>}, still reaches the type argument the reader wrote. + */ + private Track viewedAs(Track track, Type rhs, Type rhsView) { + if (rhs.tsym.equals(rhsView.tsym) || !(rhsView.tsym instanceof Symbol.ClassSymbol viewClass)) { + return track; + } + Track argument = writtenArgumentAt(track); + if (argument != null) { + return viewedAs(argument, rhs, rhsView); + } + Type declared = + switch (track.state()) { + case LOCATED -> track.node() instanceof Type.ClassType written ? written.tsym.type : null; + case DECLARED -> track.declared(); + case HIDDEN, LOST -> null; + }; + if (declared == null || !declared.tsym.equals(rhs.tsym)) { + return track; + } + Type view = TypeSubstitutionUtils.asSuper(types, declared, viewClass, config); + return view == null + ? Track.lost(track) // diff-coverage: ignore -- a view is a supertype + : new Track(Track.State.DECLARED, track.node(), track.path(), view); + } + + /** Steps into type argument {@code index} of {@code lhs} and of {@code rhsView}. */ + Frame enterTypeArgument(int index, Type.ClassType lhs, Type.ClassType rhsView) { + return enter( + new ComparisonStep( + TypePath.Step.Kind.TYPE_ARGUMENT, index, lhs, lhs.getTypeArguments().get(index)), + new ComparisonStep( + TypePath.Step.Kind.TYPE_ARGUMENT, + index, + rhsView, + rhsView.getTypeArguments().get(index))); + } + + /** Steps into the enclosing type of {@code lhs} and of {@code rhsView}. */ + Frame enterEnclosingType(Type.ClassType lhs, Type.ClassType rhsView) { + return enter( + new ComparisonStep(TypePath.Step.Kind.ENCLOSING_TYPE, -1, lhs, lhs.getEnclosingType()), + new ComparisonStep( + TypePath.Step.Kind.ENCLOSING_TYPE, -1, rhsView, rhsView.getEnclosingType())); + } + + /** Steps into the component types of two arrays. */ + Frame enterArrayElement(Type.ArrayType lhs, Type.ArrayType rhs) { + return enter( + new ComparisonStep(TypePath.Step.Kind.ARRAY_ELEMENT, -1, lhs, lhs.elemtype), + new ComparisonStep(TypePath.Step.Kind.ARRAY_ELEMENT, -1, rhs, rhs.elemtype)); + } + + /** + * Steps into the upper bounds the check compares. A side whose wildcard is {@code null} states + * its type outright and takes no step. + */ + Frame enterUpperBounds( + @Nullable Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { + return enter( + lhsWildcard == null + ? null + : new ComparisonStep( + TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, lhsWildcard, lhsBound), + rhsWildcard == null + ? null + : new ComparisonStep( + TypePath.Step.Kind.WILDCARD_UPPER_BOUND, -1, rhsWildcard, rhsBound)); + } + + /** + * Steps into the lower bound of {@code lhsWildcard} and, where {@code rhsWildcard} is not {@code + * null}, of that wildcard too, and swaps the sides: the check goes on to ask whether {@code + * lhsBound} is a subtype of {@code rhsBound}, so its left side is then the source. + */ + Frame enterLowerBounds( + Type lhsWildcard, Type lhsBound, @Nullable Type rhsWildcard, Type rhsBound) { + Frame saved = + enter( + new ComparisonStep(TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, lhsWildcard, lhsBound), + rhsWildcard == null + ? null + : new ComparisonStep( + TypePath.Step.Kind.WILDCARD_LOWER_BOUND, -1, rhsWildcard, rhsBound)); + frame = + new Frame( + frame.targetSteps(), + frame.target(), + frame.source(), + frame.viewedSource(), + frame.view(), + frame.sourceShown(), + frame.hiddenBound(), + frame.sourceFormal(), + !frame.swapped()); + return saved; + } + + /** + * Records that the check rejected {@code rhsNode} where {@code lhsNode} stands, because the right + * side does not stand in {@code relation} to the left. + */ + void reject(Relation relation, Type lhsNode, Type rhsNode) { + boolean swapped = frame.swapped(); + Type targetNode = swapped ? rhsNode : lhsNode; + Type sourceNode = swapped ? lhsNode : rhsNode; + Track target = frame.target(); + Track source = frame.source(); + Track view = frame.view(); + mismatches.add( + new Mismatch( + swapped ? relation.swapped() : relation, + frame.targetSteps(), + targetNode, + sourceNode, + target.caret(), + source.caret(), + frame.viewedSource(), + view == null ? null : view.caret(), + frame.sourceShown(), + frame.hiddenBound())); + } + + /** + * One step of the comparison into one side. + * + * @param kind the kind of step + * @param index the type argument stepped into, or {@code -1} + * @param parent the node the comparison steps from + * @param child the node it steps to + */ + private record ComparisonStep(TypePath.Step.Kind kind, int index, Type parent, Type child) {} + + /** + * Takes one step on each side the visitor names, and returns the frame from before it. A {@code + * null} step leaves that side where it is. + */ + private Frame enter(@Nullable ComparisonStep lhs, @Nullable ComparisonStep rhs) { + Frame saved = frame; + ComparisonStep targetStep = saved.swapped() ? rhs : lhs; + ComparisonStep sourceStep = saved.swapped() ? lhs : rhs; + TypePath targetSteps = saved.targetSteps(); + Track target = saved.target(); + if (targetStep != null) { + targetSteps = targetSteps.then(comparedStep(targetStep)); + target = follow(target, targetStep); + } + Track source = saved.source(); + Track view = saved.view(); + Type sourceShown = saved.sourceShown(); + HiddenBound hiddenBound = saved.hiddenBound(); + Type.TypeVar sourceFormal = saved.sourceFormal(); + if (sourceStep != null) { + source = follow(source, sourceStep); + view = view == null ? null : follow(view, sourceStep); + if (hiddenBound != null) { + hiddenBound = + new HiddenBound( + hiddenBound.bound(), + hiddenBound.steps().then(comparedStep(sourceStep)), + hiddenBound.formal()); + } else if (isShown(sourceStep)) { + sourceShown = sourceStep.child(); + } else { + hiddenBound = new HiddenBound(sourceStep.child(), TypePath.root(), sourceFormal); + } + sourceFormal = + sourceStep.kind() == TypePath.Step.Kind.TYPE_ARGUMENT + ? comparedStep(sourceStep).formal() + : null; + } + frame = + new Frame( + targetSteps, + target, + source, + saved.viewedSource(), + view, + sourceShown, + hiddenBound, + sourceFormal, + saved.swapped()); + return saved; + } + + /** Names {@code step} for the {@code path} line, in the class the comparison stepped from. */ + private static TypePath.Step comparedStep(ComparisonStep step) { + return switch (step.kind()) { + case TYPE_ARGUMENT -> typeArgumentStep(step.parent(), step.index()); + case WILDCARD_UPPER_BOUND -> TypePath.Step.wildcardUpperBound(); + case WILDCARD_LOWER_BOUND -> TypePath.Step.wildcardLowerBound(); + case ARRAY_ELEMENT -> TypePath.Step.arrayElement(); + case ENCLOSING_TYPE -> TypePath.Step.enclosingType(); + }; + } + + /** + * Whether the printer shows the node {@code step} reaches: only the bound a wildcard states is + * printed, and the upper bound of {@code ?} and of {@code ? super X} is not. It decides both + * where a track stops ({@link #follow}) and when {@link Frame#hiddenBound} is recorded, so the + * caret and the note describe one node. + */ + private static boolean isShown(ComparisonStep step) { + if (step.kind() != TypePath.Step.Kind.WILDCARD_UPPER_BOUND) { + return true; + } + Type.WildcardType wildcard = GenericsUtils.asWildcard(step.parent()); + return wildcard != null && wildcard.kind == BoundKind.EXTENDS; + } + + /** + * Follows {@code step} of the comparison in the written type {@code track} follows, as the class + * comment describes. + */ + private static Track follow(Track track, ComparisonStep step) { + return switch (track.state()) { + case HIDDEN, LOST -> track; + case DECLARED -> followDeclared(track, step); + case LOCATED -> { + if (!isShown(step)) { + // the caret stays on the wildcard that hides the bound + yield new Track(Track.State.HIDDEN, track.node(), track.path(), null); + } + Track child = childByPosition(track, step); + yield child != null ? child : Track.lost(track); + } + }; + } + + /** + * Returns the child {@code step} reaches from the written node of {@code track}, where that node + * is of the kind the step descends from: a class type of the class the comparison stepped from + * for a type argument or an enclosing type, an array for an array element, and a wildcard for a + * bound. Returns {@code null} where it is of another kind, and for the enclosing type of a + * top-level class, which is not a class type. + */ + private static @Nullable Track childByPosition(Track track, ComparisonStep step) { + Type node = track.node(); + if (!hasClassOfParent(node, step)) { + return null; + } + Type child = TypePath.childAt(node, step.kind(), step.index()); + return child == null ? null : Track.located(child, track.path().then(comparedStep(step))); + } + + /** + * Whether {@code node} has the class of {@code step}'s parent, where {@code step} goes into a + * type argument or an enclosing type; other steps descend from a node of any class. + */ + private static boolean hasClassOfParent(Type node, ComparisonStep step) { + return switch (step.kind()) { + case TYPE_ARGUMENT, ENCLOSING_TYPE -> step.parent().tsym.equals(node.tsym); + case WILDCARD_UPPER_BOUND, WILDCARD_LOWER_BOUND, ARRAY_ELEMENT -> true; + }; + } + + /** + * Follows {@code step} in the supertype the written class of {@code track} declares. Where the + * step reaches one of the class's own type variables, written without an annotation, the view + * holds the written type argument for it, and the track is located there. A type variable written + * with an annotation, as in {@code Base>}, keeps the track in the declared + * supertype, since the annotation is not written at the argument; a step below it, or a class + * comparison at it ({@link #viewedAs}), goes on from the written type argument. + */ + private static Track followDeclared(Track track, ComparisonStep step) { + Track argument = writtenArgumentAt(track); + if (argument != null) { + return follow(argument, step); + } + Type declared = castToNonNull(track.declared()); + Type child = + hasClassOfParent(declared, step) + ? TypePath.childAt(declared, step.kind(), step.index()) + : null; // diff-coverage: ignore -- the view has this shape + if (child == null) { + return Track.lost(track); + } + Track written = + child instanceof Type.TypeVar typeVariable + && !(child instanceof Type.CapturedType) + && child.getAnnotationMirrors().isEmpty() + ? writtenArgumentFor(typeVariable, (Type.ClassType) track.node(), track.path()) + : null; + return written != null + ? written + : new Track(Track.State.DECLARED, track.node(), track.path(), child); + } + + /** + * Returns the track located at the type argument the written class gives the type variable {@code + * track} stands at in a declared supertype, or {@code null} where {@code track} stands elsewhere. + * The written argument holds every node below that type variable, so a comparison that goes on + * below it goes on from there. + */ + private static @Nullable Track writtenArgumentAt(Track track) { + return track.state() == Track.State.DECLARED + && track.declared() instanceof Type.TypeVar typeVariable + && !(typeVariable instanceof Type.CapturedType) + ? writtenArgumentFor(typeVariable, (Type.ClassType) track.node(), track.path()) + : null; + } + + /** + * Returns the track located at the type argument {@code written} gives {@code typeVariable}, + * where {@code typeVariable} is a type parameter of the class of {@code written} or of a class + * enclosing it, or {@code null} where it is neither. + */ + private static @Nullable Track writtenArgumentFor( + Type.TypeVar typeVariable, Type.ClassType written, TypePath path) { + Type declaredForm = written.tsym.type; + Type actual = written; + TypePath actualPath = path; + while (declaredForm instanceof Type.ClassType declaredClass + && actual instanceof Type.ClassType actualClass) { + Iterator arguments = actualClass.getTypeArguments().iterator(); + int index = 0; + for (Type formal : declaredClass.getTypeArguments()) { + if (!arguments.hasNext()) { + break; + } + Type argument = arguments.next(); + if (formal.tsym.equals(typeVariable.tsym)) { + return Track.located(argument, actualPath.then(typeArgumentStep(actualClass, index))); + } + index++; + } + declaredForm = declaredClass.getEnclosingType(); + actual = actualClass.getEnclosingType(); + actualPath = actualPath.then(TypePath.Step.enclosingType()); + } + return null; // diff-coverage: ignore -- a supertype names only the type variables in scope + } + + /** + * Returns the step into type argument {@code index} of {@code type}, named for the type parameter + * of its class. + */ + private static TypePath.Step typeArgumentStep(Type type, int index) { + List formals = type.tsym.type.getTypeArguments(); + Type.TypeVar formal = + index < formals.size() && formals.get(index) instanceof Type.TypeVar typeVar + ? typeVar + : null; + return TypePath.Step.typeArgument(index, formal); + } +} 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..89560ce513 --- /dev/null +++ b/nullaway/src/main/java/com/uber/nullaway/generics/TypePath.java @@ -0,0 +1,216 @@ +package com.uber.nullaway.generics; + +import com.google.common.collect.ImmutableList; +import com.sun.tools.javac.code.BoundKind; +import com.sun.tools.javac.code.Type; +import java.util.Objects; +import java.util.stream.Collectors; +import org.jspecify.annotations.Nullable; + +/** + * A position inside a type, as the sequence of descents that reaches it from the root. A position + * may lie below a bound the printer does not show, such as the upper bound of {@code ?}; a caret + * for such a position goes under the wildcard that hides the bound. + * + *

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 the kinds of descent the + * printer takes. + */ +final class TypePath { + + /** + * One descent into a type. + * + * @param kind the kind of descent + * @param index the type argument descended into, for {@link Kind#TYPE_ARGUMENT}; {@code -1} for + * every other kind + * @param formal the type parameter the type argument is for, which {@link #describe} names, or + * {@code null} where the step is of another kind or its builder has none. It does not take + * part in which node the step reaches, so compare steps with {@link #reachesSameNodeAs} + */ + record Step(Kind kind, int index, Type.@Nullable TypeVar formal) { + + enum Kind { + /** Into the type argument at {@link Step#index}. */ + TYPE_ARGUMENT, + /** + * Into the upper bound of a wildcard: the bound {@code ? extends X} states, and the one + * {@code ?} and {@code ? super X} take from their type parameter, which is not printed. + */ + WILDCARD_UPPER_BOUND, + /** Into the bound {@code ? super X} states. */ + WILDCARD_LOWER_BOUND, + /** Into the component type of an array, one dimension down (JLS 10.1). */ + ARRAY_ELEMENT, + /** Into the enclosing instance type of an inner class. */ + ENCLOSING_TYPE + } + + static Step typeArgument(int index, Type.@Nullable TypeVar formal) { + return new Step(Kind.TYPE_ARGUMENT, index, formal); + } + + static Step wildcardUpperBound() { + return new Step(Kind.WILDCARD_UPPER_BOUND, -1, null); + } + + static Step wildcardLowerBound() { + return new Step(Kind.WILDCARD_LOWER_BOUND, -1, null); + } + + static Step arrayElement() { + return new Step(Kind.ARRAY_ELEMENT, -1, null); + } + + static Step enclosingType() { + return new Step(Kind.ENCLOSING_TYPE, -1, 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 in the terms of the JLS, as {@code type argument for K of Map} + * or {@code component type}. + */ + String describe() { + return switch (kind) { + case TYPE_ARGUMENT -> { + if (formal == null) { + yield "type argument " + (index + 1); // diff-coverage: ignore -- the recorder sets it + } + yield "type argument for " + + formal.tsym.getSimpleName() + + " of " + + formal.tsym.owner.getSimpleName(); + } + case WILDCARD_UPPER_BOUND -> "upper bound of wildcard"; + case WILDCARD_LOWER_BOUND -> "lower bound of wildcard"; + case ARRAY_ELEMENT -> "component type"; + case ENCLOSING_TYPE -> "enclosing type"; + }; + } + } + + /** + * Returns the node a step of {@code kind} reaches from {@code node}, or {@code null} where {@code + * node} is not of the kind the step descends from: a class type with a type argument at {@code + * index}, a class type whose enclosing type is a class type, an array, or a wildcard or capture + * that states a bound of the step's kind. So it returns {@code null} for the upper bound of + * {@code ?} and of {@code ? super X}, which neither states. + */ + static @Nullable Type childAt(Type node, Step.Kind kind, int index) { + return switch (kind) { + case TYPE_ARGUMENT -> + node instanceof Type.ClassType classType && index < classType.getTypeArguments().size() + ? classType.getTypeArguments().get(index) + : null; // diff-coverage: ignore -- no test replays a path on a shorter type + case ENCLOSING_TYPE -> + node instanceof Type.ClassType classType + && classType.getEnclosingType() instanceof Type.ClassType enclosing + ? enclosing + : null; + case ARRAY_ELEMENT -> node instanceof Type.ArrayType array ? array.elemtype : null; + case WILDCARD_UPPER_BOUND -> statedBound(node, BoundKind.EXTENDS); + case WILDCARD_LOWER_BOUND -> statedBound(node, BoundKind.SUPER); + }; + } + + /** + * Returns the bound of {@code kind} that {@code node} states, where it is a wildcard or the + * capture of one, or {@code null}. + */ + private static @Nullable Type statedBound(Type node, BoundKind kind) { + Type.WildcardType wildcard = GenericsUtils.asWildcard(node); + return wildcard != null && wildcard.kind == kind ? wildcard.type : null; + } + + private static final TypePath ROOT = new TypePath(null, null, 0); + + /** The path this one extends by {@link #last}, or {@code null} for the root. */ + private final @Nullable TypePath parent; + + /** The last descent of this path, or {@code null} for the root. */ + private final @Nullable Step last; + + /** The number of steps from the root. */ + private final int depth; + + private TypePath(@Nullable TypePath parent, @Nullable Step last, int depth) { + this.parent = parent; + this.last = last; + this.depth = depth; + } + + /** The path of the type itself, which no step has descended from. */ + static TypePath root() { + return ROOT; + } + + /** + * Returns this path extended by {@code step}. The new path shares this one rather than copying + * it, so descending one level of a type costs the same at any depth. + */ + TypePath then(Step step) { + return new TypePath(this, step, depth + 1); + } + + /** Returns the descents from the root, in order. */ + ImmutableList steps() { + Step[] steps = new Step[depth]; + TypePath path = this; + for (int i = depth - 1; i >= 0; i--) { + steps[i] = Objects.requireNonNull(path.last); + path = Objects.requireNonNull(path.parent); + } + return ImmutableList.copyOf(steps); + } + + /** Returns the last descent of this path, or {@code null} for the root. */ + @Nullable Step lastStep() { + return last; + } + + /** Returns the path this one extends by its last step, or {@code null} for the root. */ + @Nullable TypePath parent() { + return parent; + } + + boolean isRoot() { + return depth == 0; + } + + /** Whether this path and {@code other} address the same node. */ + boolean reachesSameNodeAs(TypePath other) { + if (depth != other.depth) { + return false; + } + TypePath path = this; + TypePath otherPath = other; + while (path.last != null && otherPath.last != null) { + if (!path.last.reachesSameNodeAs(otherPath.last)) { + return false; + } + path = Objects.requireNonNull(path.parent); + otherPath = Objects.requireNonNull(otherPath.parent); + } + return true; + } + + /** + * Names this path for a reader, as {@code type argument for V of Map -> type argument for E of + * List -> upper bound of wildcard}. 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/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java b/nullaway/src/test/java/com/uber/nullaway/JSpecifyJDKModelsTest.java index ea8a80bb89..6879beecf7 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 in type argument for E of Collection -> upper bound of wildcard: source has @Nullable String where target requires 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 in component type: source has @Nullable Object where target requires 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..29d0a6774e 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 in type argument for E of List: source has @Nullable String where target requires 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 in component type: source has @Nullable String where target requires String p = q; } void matchingArrayElementTypesAreAllowed(@Nullable String[] p, @Nullable String[] q) { diff --git a/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java new file mode 100644 index 0000000000..ab23a64c58 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/generics/MismatchMessageWorkTests.java @@ -0,0 +1,100 @@ +package com.uber.nullaway.generics; + +import static com.google.common.truth.Truth.assertWithMessage; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.NullAway; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.IntStream; +import org.junit.Test; + +/** + * Building a generic nullability mismatch message reruns the check over both types, so it is + * skipped for a mismatch whose error is suppressed, and each path it follows links to the path it + * extends rather than copying it. + */ +public class MismatchMessageWorkTests { + + @Test + public void aMismatchInAnExcludedNestedClassBuildsNoMessage() { + AtomicInteger builds = new AtomicInteger(); + NullabilityMismatchMessage.buildListener = builds::incrementAndGet; + try { + CompilationTestHelper.newInstance(NullAway.class, getClass()) + .setArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:ExcludedClassAnnotations=Test.Excluded"))) + .addSourceLines( + "Test.java", + """ + import java.util.Collection; + import java.util.List; + import org.jspecify.annotations.NullMarked; + @NullMarked + class Test { + @interface Excluded {} + static void take(Collection c) {} + static List make() { + throw new RuntimeException(); + } + @Excluded + static class Inner { + void assignment() { + List l = make(); + Collection c = l; + } + void argument() { + take(make()); + } + Collection returned() { + return make(); + } + } + void reported() { + // BUG: Diagnostic contains: incompatible nullability in type argument for E of Collection + take(make()); + } + } + """) + .doTest(); + } finally { + NullabilityMismatchMessage.buildListener = null; + } + assertWithMessage( + "NullAway checks an excluded nested class and drops its errors as suppressed, so only" + + " the mismatch outside it builds a message") + .that(builds.get()) + .isEqualTo(1); + } + + // a path that copied the steps above it would cost time and memory quadratic in the depth of the + // type it walks; these are the fields a path that shares its parent needs, and no others + @Test + public void eachDescentLinksToThePathItExtends() { + TypePath path = TypePath.root(); + for (int i = 0; i < 50; i++) { + TypePath next = path.then(TypePath.Step.typeArgument(i, null)); + assertWithMessage("parent of the path at depth %s", i + 1) + .that(next.parent()) + .isSameInstanceAs(path); + path = next; + } + assertWithMessage("type argument indices of the steps, root first") + .that(path.steps().stream().map(TypePath.Step::index).toList()) + .containsExactlyElementsIn(IntStream.range(0, 50).boxed().toList()) + .inOrder(); + assertWithMessage("instance fields of TypePath") + .that( + Arrays.stream(TypePath.class.getDeclaredFields()) + .filter(field -> !Modifier.isStatic(field.getModifiers())) + .map(Field::getName) + .toList()) + .containsExactly("parent", "last", "depth"); + } +} 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..bce37ae945 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 in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String NullableTypeParam.staticField = t1; - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 in type argument for E of NullableTypeParam: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String GenericTypeArgMethods.nullableTypeParamArg(t1); - // BUG: Diagnostic contains: incompatible types: NullableTypeParam<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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..9886b935eb 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable Void where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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 in type argument for T of Foo: source has @Nullable String where target requires 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..b4789f18f5 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 in component type: source has @Nullable E where target requires E 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..b4bac8dba3 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericInheritanceTests.java @@ -245,7 +245,7 @@ static class Sub extends Outer<@Nullable S> {} > void nullableThroughBound(Y y) { // BUG: Diagnostic contains: dereferenced expression 'y.get()' is @Nullable y.get().hashCode(); - // BUG: Diagnostic contains: incompatible types: Y cannot be converted to Outer + // BUG: Diagnostic contains: incompatible nullability in type argument for O of Outer: source has @Nullable String where target requires String Outer nonNull = y; Outer<@Nullable String> nullable = y; y.new Inner(null); @@ -272,7 +272,7 @@ > void nonNullThroughBoundOfBound(Z z) { void nullableThroughCapturedWildcard(List> l) { // BUG: Diagnostic contains: dereferenced expression 'l.get(0).get()' is @Nullable l.get(0).get().hashCode(); - // BUG: Diagnostic contains: incompatible types: capture of ? extends Sub cannot be converted to Outer + // BUG: Diagnostic contains: incompatible nullability in type argument for O of Outer: source has @Nullable String where target requires String Outer nonNull = l.get(0); Outer<@Nullable String> nullable = l.get(0); } @@ -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 in type argument for T of MyFuture -> type argument for E of List: source has @Nullable V where target requires 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 in type argument for E of List: source has @Nullable String where target requires 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 in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for E of List: source has @Nullable O where target requires 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..a1f5fb0663 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 in type argument for E of List: source has @Nullable String where target requires 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 in type argument for E of List: source has @Nullable String where target requires 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..1b3a1bb3ac 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 in type argument for T of Box: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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..cad8f0cf7f 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/GenericMethodTests.java @@ -559,9 +559,9 @@ interface B { X b(); } id1(value).a().length(); A<@Nullable String> nullableA = id1(value); B nonNullB = id1(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id1(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id1(value); } @@ -572,9 +572,9 @@ interface B { X b(); } id2(value).a().length(); A<@Nullable String> nullableA = id2(value); B nonNullB = id2(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id2(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id2(value); } @@ -585,9 +585,9 @@ interface B { X b(); } id3(value).a().length(); A<@Nullable String> nullableA = id3(value); B nonNullB = id3(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id3(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id3(value); } @@ -598,9 +598,9 @@ interface B { X b(); } id4(value).a().length(); A<@Nullable String> nullableA = id4(value); B nonNullB = id4(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A: source has @Nullable String where target requires String A nonNullA = id4(value); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> nullableB = id4(value); } } @@ -634,9 +634,9 @@ static class Box1> & B>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -652,9 +652,9 @@ static class Box2> & A>> { box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -670,9 +670,9 @@ static class Box3> & B>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } @@ -688,9 +688,9 @@ static class Box4> & A>> box.get().a().get(0).length(); A> nullableA = box.get(); B> nonNullB = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of A -> type argument for E of List: source has @Nullable String where target requires String A> nonNullA = box.get(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for X of B -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B> nullableB = box.get(); } } @@ -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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for V of Foo -> type argument for E of ArrayList: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Foo> fooNonNull_2 = f.nonNullTest(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for K of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @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 in type argument for T of Foo -> component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in component type -> type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of Bar -> type argument for T of Bar: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String 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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in component type: source has @Nullable String where target requires 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 in component type: source has @Nullable String where target requires String stringField = f(arr2, "hi"); } } @@ -2237,6 +2237,18 @@ static void testParam() { @Test public void capturedTypeAtNullUnmarkedBoundary() { makeHelper() + .expectErrorMessage( + "CAPTURE_FROM_UNMARKED", + message -> + message.contains( + """ + incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Foo + ^^^^^^^^^^^^ + target: Foo + ^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """)) .addSourceLines( "Test.java", """ @@ -2262,7 +2274,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 +2285,18 @@ static Foo getReturnType() { @Test public void capturedTypeGetsDirectNullableAnnotationFromTypeVariableUse() { makeHelper() + .expectErrorMessage( + "CAPTURE_FROM_MARKED", + message -> + message.contains( + """ + incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Foo<@Nullable capture of ?> + ^^^^^^^^^^^^^^^^^^^^^^ + target: Foo + ^^^^^^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """)) .addSourceLines( "Test.java", """ @@ -2290,7 +2314,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 +2450,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 in type argument for T of Box: source has @Nullable String where target requires String swapBoxes(box1, box2); } void TestNegative(Box<@Nullable String> box1, Box<@Nullable String> box2) { @@ -2521,7 +2545,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 in type argument for T of Supplier: a non-wildcard type argument must have the same nullability in source and target; source has OuterT where target requires @Nullable OuterT acceptTwoSup(sup, sup2); } } @@ -2653,7 +2677,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 in type argument for T of Foo: source has @Nullable String where target requires String static Foo WRONG = Foo.of(new Foo<@Nullable String>()).or(new Foo<@Nullable String>()); } @@ -2709,7 +2733,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 in type argument for T of Box: a non-wildcard type argument must have the same nullability in source and target; source has CompletableFuture where target requires @Nullable CompletableFuture accept(box); } } @@ -3322,9 +3346,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 in enclosing type -> type argument for O of Outer: source has @Nullable String where target requires 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 in enclosing type -> type argument for O of Outer: source has @Nullable String where target requires 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..86f2e93e76 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 in type argument for E of List: source has @Nullable Void where target requires 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 in type argument for E of List: source has @Nullable Void where target requires 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..f475924f18 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 in type argument for E of NonNullTypeParam: source has @Nullable String where target requires 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 in type argument for E of Holder: source has @Nullable String where target requires 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 in enclosing type -> type argument for P of Wrapper: source has @Nullable String where target requires String 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 in enclosing type -> type argument for P of Wrapper: source has @Nullable String where target requires 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 in enclosing type -> type argument for P of Wrapper: source has @Nullable String where target requires String 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 in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @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 in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer removeCallback(this); - // BUG: Diagnostic contains: incompatible types: Callback cannot be converted to Callback<@Nullable Integer> + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Callback: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @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 in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 in type argument for E of NullableTypeParam: source has @Nullable String where target requires 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 in type argument for E1 of SampleClassMultipleArguments -> type argument for E of SampleClass -> type argument for E of SampleClass: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for R of Fn: source has @Nullable String where target requires 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 in type argument for P of Fn2: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for P1 of SuperClassC: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for P of D: source has @Nullable String where target requires String D f1 = new B<@Nullable String>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for P of D: source has @Nullable String where target requires 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 in type argument for A of Super and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String 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 in type argument for P of D -> type argument for P of C: source has @Nullable String where target requires String D> f1 = new B>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for P of A: source has @Nullable String where target requires String A, String> f2 = new A, @Nullable String>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for P of D: source has Test.@Nullable C where target requires 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 in type argument for T1 of A: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of A: source has @Nullable String where target requires String return new A<@Nullable String>(); } static A<@Nullable String> testPositive2() { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of A: source has @Nullable String where target requires 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 in type argument for T of A: source has @Nullable String where target requires 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 in type argument for T of A -> type argument for T of A: source has @Nullable String where target requires String A a = sampleMethod1(a1, a2); } static void testPositive2(A> a1, A a2) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String A a = sampleMethod2(a1, a2); } static void testPositive3(A a1) { - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of A: source has @Nullable String where target requires String A<@Nullable String> b = sampleMethodWithVarArgs(a1); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: source has @Nullable String where target requires 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 in component type -> type argument for T of A: source has @Nullable String where target requires 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 in type argument for T of A -> component type -> type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String A[]> var1 = new A[]>(); - // BUG: Diagnostic contains: incompatible types: + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A -> component type -> type argument for T of A: source has @Nullable String where target requires 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 in type argument for T of A -> component type -> type argument for T of A: source has @Nullable String where target requires 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 in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has int [] where target requires 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 in enclosing type -> type argument for X of A: source has @Nullable String where target requires 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 in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires 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 in enclosing type -> type argument for T of Outer: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires 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 in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String Outer.Inner result = input; } } @@ -3033,7 +3033,7 @@ static class B implements A<@Nullable String>, Serializable {} static class C implements A, Serializable {} static void test1(Object o) { var x = (A & Serializable) o; - // BUG: Diagnostic contains: incompatible types: B cannot be converted to A & Serializable + // BUG: Diagnostic contains: source supertype: A<@Nullable String> x = new B(); // ok x = new C(); @@ -3041,7 +3041,7 @@ static void test1(Object o) { static void test2(Object o) { var x = (A<@Nullable String> & Serializable) o; x = new B(); - // BUG: Diagnostic contains: incompatible types: C cannot be converted to A<@Nullable String> & Serializable + // BUG: Diagnostic contains: incompatible nullability in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String x = new C(); } } @@ -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 in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has V where target requires @Nullable V 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 in component type -> type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has V where target requires @Nullable V 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 in type argument for T of Function and 1 other differing position: source has @Nullable String where target requires String this.<@Nullable String>foo(f); } void testPositiveArray(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Function and 1 other differing position: source has String @Nullable [] where target requires String [] 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 in type argument for T of Function and 1 other differing position: source has @Nullable V where target requires V foo(f); } void testPositive2(Function f) { - // BUG: Diagnostic contains: incompatible types: Function cannot be converted to + // BUG: Diagnostic contains: incompatible nullability in type argument for R of Function: a non-wildcard type argument must have the same nullability in source and target; source has V where target requires @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 in type argument for T of Function: source has @Nullable V where target requires 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 in type argument for T of Function and 1 other differing position: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of Inner: source has @Nullable Object where target requires 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 in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of A: source has @Nullable Object where target requires 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 in type argument for T of A: a non-wildcard type argument must have the same nullability in source and target; source has Object where target requires @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 in type argument for T of MaybeNull: source has @Nullable String where target requires 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 in type argument for T of MaybeNull: source has @Nullable String where target requires 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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @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 in type argument for T of Foo: source has @Nullable String where target requires 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..40a8f0f806 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 in type argument for T of Result -> upper bound of wildcard: source has @Nullable A & @Nullable B where target requires A return source.result(); } Result rejectsAllNullableLastComponent(AllNullable source) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Result -> upper bound of wildcard: source has @Nullable A & @Nullable B where target requires B return source.result(); } } diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java index 3bf603888b..2e6d0a53e2 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/IntersectionRestorationTests.java @@ -36,7 +36,7 @@ void acceptsMatchingNullableComponent(Factory factory) { } void rejectsNonNullMatchingComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for E of A: source has @Nullable String where target requires String A result = factory.fromA().get(); } @@ -45,7 +45,7 @@ void acceptsOtherNonNullComponent(Factory factory) { } void rejectsWideningOtherInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromA().get(); } @@ -54,7 +54,7 @@ void acceptsMatchingNonNullComponent(Factory factory) { } void rejectsWideningMatchingInvariantComponent(Factory factory) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String B<@Nullable String> result = factory.fromB().get(); } } 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..39a2b67d5f 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 in component type: source has @Nullable Test where target requires 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 in component type: source has @Nullable Test where target requires 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 in component type: source has @Nullable Test where target requires 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 in component type: source has @Nullable Integer where target requires 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 in component type: source has @Nullable Integer where target requires 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 in component type -> component type: source has @Nullable Integer where target requires 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 in component type: source has @Nullable Integer where target requires 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 in component type -> component type: source has @Nullable Integer where target requires Integer 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 in component type -> component type: source has @Nullable Integer where target requires Integer Integer[][] y1 = nullableElems2D; - // BUG: Diagnostic contains: incompatible types: @Nullable Integer [] [] [] cannot be converted to Integer [] [] [] + // BUG: Diagnostic contains: incompatible nullability in component type -> component type -> component type: source has @Nullable Integer where target requires Integer Integer[][][] y2 = nullableElems3D; - // BUG: Diagnostic contains: incompatible types: Integer @Nullable [] [] cannot be converted to Integer [] [] + // BUG: Diagnostic contains: incompatible nullability in component type: source has Integer @Nullable [] where target requires 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 in type argument for E of List -> component type: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @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 in component type: source has @Nullable Foo where target requires 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 in component type: source has @Nullable Foo where target requires 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 in component type: source has @Nullable Foo where target requires Foo takeFoosVarargs(p); - // BUG: Diagnostic contains: incompatible types: @Nullable Foo [] + // BUG: Diagnostic contains: incompatible nullability in component type: source has @Nullable Foo where target requires 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 in type argument for T of CompletableFuture -> upper bound of wildcard: source has @Nullable String where target requires 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 in type argument for E of List: source has @Nullable String where target requires String List l = local[0]; } void assignMatchingTypeArgumentElementOfLocalArray() { 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..06923dcd8a 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 in type argument for E of List: source has @Nullable Object where target requires Object PolyNullMethods.first(nullable, nullable); } } 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..1a95b64afd 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 in type argument for Y of NullableSibling: source has @Nullable String where target requires 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..9d97792e9f 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 in type argument for E of List: source has @Nullable String where target requires 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 in type argument for E of List: source has @Nullable String where target requires 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..7de2949103 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 in type argument for T of Box: source has @Nullable String where target requires 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..d4ac629d54 100644 --- a/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/WildcardTests.java @@ -319,7 +319,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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String String s = nonnullWildcard(f); // legal String s2 = nonnullWildcard(f2); @@ -348,7 +348,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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -379,7 +379,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 in type argument for T of Foo -> upper bound of wildcard -> type argument for T of Bar: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -411,7 +411,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 in type argument for T of Foo -> upper bound of wildcard -> type argument for T of Bar -> type argument for T of Baz: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -443,7 +443,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 in type argument for T of Foo -> upper bound of wildcard: source has Test.@Nullable Bar> where target requires Test.Bar> String s = nonnullWildcard(f); s.hashCode(); } @@ -473,7 +473,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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String String s = nonnullWildcard(f); s.hashCode(); } @@ -496,22 +496,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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires 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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires 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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires 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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable String where target requires String Foo bad2 = f2; } } @@ -538,10 +538,10 @@ void testLocals( Foo nonnullSuperLocal = nullableObjectFoo; Foo nullableSuperLocal = nullableObjectFoo; Foo nullableSuperLocal2 = nullableStringFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> lower bound of wildcard: source has Object where target requires a supertype of @Nullable String Foo nullableSuperLocal3 = objectFoo; Foo nonnullSuperFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String Foo nullableSuperFromNonnullSuper = nonnullSuperFoo; } } @@ -566,11 +566,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 in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object Foo badFromNonnullSuper = nonnullSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object Foo badFromNullableSuper = nullableSuperFoo; - // BUG: Diagnostic contains: incompatible types: Test.Foo cannot be converted to Test.Foo + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Foo -> upper bound of wildcard: source has @Nullable Object where target requires Object Foo badFromUnbounded = unboundedFoo; } } @@ -595,7 +595,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 in type argument for T of NonNullBoundFoo -> upper bound of wildcard: source has @Nullable Object where target requires Object NonNullBoundFoo fromNullableExtends = nullableExtendsObjectWithNonnullBoundFoo; NonNullBoundFoo fromSuper = nonnullSuperStringFoo; } @@ -621,13 +621,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 in type argument for U of Pair -> upper bound of wildcard: source has @Nullable String where target requires 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 in type argument for U of Pair -> upper bound of wildcard: source has @Nullable Object where target requires Object Pair invalid = pair; } @@ -636,7 +636,7 @@ static class UnmarkedPair {} static void capturedFirstArgumentFromUnmarkedCode(UnmarkedPair pair) { UnmarkedPair target = pair; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for U of UnmarkedPair -> upper bound of wildcard: source has @Nullable Object where target requires Object UnmarkedPair invalid = pair; } } @@ -754,7 +754,7 @@ T get() { } } static void test(Holder> holder) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box: source has @Nullable String where target requires String Box box = holder.get(); } } @@ -880,7 +880,7 @@ static void nullable(NullableHolder holder) { // BUG: Diagnostic contains: dereferenced expression 'box.get()' is @Nullable box.get().length(); Box<@Nullable String> compatible = holder.nonNullValue(); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for E of Box: source has @Nullable String where target requires String Box incompatible = holder.nonNullValue(); // BUG: Diagnostic contains: dereferenced expression 'holder.value()' is @Nullable holder.value().hashCode(); @@ -915,18 +915,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable String where target requires String return local.wildcardUpperTypeVariable(); } @@ -960,18 +960,18 @@ Nested self() { } Nested testDirect(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable Object where target requires Object return receiver.wildcardUpperTypeVariable(); } Nested testWithSelf(Nested receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable Object where target requires Object return receiver.self().wildcardUpperTypeVariable(); } Nested testWithVar(Nested receiver) { var local = receiver; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Nested -> upper bound of wildcard: source has @Nullable Object where target requires Object return local.wildcardUpperTypeVariable(); } @@ -1038,7 +1038,7 @@ interface NullableI2< } NullableI1 incompatible(NullableI2 i2) { var i2var = i2; - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for X of NullableI1: source has @Nullable Object where target requires Object return i2var.get(); } } @@ -1479,7 +1479,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 in type argument for T of Foo: a non-wildcard type argument must have the same nullability in source and target; source has Void where target requires @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 @@ -1532,7 +1532,7 @@ void test( Box nonNullBoundBox, Box nullableBoundBox) { Box ok = identity(nullableBoundBox); - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String Box bad = identity(nonNullBoundBox); } } @@ -1556,7 +1556,7 @@ interface Nested {} return box; } void test(Box> box) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of Box -> lower bound of wildcard -> type argument for T of Nested: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String Box> bad = identity(box); } } @@ -2079,7 +2079,7 @@ static void nullableSuperBounded(NullableNode node) { } static void superBoundedNullableElements(ListNode> node) { - // BUG: Diagnostic contains: incompatible types: List<@Nullable String> + // BUG: Diagnostic contains: incompatible nullability in type argument for E of List: source has @Nullable String where target requires String takesList(node.get()); } } 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..1cd8d2cbd9 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/CaretTests.java @@ -0,0 +1,625 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import com.google.errorprone.CompilationTestHelper; +import com.uber.nullaway.generics.JSpecifyJavacConfig; +import java.util.List; +import java.util.Map; +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. Differences below one printed node, such as a {@code ?} whose implicit + * bound holds two of them, share its caret, which is numbered for each. + */ +public class CaretTests extends MismatchMessageTestBase { + + @Test + public void onlyTheInnermostDifferingNodeIsMarkedInsideAWildcardBound() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ + """, + """ + static void take(List> l) {} + void test(List> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aClassInsideAnImplicitBoundViewedAsItsSupertypeIsMarkedAtTheWildcard() { + assertMessages( + Map.of( + "WRITTEN", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Box + ^ + target: Box> + ^^^^^^ + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is ArrayList<@Nullable String> (JLS 5.1.10) + """, + "CAPTURED", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Box + ^^^^^^^^^^^^ + target: Box> + ^^^^^^ + note: capture of ? is the captured type argument for T of Box, whose upper bound is ArrayList<@Nullable String> (JLS 5.1.10) + """), + """ + static class Box> {} + static void take(Box> b) {} + static Box make() { + throw new RuntimeException(); + } + void written(Box b) { + // BUG: Diagnostic matches: WRITTEN + take(b); + } + void captured() { + // BUG: Diagnostic matches: CAPTURED + take(make()); + } + """); + } + + @Test + public void caretSkipsATypeArgumentTheTargetAccepts() { + assertMessage( + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """, + """ + 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 in type argument for V of Map: source has @Nullable String where target requires String + source: Map + ^^^^^^^^^^^^^^^^ + target: Map + ^^^^^^ + """, + """ + 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 in type argument for C of Three: source has @Nullable String where target requires String + source: Three + ^^^^^^^^^^^^^^^^ + target: Three + ^^^^^^ + """, + """ + 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 in type argument for C of Three: source has @Nullable String where target requires String + source: Three + ^^^^^^^^^^^^^^^^ + target: Three + ^^^^^^ + """, + """ + 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 in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for V of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """, + """ + 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 in component type -> type argument for E of List: source has @Nullable String where target requires String + source: List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + target: List [] + ^^^^^^ + """, + """ + static void take(List[] l) {} + void test(List<@Nullable String>[] l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aNullableArrayComponentTypeIsMarkedInsideATypeArgument() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> component type: source has @Nullable String where target requires String + source: List<@Nullable String []> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ + """, + """ + static void take(List l) {} + void test(List<@Nullable String[]> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aNullableArrayTypeIsMarkedInsideATypeArgument() { + assertMessage( + """ + incompatible nullability in type argument for E of List: source has String @Nullable [] where target requires String [] + source: List + ^^^^^^^^^^^^^^^^^^^ + target: List + ^^^^^^^^^ + """, + """ + static void take(List l) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void twoMismatchesUnderOneWildcardShareItsCaret() { + assertMessage( + """ + incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String + source: Foo + ^ + 1,2 + target: Foo> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map + source: @Nullable String + target: String + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 2. path: type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map + source: @Nullable String + target: String + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + """, + """ + static class Foo> {} + static void take(Foo> f) {} + void test(Foo f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void twoMismatchesUnderOneNestedWildcardShareItsCaret() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String + source: List> + ^ + 1,2 + target: List>> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for K of Map + source: @Nullable String + target: String + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 2. path: type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for V of Map + source: @Nullable String + target: String + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is Map<@Nullable String, @Nullable String> (JLS 5.1.10) + """, + """ + static class Foo> {} + static void take(List>> f) {} + void test(List> f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + // The printed types show a type-use annotation only where its simple name is Nullable, so the + // caret columns count no other annotation + @Test + public void printedTypesShowOnlyAnAnnotationNamedNullable() { + CompilationTestHelper helper = + makeTestHelperWithArgs( + JSpecifyJavacConfig.withJSpecifyModeArgs( + List.of( + "-XepOpt:NullAway:OnlyNullMarked=true", + "-XepOpt:NullAway:CustomNullableAnnotations=Test.CanBeNull,p.Nullable"))); + String withoutAnnotation = + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """; + Map.of( + "NULLABLE_WITH_A_VALUE", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, + "ANNOTATED_WILDCARD", + withoutAnnotation, + "NULLABLE_WILDCARD", + withoutAnnotation, + "TAINTED", + withoutAnnotation, + "TAINTED_ARRAY_ELEMENT", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Map + ^ + target: Map + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter K of Map, which is @Nullable Object (JLS 5.1.10) + """, + "CUSTOM_NULLABLE", + withoutAnnotation) + .forEach((key, expected) -> helper.expectErrorMessage(key, messageIs(expected))); + helper + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface Tainted {} + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + @interface CanBeNull {} + static void takeCustom(Map m) {} + void customNullable(Map custom) { + // BUG: Diagnostic matches: CUSTOM_NULLABLE + takeCustom(custom); + } + static void take(Map m) {} + static void takeArrays(Map m) {} + void tainted(Map tainted) { + // BUG: Diagnostic matches: TAINTED + take(tainted); + } + void taintedArrayElement(Map m) { + // BUG: Diagnostic matches: TAINTED_ARRAY_ELEMENT + takeArrays(m); + } + static void takeNullableValues(Map m) {} + void nullableWithAValue(Map m) { + // BUG: Diagnostic matches: NULLABLE_WITH_A_VALUE + takeNullableValues(m); + } + void annotatedWildcard(Map<@Tainted ?, String> m) { + // BUG: Diagnostic matches: ANNOTATED_WILDCARD + take(m); + } + // BUG: Diagnostic contains: nullness annotations cannot be written directly on a wildcard + void nullableWildcard(Map<@Nullable ?, String> m) { + // BUG: Diagnostic matches: NULLABLE_WILDCARD + take(m); + } + """)) + .addSourceLines( + "p/Nullable.java", + """ + package p; + @java.lang.annotation.Target(java.lang.annotation.ElementType.TYPE_USE) + public @interface Nullable { + String value(); + } + """) + .doTest(); + } + + @Test + public void aNumberThatWouldRunIntoTheOneBeforeItGoesOnAnotherRow() { + assertMessages( + Map.of( + "COLLIDING", + """ + incompatible nullability in type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for A of Three and 4 other differing positions: source has @Nullable String where target requires String + source: ThreeAndTwo + ^ ^ + 1,2,3 + 4,5 + target: ThreeAndTwo, ? extends Two> + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for A of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo has the upper bound of type parameter A of ThreeAndTwo, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 2. path: type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for B of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo has the upper bound of type parameter A of ThreeAndTwo, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for A of ThreeAndTwo -> upper bound of wildcard -> type argument for C of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo has the upper bound of type parameter A of ThreeAndTwo, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 4. path: type argument for B of ThreeAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo<..., ?> has the upper bound of type parameter B of ThreeAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 5. path: type argument for B of ThreeAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeAndTwo<..., ?> has the upper bound of type parameter B of ThreeAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + """, + "COLLIDING_INSIDE_A_MARKED_NODE", + """ + incompatible nullability in type argument for A of Pair -> upper bound of wildcard and 4 other differing positions: source has @Nullable TwoAndTwo where target requires TwoAndTwo + source: Same<@Nullable TwoAndTwo> + ^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 + ^ ^ + 2,3 + 4,5 + target: Pair, ? extends @Nullable TwoAndTwo, ? extends Two>> + ^^^^^^^^^^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Pair -> upper bound of wildcard + source: @Nullable TwoAndTwo + target: TwoAndTwo + \s + 2. path: type argument for B of Pair -> upper bound of wildcard -> type argument for A of TwoAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo has the upper bound of type parameter A of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for B of Pair -> upper bound of wildcard -> type argument for A of TwoAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo has the upper bound of type parameter A of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 4. path: type argument for B of Pair -> upper bound of wildcard -> type argument for B of TwoAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo<..., ?> has the upper bound of type parameter B of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 5. path: type argument for B of Pair -> upper bound of wildcard -> type argument for B of TwoAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in TwoAndTwo<..., ?> has the upper bound of type parameter B of TwoAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + """, + "COLLIDING_ABOVE_A_DEEPER_CARET", + """ + incompatible nullability in type argument for A of Triple -> upper bound of wildcard -> type argument for A of Three and 4 other differing positions: source has @Nullable String where target requires String + source: ThreeThenSame> + ^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1,2,3 + 4 + ^^^^^^^^^^^^^^^^ + 5 + target: Triple, ? extends List<@Nullable String>, ? extends @Nullable List> + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Triple -> upper bound of wildcard -> type argument for A of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeThenSame has the upper bound of type parameter X of ThreeThenSame, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 2. path: type argument for A of Triple -> upper bound of wildcard -> type argument for B of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeThenSame has the upper bound of type parameter X of ThreeThenSame, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for A of Triple -> upper bound of wildcard -> type argument for C of Three + source: @Nullable String + target: String + note: the unbounded wildcard ? in ThreeThenSame has the upper bound of type parameter X of ThreeThenSame, which is Three<@Nullable String, @Nullable String, @Nullable String> (JLS 5.1.10) + \s + 4. path: type argument for B of Triple -> upper bound of wildcard + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 5. path: type argument for C of Triple -> upper bound of wildcard -> type argument for E of List + source: @Nullable String + target: String + """, + "FITTING", + """ + incompatible nullability in type argument for A of OneAndTwo -> upper bound of wildcard -> type argument for A of Two and 2 other differing positions: source has @Nullable String where target requires String + source: OneAndTwo + ^ ^ + 1 2,3 + target: OneAndTwo, ? extends Two> + ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 + \s + 1. path: type argument for A of OneAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in OneAndTwo has the upper bound of type parameter A of OneAndTwo, which is Two<@Nullable String, String> (JLS 5.1.10) + \s + 2. path: type argument for B of OneAndTwo -> upper bound of wildcard -> type argument for A of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in OneAndTwo<..., ?> has the upper bound of type parameter B of OneAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + \s + 3. path: type argument for B of OneAndTwo -> upper bound of wildcard -> type argument for B of Two + source: @Nullable String + target: String + note: the unbounded wildcard ? in OneAndTwo<..., ?> has the upper bound of type parameter B of OneAndTwo, which is Two<@Nullable String, @Nullable String> (JLS 5.1.10) + """), + """ + static class Two {} + static class Three {} + static class ThreeAndTwo, B extends Two<@Nullable String, @Nullable String>> {} + static class TwoAndTwo, B extends Two<@Nullable String, @Nullable String>> {} + static class OneAndTwo, B extends Two<@Nullable String, @Nullable String>> {} + interface Pair {} + interface Same extends Pair {} + static void takeThreeAndTwo(ThreeAndTwo, ? extends Two> t) {} + static void takePair(Pair, ? extends @Nullable TwoAndTwo, ? extends Two>> p) {} + static void takeOneAndTwo(OneAndTwo, ? extends Two> o) {} + void colliding(ThreeAndTwo t) { + // BUG: Diagnostic matches: COLLIDING + takeThreeAndTwo(t); + } + void collidingInsideAMarkedNode(Same<@Nullable TwoAndTwo> s) { + // BUG: Diagnostic matches: COLLIDING_INSIDE_A_MARKED_NODE + takePair(s); + } + interface Triple, B extends @Nullable Object, C extends @Nullable Object> {} + interface ThreeThenSame, T extends @Nullable Object> extends Triple {} + static void takeTriple(Triple, ? extends List<@Nullable String>, ? extends @Nullable List> t) {} + void collidingAboveADeeperCaret(ThreeThenSame> t) { + // BUG: Diagnostic matches: COLLIDING_ABOVE_A_DEEPER_CARET + takeTriple(t); + } + void fitting(OneAndTwo o) { + // BUG: Diagnostic matches: FITTING + takeOneAndTwo(o); + } + """); + } + + @Test + public void anIntersectionIsMarkedOnceAsOneNode() { + assertMessages( + Map.of( + "INTERSECTION", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard: source has I1 & I2 where target requires a supertype of @Nullable C1 + source: List> + ^^^^^^^^^^^^^^^ + target: List + ^^^^^^^^^^^^ + """, + "INTERSECTION_BELOW_ANOTHER_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for V of Map -> lower bound of wildcard: source has I1 & I2 where target requires a supertype of @Nullable C1 + source: Map> + ^^^^^^^^^^^^^^^ + target: Map + ^^^^^^^^^^^^ + """), + """ + interface I1 {} + interface I2 {} + static class C1 implements I1, I2 {} + static class C2 implements I1, I2 {} + static List of2(T a, T b) { + throw new RuntimeException(); + } + void intersection(C1 a, C2 b) { + var l = of2(a, b); + // BUG: Diagnostic matches: INTERSECTION + List t = l; + } + static Map mapOf2(T a, T b) { + throw new RuntimeException(); + } + void intersectionBelowAnotherTypeArgument(C1 a, C2 b) { + var m = mapOf2(a, b); + // BUG: Diagnostic matches: INTERSECTION_BELOW_ANOTHER_TYPE_ARGUMENT + Map t = m; + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java new file mode 100644 index 0000000000..f38d49d2af --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/LowerBoundAndRawSourceTests.java @@ -0,0 +1,171 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.Map; +import org.junit.Test; + +/** + * A difference in a {@code ? super} bound is located like any other, and the target side reads as + * {@code a supertype of} the bound the target states. A raw source has no type arguments to compare + * and draws no message at all, and neither does an array of a raw target type. + */ +public class LowerBoundAndRawSourceTests extends MismatchMessageTestBase { + + @Test + public void aLowerBoundDifferenceIsMarkedInBothTypes() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String + source: List + ^^^^^^ + target: 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 aLowerBoundDifferenceIsMarkedAcrossASupertypeView() { + assertMessage( + """ + incompatible nullability in type argument for T of Base -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String + source: Sub + ^^^^^^ + target: 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 eachNumberedLowerBoundDifferenceSaysTheTargetRequiresASupertype() { + assertMessage( + """ + incompatible nullability in type argument for K of Map -> lower bound of wildcard and 1 other differing position: source has String where target requires a supertype of @Nullable String + source: Map + ^^^^^^ ^^^^^^ + 1 2 + target: Map + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map -> lower bound of wildcard + source: String + target: a supertype of @Nullable String + \s + 2. path: type argument for V of Map -> lower bound of wildcard + source: String + target: a supertype of @Nullable String + """, + """ + static void takeLower(Map m) {} + void numberedLower(Map m) { + // BUG: Diagnostic matches: MESSAGE + takeLower(m); + } + """); + } + + @Test + public void aRawTypeOnEitherSideIsAcceptedWithNoMismatchToReport() { + makeHelper() + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + @SuppressWarnings("rawtypes") + void rawSource(List raw) { + List typed = raw; + typed.hashCode(); + } + @SuppressWarnings("rawtypes") + void rawArrayTarget(List<@Nullable String>[] typed) { + List[] raw = typed; + raw.hashCode(); + } + """)) + .doTest(); + } + + @Test + public void underALowerBoundTheTargetIsTheSubtypeSide() { + assertMessages( + Map.of( + "REORDERING_SUBCLASS", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for B of Pair: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String + source: List> + ^^^^^^ + target: List> + ^^^^^^^^^^^^^^^^ + """, + "WILDCARD_ONLY_IN_SOURCE", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for T of Box: source has Object where target requires a supertype of @Nullable String + source: List> + ^^^^^^ + target: List> + ^^^^^^^^^^^^^^^^ + """, + "TWO_LOWER_BOUNDS", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List -> lower bound of wildcard: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ + """, + "TWO_LOWER_BOUNDS_THEN_A_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List -> lower bound of wildcard -> type argument for T of Box: source has @Nullable String where target requires String + source: List>> + ^^^^^^^^^^^^^^^^ + target: List>> + ^^^^^^ + """), + """ + static class Pair {} + static class Rev extends Pair {} + static class Box {} + static List> pairs() { throw new RuntimeException(); } + static List> boxes() { throw new RuntimeException(); } + void reorderingSubclass() { + // BUG: Diagnostic matches: REORDERING_SUBCLASS + List> l = pairs(); + l.hashCode(); + } + void wildcardOnlyInSource() { + // BUG: Diagnostic matches: WILDCARD_ONLY_IN_SOURCE + List> l = boxes(); + l.hashCode(); + } + static void takeTwo(List> l) {} + void twoLowerBounds(List> l) { + // BUG: Diagnostic matches: TWO_LOWER_BOUNDS + takeTwo(l); + } + static void takeTwoBoxes(List>> l) {} + void twoLowerBoundsThenATypeArgument(List>> l) { + // BUG: Diagnostic matches: TWO_LOWER_BOUNDS_THEN_A_TYPE_ARGUMENT + takeTwoBoxes(l); + } + """); + } +} 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..a495e09dde --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/MismatchMessageTestBase.java @@ -0,0 +1,467 @@ +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.ArrayList; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.function.Predicate; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import org.jspecify.annotations.Nullable; + +/** + * 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 note:} line. A failure prints the expected message beside every + * diagnostic the compilation reported. + * + *

Every diagnostic a test compares must also hold the invariants {@link #checkInvariants} + * states, whatever message the test expects. + */ +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) { + assertMessages(Map.of("MESSAGE", expected), members); + } + + /** + * Compiles {@code members} as the body of {@code @NullMarked class Test} and expects, for each + * key of {@code expectedByKey}, the line after {@code // BUG: Diagnostic matches: KEY} to report + * exactly the message mapped to that key. {@link #assertMessage} documents the rest. + */ + void assertMessages(Map expectedByKey, String members) { + CompilationTestHelper helper = makeHelper(); + Set violations = new LinkedHashSet<>(); + expectedByKey.forEach( + (key, expected) -> helper.expectErrorMessage(key, new MessageIs(expected, violations))); + AssertionError mismatch = null; + try { + helper.addSourceLines("Test.java", nullMarkedClass(members)).doTest(); + } catch (AssertionError e) { + mismatch = e; + } + if (!violations.isEmpty()) { + // a broken invariant usually also makes the text differ from the expected message; the + // invariant names the defect, and the mismatch stays attached as suppressed + AssertionError broken = new AssertionError(String.join("\n", violations)); + if (mismatch != null) { + broken.addSuppressed(mismatch); + } + throw broken; + } + if (mismatch != null) { + throw mismatch; + } + } + + /** + * 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}. The matcher throws {@link AssertionError} on a diagnostic + * that breaks the invariants {@link #checkInvariants} states. + */ + static Predicate messageIs(String expected) { + return new MessageIs(expected, null); + } + + /** + * Returns why {@code message} breaks the invariants every message holds, or an empty list where + * it holds them all: those of {@link #checkNotes}, {@link #checkUnannotatedClassWasCompared}, and + * {@link #checkCarets}. + * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkInvariants(String message) { + List violations = new ArrayList<>(checkNotes(message)); + violations.addAll(checkUnannotatedClassWasCompared(message)); + violations.addAll(checkCarets(message)); + return violations; + } + + /** The first line of a message: the path to the mismatch and the type the source has there. */ + private static final Pattern FIRST_LINE = + Pattern.compile("incompatible nullability in (.*?): source has (.*?) where target requires"); + + /** A {@code note:} line, without its indentation. */ + private static final Pattern NOTE = Pattern.compile("(?m)^\\s*note: (.*)$"); + + /** The citation every note about a wildcard's upper bound ends its bound with. */ + private static final String CITATION = " (JLS 5.1.10)"; + + /** + * Returns why {@code message} breaks the invariants below, or an empty list where it holds them: + * every {@code note:} line states the upper bound of the source wildcard and cites JLS 5.1.10, + * and the bound it states contains no captured type. Where the message has one note and the check + * compared the source's wildcard bound itself, the last step of the first line's path, the bound + * the note states must have the top-level nullness the first line gives the source. + * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkNotes(String message) { + List violations = new ArrayList<>(); + Matcher notes = NOTE.matcher(message); + int noteCount = 0; + String lastBound = null; + while (notes.find()) { + noteCount++; + String note = notes.group(1); + int citation = note.indexOf(CITATION); + String bound = citation < 0 ? null : statedBound(note.substring(0, citation)); + if (bound == null) { + violations.add("a note must state the upper bound and cite JLS 5.1.10, got:\n" + message); + continue; + } + if (bound.contains("capture of")) { + violations.add( + "the bound a note states must not contain a captured type, got:\n" + message); + } + lastBound = bound; + } + Matcher firstLine = FIRST_LINE.matcher(message); + if (noteCount != 1 || lastBound == null || !firstLine.find()) { + return violations; + } + List path = List.of(firstLine.group(1).split(" -> ")); + if (!path.get(path.size() - 1).equals("upper bound of wildcard") + || path.indexOf("upper bound of wildcard") != path.size() - 1) { + return violations; + } + boolean sourceNullable = isTopLevelNullable(firstLine.group(2)); + if (isTopLevelNullable(lastBound) != sourceNullable) { + violations.add( + "the bound a note states must have the nullness the first line gives the source, got:\n" + + message); + } + return violations; + } + + /** + * Returns the upper bound a note states before its citation, or {@code null} where it states + * none. + */ + private static @Nullable String statedBound(String beforeCitation) { + for (String lead : List.of(", which is ", "upper bound is ", "has the upper bound ")) { + int at = beforeCitation.lastIndexOf(lead); + if (at >= 0) { + return beforeCitation.substring(at + lead.length()); + } + } + return null; + } + + /** The path the first line names, without the count of the other differing positions. */ + private static final Pattern FIRST_LINE_PATH = + Pattern.compile( + "^incompatible nullability in (.*?)(?: and \\d+ other differing positions?)?:" + + " (?:source has|a non-wildcard)"); + + /** The {@code path:} line of a numbered entry. */ + private static final Pattern ENTRY_PATH = Pattern.compile("^\\s*\\d+\\. path: (.*)$"); + + /** The class a note names as unannotated, which makes the bound it states {@code @Nullable}. */ + private static final Pattern UNANNOTATED_CLASS = + Pattern.compile("the bound is @Nullable because (\\w+) is unannotated"); + + /** The step of a path into a type argument, naming the type parameter there. */ + private static final String TYPE_ARGUMENT_STEP = "type argument for "; + + /** The step of a path into the upper bound of a wildcard. */ + private static final String UPPER_BOUND_STEP = "upper bound of wildcard"; + + /** + * Returns why {@code message} breaks this invariant, or an empty list where it holds it: a note + * that blames an unannotated class for the {@code @Nullable} bound it states names the class of a + * type parameter whose bound the check compared. Such a type parameter is one the path of the + * note's mismatch steps into just before an {@code upper bound of wildcard} step. A note under a + * numbered entry belongs to that entry's {@code path:}, and any other note to the path the first + * line names. Such a note also states a bound that is {@code @Nullable} at its top level, since + * an unannotated class keeps an explicit {@code @NonNull}, and belongs to a path that ends in the + * {@code upper bound of wildcard} step, since NullAway's default for unannotated code makes only + * the bound itself {@code @Nullable} and explains no difference below it. + * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkUnannotatedClassWasCompared(String message) { + List violations = new ArrayList<>(); + String[] lines = message.split("\n", -1); + Matcher first = FIRST_LINE_PATH.matcher(lines[0]); + String path = first.find() ? first.group(1) : ""; + for (String line : lines) { + Matcher entry = ENTRY_PATH.matcher(line); + if (entry.matches()) { + path = entry.group(1); + continue; + } + Matcher note = NOTE.matcher(line); + Matcher blamed = UNANNOTATED_CLASS.matcher(line); + if (!note.matches() || !blamed.find()) { + continue; + } + List compared = new ArrayList<>(); + List steps = List.of(path.split(" -> ")); + for (int i = 1; i < steps.size(); i++) { + if (steps.get(i).equals(UPPER_BOUND_STEP) + && steps.get(i - 1).startsWith(TYPE_ARGUMENT_STEP)) { + String parameter = steps.get(i - 1).substring(TYPE_ARGUMENT_STEP.length()); + compared.add(parameter.substring(parameter.indexOf(" of ") + " of ".length())); + } + } + if (!steps.get(steps.size() - 1).equals(UPPER_BOUND_STEP)) { + violations.add( + "a note that says the bound is @Nullable must belong to a mismatch at the bound itself," + + " got:\n" + + message); + } + if (!compared.contains(blamed.group(1))) { + violations.add( + String.format( + "a note must blame only a class whose type parameter's bound the check compared," + + " one of %s, and it blames %s:%n%s", + compared, blamed.group(1), message)); + } + int citation = note.group(1).indexOf(CITATION); + String bound = citation < 0 ? null : statedBound(note.group(1).substring(0, citation)); + if (bound == null || !isTopLevelNullable(bound)) { + violations.add( + "a note that says the bound is @Nullable must state a @Nullable bound, got:\n" + + message); + } + } + return violations; + } + + /** + * Whether {@code printed}, a printed type, is {@code @Nullable} at its top level, where the + * printer puts that annotation: before a class type, before the last simple name of an inner + * class type ({@code Outer.@Nullable Inner}), or, for an array type, on its last + * dimension, which the printer writes outermost last ({@code String @Nullable []}); an annotation + * anywhere else in an array type is on a component. + */ + static boolean isTopLevelNullable(String printed) { + if (printed.endsWith("[]")) { + return printed.endsWith(" @Nullable []"); + } + if (printed.startsWith("@Nullable ")) { + return true; + } + // a qualified name is annotated at its innermost class where the last "." outside every type + // argument list starts ".@Nullable " + int depth = 0; + int last = -1; + for (int i = 0; i < printed.length(); i++) { + char c = printed.charAt(i); + if (c == '<') { + depth++; + } else if (c == '>') { + depth--; + } else if (depth == 0 && c == '.') { + last = printed.startsWith(".@Nullable ", i) ? i : -1; + } + } + return last >= 0; + } + + /** + * Whether {@code printed}, a printed type, is an intersection: it holds {@code &} outside the + * angle brackets of every type argument list. + */ + private static boolean isIntersection(String printed) { + int depth = 0; + for (int i = 0; i < printed.length(); i++) { + char c = printed.charAt(i); + if (c == '<') { + depth++; + } else if (c == '>') { + depth--; + } else if (c == '&' && depth == 0) { + return true; + } + } + return false; + } + + /** A line that prints a type: the source, the supertype of it the check compared, the target. */ + private static final Pattern TYPE_LINE = + Pattern.compile("^ (source supertype|source|target): "); + + /** A row of carets under a type line. */ + private static final Pattern CARET_ROW = Pattern.compile("^ +[\\^ ]*\\^[\\^ ]*$"); + + /** A row of mismatch numbers under a row of carets. */ + private static final Pattern NUMBER_ROW = Pattern.compile("^ +[0-9][0-9, ]*$"); + + /** A run of carets in a caret row. */ + private static final Pattern CARET_RUN = Pattern.compile("\\^+"); + + /** + * Returns why {@code message} breaks these invariants, or an empty list where it holds them: + * + *

    + *
  • a {@code source supertype} line carries a caret, since a caret is what it is printed for; + *
  • a message with one mismatch puts at most one caret run under each type line, and in a + * numbered message each number appears at most once under each type line, and at most once + * under the two source lines together, so one position gets one mark; + *
  • in a numbered message, every numbered entry has its number under the {@code target} line, + * except where the target is an intersection, which has no caret yet (#2202). + *
+ * + * @param message the text of one diagnostic, without the {@code [NullAway]} prefix and the link + * line + */ + static List checkCarets(String message) { + List violations = new ArrayList<>(); + String[] lines = message.split("\n", -1); + int entries = 0; + for (String line : lines) { + if (ENTRY_PATH.matcher(line).matches()) { + entries++; + } + } + List sourceNumbers = new ArrayList<>(); + for (int i = 0; i < lines.length; i++) { + Matcher typeLine = TYPE_LINE.matcher(lines[i]); + if (!typeLine.find()) { + continue; + } + String label = typeLine.group(1); + int runs = 0; + List numbers = new ArrayList<>(); + for (int j = i + 1; j < lines.length; j++) { + if (CARET_ROW.matcher(lines[j]).matches()) { + Matcher run = CARET_RUN.matcher(lines[j]); + while (run.find()) { + runs++; + } + } else if (NUMBER_ROW.matcher(lines[j]).matches()) { + for (String number : lines[j].trim().split("[ ,]+")) { + numbers.add(number); + } + } else { + break; + } + } + if (label.equals("source supertype") && runs == 0) { + violations.add("a source supertype line must carry a caret, got:\n" + message); + } + if (entries == 0 && runs > 1) { + violations.add( + String.format( + "the %s line of a message with one mismatch must carry one caret run, got %d:%n%s", + label, runs, message)); + } + if (numbers.size() != new LinkedHashSet<>(numbers).size()) { + violations.add( + String.format( + "each number must mark one position under the %s line, got %s:%n%s", + label, numbers, message)); + } + if (label.startsWith("source")) { + sourceNumbers.addAll(numbers); + } else if (isIntersection(lines[i].substring(typeLine.end()))) { + // known gap #2202: the target line of an intersection has no caret under either component + if (!numbers.isEmpty()) { + violations.add( + "an intersection target now carries numbers; drop the #2202 exception, got:\n" + + message); + } + } else { + for (int number = 1; number <= entries; number++) { + if (!numbers.contains(Integer.toString(number))) { + violations.add( + String.format( + "entry %d must have its caret under the target line, got %s:%n%s", + number, numbers, message)); + } + } + } + } + if (sourceNumbers.size() != new LinkedHashSet<>(sourceNumbers).size()) { + violations.add( + String.format( + "each number must mark one position on the source lines together, got %s:%n%s", + sourceNumbers, message)); + } + return violations; + } + + /** + * 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. What {@link + * #checkInvariants} finds wrong in a diagnostic it is shown goes to {@code violations}, and where + * that is {@code null}, fails the test at once. + */ + private record MessageIs(String expected, @Nullable Set violations) + 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 diagnostic) { + if (!diagnostic.startsWith(PREFIX)) { + return false; + } + if (!diagnostic.endsWith(LINK_LINE)) { + return false; + } + int link = diagnostic.length() - LINK_LINE.length(); + String message = diagnostic.substring(PREFIX.length(), link); + List broken = checkInvariants(message); + if (violations != null) { + violations.addAll(broken); + } else if (!broken.isEmpty()) { + throw new AssertionError(String.join("\n", broken)); + } + return message.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..3fa40cff67 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/NoteTests.java @@ -0,0 +1,1376 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.Map; +import org.junit.Test; + +/** + * A {@code note:} line says where the source takes a nullness its printed form does not show: the + * upper bound an unbounded or lower-bounded wildcard takes from its type parameter, or the upper + * bound of a captured wildcard. It prints the class the wildcard is a type argument of, with every + * other type argument whose printed form contains {@code ?} or {@code <} written as {@code ...}. 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 anUnboundedWildcardNamesTheTypeParameterItsUpperBoundComesFrom() { + assertMessage( + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + """ + 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 theNotePrintsOnlyTheWildcardItMeansAndSimpleTypeArguments() { + assertMessage( + """ + incompatible nullability in type argument for B of Triple -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Triple> + ^ + target: Triple + ^^^^^^ + note: the unbounded wildcard ? in Triple has the upper bound of type parameter B of Triple, which is @Nullable Object (JLS 5.1.10) + """, + """ + static class Triple {} + static void take(Triple t) {} + void test(Triple> t) { + // BUG: Diagnostic matches: MESSAGE + take(t); + } + """); + } + + @Test + public void theNoteGivesTheBoundWithTheOtherTypeArgumentsSubstituted() { + assertMessage( + """ + incompatible nullability in type argument for B of Foo -> upper bound of wildcard: source has @Nullable List where target requires List + source: Foo + ^ + target: Foo> + ^^^^^^^^^^^^ + note: the unbounded wildcard ? in Foo has the upper bound of type parameter B of Foo, which is @Nullable List (JLS 5.1.10) + """, + """ + static class Foo> {} + static void take(Foo> f) {} + void test(Foo f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void aSuperBoundedWildcardNamesTheTypeParameterItsUpperBoundComesFrom() { + assertMessage( + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^^^^^^^^^^^^^^ + target: Collection + ^^^^^^ + note: the wildcard ? super String in List has no upper bound of its own; its upper bound is the bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + """ + static void take(Collection c) {} + void test(List list) { + // BUG: Diagnostic matches: MESSAGE + take(list); + } + """); + } + + @Test + public void anExplicitlyWrittenNullableBoundDrawsNoNote() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard: source has @Nullable String where target requires String + source: List + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ + """, + """ + static void take(List l) {} + void test(List l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void noNoteWhereTheUseStatesItsOwnNullness() { + assertMessage( + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable T where target requires Object + source: Box<@Nullable T> + ^^^^^^^^^^^ + target: Box + ^^^^^^ + """, + """ + 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); + } + """); + } + + @Test + public void aWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in type argument for T of Foo -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Foo + ^ + target: Foo> + ^^^^^^ + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) + """, + """ + static class Foo> {} + static void take(Foo> f) {} + void test(Foo f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void aNestedWildcardWhoseImplicitBoundHoldsTheMismatchNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for T of Foo -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: List> + ^ + target: List>> + ^^^^^^ + note: the unbounded wildcard ? in Foo has the upper bound of type parameter T of Foo, which is List<@Nullable String> (JLS 5.1.10) + """, + """ + static class Foo> {} + static void take(List>> f) {} + void test(List> f) { + // BUG: Diagnostic matches: MESSAGE + take(f); + } + """); + } + + @Test + public void aWildcardInsideAWildcardBoundNamesItsTypeParameter() { + assertMessages( + Map.of( + "WRITTEN", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List> + ^ + target: List> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "CAPTURED", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List> + ^ + target: List> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "CAPTURED_ONE_LEVEL_DOWN", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List>> + ^ + target: List>> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """), + """ + static void take(List> l) {} + static void takeNested(List>> l) {} + static List same(List l) { + throw new RuntimeException(); + } + static List wrap(T t) { + throw new RuntimeException(); + } + void written(List> l) { + // BUG: Diagnostic matches: WRITTEN + take(l); + } + void captured(List> l) { + // BUG: Diagnostic matches: CAPTURED + take(same(l)); + } + void capturedOneLevelDown(List> l) { + // BUG: Diagnostic matches: CAPTURED_ONE_LEVEL_DOWN + takeNested(wrap(same(l))); + } + """); + } + + @Test + public void aWildcardInsideAnArrayInsideAWildcardBoundNamesItsTypeParameter() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> component type -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List []> + ^ + target: List []> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + """ + static void take(List[]> l) {} + void test(List[]> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + // SubBox and SubSubBox bound T by a non-null Object, while the check compares the @Nullable + // bound of Box and reports a false positive (#2206). CAPTURED_IN_A_SUBCLASS and + // CAPTURED_TWO_SUBCLASSES_DOWN get no note, since it would attribute the bound the check compared + // to a T that declares another. + @Test + public void aCapturedWildcardNamesTheTypeParameterOnlyWhereItInstantiatesIt() { + assertMessages( + Map.of( + "CAPTURED_FROM_AN_UNANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """, + "CAPTURED_IN_A_SUBCLASS", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: SubBox + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + """, + "CAPTURED_TWO_SUBCLASSES_DOWN", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: SubSubBox + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + """, + "CAPTURED_WHERE_WRITTEN", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Box + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + note: capture of ? is the captured type argument for T of Box, whose upper bound is @Nullable Object (JLS 5.1.10) + """, + "SUBSTITUTED_INTO_ANOTHER_CLASS", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for V of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """, + "SUBSTITUTED_WITH_A_BOUND_ON_ANOTHER_CAPTURE", + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable List where target requires List + source: Map + ^^^^^^^^^^^^ + target: Map> + ^^^^^^^ + """, + "SUBSTITUTED_WITH_A_BOUND_ON_A_METHOD_TYPE_VARIABLE", + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable List where target requires List + source: Map + ^^^^^^^^^^^^ + target: Map> + ^^^^^^^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable List (JLS 5.1.10) + """, + "SUBSTITUTED_WITH_A_BOUND_ON_A_TYPE_VARIABLE_OF_A_CLASS_NOT_PRINTED", + """ + incompatible nullability in type argument for V of Map -> upper bound of wildcard: source has @Nullable List where target requires List + source: Map + ^^^^^^^^^^^^ + target: Map> + ^^^^^^^ + note: capture of ? is a captured wildcard whose upper bound is @Nullable List (JLS 5.1.10) + """, + "EARLIER_VIEW", + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "SUBSTITUTED_AFTER_AN_EARLIER_VIEW", + """ + incompatible nullability in type argument for K of Map -> upper bound of wildcard and 1 other differing position: source has @Nullable Object where target requires Object + source: Map + ^^^^^^^^^^^^ ^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for V of Map -> upper bound of wildcard + source: @Nullable Object + target: Object + note: capture of ? is a captured wildcard whose upper bound is @Nullable Object (JLS 5.1.10) + """), + """ + static class Box {} + static void takeBox(Box b) {} + static Box make() { + throw new RuntimeException(); + } + @NullUnmarked + static class Legacy {} + @NullUnmarked + static Legacy makeLegacy() { + throw new RuntimeException(); + } + static void takeLegacy(Legacy l) {} + void capturedFromAnUnannotatedClass() { + // BUG: Diagnostic matches: CAPTURED_FROM_AN_UNANNOTATED_CLASS + takeLegacy(makeLegacy()); + } + static class SubBox extends Box {} + static SubBox makeSubBox() { + throw new RuntimeException(); + } + void capturedInASubclass() { + // BUG: Diagnostic matches: CAPTURED_IN_A_SUBCLASS + takeBox(makeSubBox()); + } + static class SubSubBox extends SubBox {} + static SubSubBox makeSubSubBox() { + throw new RuntimeException(); + } + void capturedTwoSubclassesDown() { + // BUG: Diagnostic matches: CAPTURED_TWO_SUBCLASSES_DOWN + takeBox(makeSubSubBox()); + } + void capturedWhereWritten() { + // BUG: Diagnostic matches: CAPTURED_WHERE_WRITTEN + takeBox(make()); + } + static Map duplicate(List x) { + throw new RuntimeException(); + } + static void takeMap(Map m) {} + void substitutedIntoAnotherClass(List l) { + // BUG: Diagnostic matches: SUBSTITUTED_INTO_ANOTHER_CLASS + takeMap(duplicate(l)); + } + static class Dep> {} + static Dep makeDep() { + throw new RuntimeException(); + } + static > Map toMap(Dep d) { + throw new RuntimeException(); + } + static void takeMapOfLists(Map> m) {} + void substitutedWithABoundOnAnotherCapture() { + // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_ANOTHER_CAPTURE + takeMapOfLists(toMap(makeDep())); + } + void substitutedWithABoundOnAMethodTypeVariable(Dep d) { + // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_A_METHOD_TYPE_VARIABLE + takeMapOfLists(toMap(d)); + } + static class Host { + void substitutedWithABoundOnATypeVariableOfAClassNotPrinted(Dep d) { + // BUG: Diagnostic matches: SUBSTITUTED_WITH_A_BOUND_ON_A_TYPE_VARIABLE_OF_A_CLASS_NOT_PRINTED + takeMapOfLists(toMap(d)); + } + } + static void takeCollection(Collection c) {} + void substitutedAfterAnEarlierView(List l) { + // BUG: Diagnostic matches: EARLIER_VIEW + takeCollection(l); + // BUG: Diagnostic matches: SUBSTITUTED_AFTER_AN_EARLIER_VIEW + takeMap(duplicate(l)); + } + """); + } + + @Test + public void aNoteSaysTheBoundIsNullableBecauseTheClassWhoseBoundTheCheckComparedIsUnannotated() { + assertMessages( + Map.ofEntries( + Map.entry( + "UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: LegacySub + ^ + target: Box + ^^^^^^ + note: the unbounded wildcard ? in LegacySub has the upper bound of type parameter T of LegacySub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "CAPTURED_IN_AN_UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: LegacySub + ^^^^^^^^^^^^ + target: Box + ^^^^^^ + note: capture of ? is the captured type argument for T of LegacySub, whose upper bound is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_SUBCLASS_WITH_A_PARAMETERIZED_BOUND", + """ + incompatible nullability in type argument for T of ListBox -> upper bound of wildcard: source has @Nullable List where target requires List + source: LegacyListSub + ^ + target: ListBox> + ^^^^^^^^^^^^ + note: the unbounded wildcard ? in LegacyListSub has the upper bound of type parameter T of LegacyListSub, which is @Nullable List (JLS 5.1.10) + """), + Map.entry( + "ANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableSub + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in NullableSub has the upper bound of type parameter T of NullableSub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: LegacySubOfLegacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in LegacySubOfLegacy has the upper bound of type parameter T of LegacySubOfLegacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of ExplicitLegacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: ExplicitLegacy + ^ + target: ExplicitLegacy + ^^^^^^ + note: the unbounded wildcard ? in ExplicitLegacy has the upper bound of type parameter T of ExplicitLegacy, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_SUBCLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: ExplicitLegacySub + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in ExplicitLegacySub has the upper bound of type parameter T of ExplicitLegacySub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_AN_IMPLICITLY_NULLABLE_INNER_CLASS_BOUND", + """ + incompatible nullability in type argument for T of InnerLegacy -> upper bound of wildcard: source has Outer.@Nullable Inner where target requires Outer.Inner + source: InnerLegacy + ^ + target: InnerLegacy + ^^^^^^^^^^^ + note: the unbounded wildcard ? in InnerLegacy has the upper bound of type parameter T of InnerLegacy, which is Outer.@Nullable Inner (JLS 5.1.10); the bound is @Nullable because InnerLegacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_A_BOUND_ON_A_NULLABLE_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for B of DepLegacy -> upper bound of wildcard: source has @Nullable String where target requires Object + source: DepLegacy<@Nullable String, capture of ?> + ^^^^^^^^^^^^ + target: DepLegacy + ^^^^^^ + note: capture of ? is the captured type argument for B of DepLegacy, whose upper bound is @Nullable String (JLS 5.1.10) + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_A_BOUND_IN_A_GENERIC_ENCLOSING_TYPE", + """ + incompatible nullability in type argument for T of GenericInnerLegacy -> upper bound of wildcard: source has GenericOuter.@Nullable Inner where target requires GenericOuter.Inner + source: GenericInnerLegacy + ^ + target: GenericInnerLegacy.Inner> + ^^^^^^^^^^^^^^^^^^^^^^^^^^ + note: the unbounded wildcard ? in GenericInnerLegacy has the upper bound of type parameter T of GenericInnerLegacy, which is GenericOuter.@Nullable Inner (JLS 5.1.10); the bound is @Nullable because GenericInnerLegacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_WITH_A_NON_NULL_BOUND", + """ + incompatible nullability in type argument for T of NonNullLegacy -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NonNullLegacy + ^ + target: NonNullLegacy> + ^^^^^^ + note: the unbounded wildcard ? in NonNullLegacy has the upper bound of type parameter T of NonNullLegacy, which is List<@Nullable String> (JLS 5.1.10) + """), + Map.entry( + "UNBOUNDED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "UNBOUNDED_IN_AN_ASSIGNMENT", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^ + target: Legacy + ^^^^^^ + note: the unbounded wildcard ? in Legacy has the upper bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "SUPER_BOUNDED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: the wildcard ? super String in Legacy has no upper bound of its own; its upper bound is the bound of type parameter T of Legacy, which is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "CAPTURED", + """ + incompatible nullability in type argument for T of Legacy -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Legacy + ^^^^^^^^^^^^ + target: Legacy + ^^^^^^ + note: capture of ? is the captured type argument for T of Legacy, whose upper bound is @Nullable Object (JLS 5.1.10); the bound is @Nullable because Legacy is unannotated + """), + Map.entry( + "UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of NestedLegacy -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NestedLegacy + ^ + target: NestedLegacy> + ^^^^^^ + note: the unbounded wildcard ? in NestedLegacy has the upper bound of type parameter T of NestedLegacy, which is @Nullable List<@Nullable String> (JLS 5.1.10) + """), + Map.entry( + "CAPTURED_IN_AN_UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND", + """ + incompatible nullability in type argument for T of NestedLegacy -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NestedLegacy + ^^^^^^^^^^^^ + target: NestedLegacy> + ^^^^^^ + note: capture of ? is the captured type argument for T of NestedLegacy, whose upper bound is @Nullable List<@Nullable String> (JLS 5.1.10) + """), + Map.entry( + "ANNOTATED", + """ + incompatible nullability in type argument for T of Box -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Box + ^ + target: Box + ^^^^^^ + note: the unbounded wildcard ? in Box has the upper bound of type parameter T of Box, which is @Nullable Object (JLS 5.1.10) + """)), + """ + @NullUnmarked + static class Legacy {} + @NullUnmarked + static Legacy makeLegacy() { + throw new RuntimeException(); + } + static void takeLegacy(Legacy l) {} + void unbounded(Legacy l) { + // BUG: Diagnostic matches: UNBOUNDED + takeLegacy(l); + } + void unboundedInAnAssignment(Legacy l) { + // BUG: Diagnostic matches: UNBOUNDED_IN_AN_ASSIGNMENT + Legacy x = l; + x.hashCode(); + } + void superBounded(Legacy l) { + // BUG: Diagnostic matches: SUPER_BOUNDED + takeLegacy(l); + } + void captured() { + // BUG: Diagnostic matches: CAPTURED + takeLegacy(makeLegacy()); + } + static class Box {} + static void takeBox(Box b) {} + void annotated(Box b) { + // BUG: Diagnostic matches: ANNOTATED + takeBox(b); + } + @NullUnmarked + static class LegacySub extends Box {} + void unannotatedSubclassOfAnAnnotatedClass(LegacySub s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS + takeBox(s); + } + @NullUnmarked + static LegacySub makeLegacySub() { + throw new RuntimeException(); + } + void capturedInAnUnannotatedSubclassOfAnAnnotatedClass() { + // BUG: Diagnostic matches: CAPTURED_IN_AN_UNANNOTATED_SUBCLASS_OF_AN_ANNOTATED_CLASS + takeBox(makeLegacySub()); + } + static class ListBox> {} + @NullUnmarked + static class LegacyListSub> extends ListBox {} + static void takeListBox(ListBox> b) {} + void unannotatedSubclassWithAParameterizedBound(LegacyListSub s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_WITH_A_PARAMETERIZED_BOUND + takeListBox(s); + } + static class NullableSub extends Legacy {} + void annotatedSubclassOfAnUnannotatedClass(NullableSub s) { + // BUG: Diagnostic matches: ANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS + takeLegacy(s); + } + @NullUnmarked + static class LegacySubOfLegacy extends Legacy {} + @NullUnmarked + static class NonNullLegacy> {} + static void takeNonNullLegacy(NonNullLegacy> l) {} + @NullUnmarked + static class ExplicitLegacy {} + static void takeExplicitLegacy(ExplicitLegacy l) {} + void unannotatedClassWithAnExplicitlyNullableBound(ExplicitLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND + takeExplicitLegacy(l); + } + @NullUnmarked + static class ExplicitLegacySub extends Legacy {} + void unannotatedSubclassWithAnExplicitlyNullableBound(ExplicitLegacySub s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_WITH_AN_EXPLICITLY_NULLABLE_BOUND + takeLegacy(s); + } + static class Outer { + class Inner {} + } + @NullUnmarked + static class InnerLegacy {} + static void takeInnerLegacy(InnerLegacy l) {} + void unannotatedClassWithAnImplicitlyNullableInnerClassBound(InnerLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_AN_IMPLICITLY_NULLABLE_INNER_CLASS_BOUND + takeInnerLegacy(l); + } + @NullUnmarked + static class DepLegacy {} + static DepLegacy<@Nullable String, ?> makeDepLegacy() { + throw new RuntimeException(); + } + static void takeDepLegacy(DepLegacy d) {} + void unannotatedClassWithABoundOnANullableTypeArgument() { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_A_BOUND_ON_A_NULLABLE_TYPE_ARGUMENT + takeDepLegacy(makeDepLegacy()); + } + static class GenericOuter { + class Inner {} + } + @NullUnmarked + static class GenericInnerLegacy.Inner> {} + static void takeGenericInnerLegacy( + GenericInnerLegacy.Inner> l) {} + void unannotatedClassWithABoundInAGenericEnclosingType(GenericInnerLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_A_BOUND_IN_A_GENERIC_ENCLOSING_TYPE + takeGenericInnerLegacy(l); + } + void unannotatedClassWithANonNullBound(NonNullLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_WITH_A_NON_NULL_BOUND + takeNonNullLegacy(l); + } + void unannotatedSubclassOfAnUnannotatedClass(LegacySubOfLegacy s) { + // BUG: Diagnostic matches: UNANNOTATED_SUBCLASS_OF_AN_UNANNOTATED_CLASS + takeLegacy(s); + } + @NullUnmarked + static class NestedLegacy> {} + @NullUnmarked + static NestedLegacy makeNestedLegacy() { + throw new RuntimeException(); + } + static void takeNestedLegacy(NestedLegacy> l) {} + void unannotatedClassDifferingBelowItsImplicitlyNullableBound(NestedLegacy l) { + // BUG: Diagnostic matches: UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND + takeNestedLegacy(l); + } + void capturedInAnUnannotatedClassDifferingBelowItsImplicitlyNullableBound() { + // BUG: Diagnostic matches: CAPTURED_IN_AN_UNANNOTATED_CLASS_DIFFERING_BELOW_ITS_IMPLICITLY_NULLABLE_BOUND + takeNestedLegacy(makeNestedLegacy()); + } + """); + } + + @Test + public void aCapturedWildcardsBoundNamesTypeParametersRatherThanCaptures() { + assertMessages( + Map.of( + "SELF", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: Self + ^^^^^^^^^^^^ + target: Self> + ^^^^^^^^^^^^^ + note: capture of ? is the captured type argument for T of Self, whose upper bound is @Nullable Comparable (JLS 5.1.10) + """, + "SUBCLASS_DECLARING_THE_SAME_BOUND", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: SubSelf + ^^^^^^^^^^^^ + target: Self> + ^^^^^^^^^^^^^ + note: capture of ? is the captured type argument for U of SubSelf, whose upper bound is @Nullable Comparable (JLS 5.1.10) + """, + "SUBCLASS_DECLARING_ANOTHER_BOUND", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: NonNullSubSelf + ^^^^^^^^^^^^ + target: Self> + ^^^^^^^^^^^^^ + """, + "BELOW_ROOT_NAMES_NO_HOLDER", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: List + target: List>>> + ^^^^^^^^^^^^^ + """, + "INNER", + """ + incompatible nullability in type argument for I of Inner -> upper bound of wildcard: source has @Nullable List where target requires List + source: Outer.Inner + ^^^^^^^^^^^^ + target: Outer.Inner> + ^^^^^^^ + note: capture of ? is the captured type argument for I of Inner, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "INNER_SUBCLASS", + """ + incompatible nullability in type argument for I of Inner -> upper bound of wildcard: source has @Nullable List where target requires List + source: Outer.NonNullInner + ^^^^^^^^^^^^ + target: Outer.Inner> + ^^^^^^^ + """, + "WILDCARD_IN_BOUND", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard: source has @Nullable List where target requires List + source: Dep + ^^^^^^^^^^^^ + target: Dep> + ^^^^^^^ + note: capture of ? is the captured type argument for B of Dep, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "ARRAY_IN_BOUND", + """ + incompatible nullability in type argument for B of ArrayDep -> upper bound of wildcard: source has @Nullable List where target requires List + source: ArrayDep + ^^^^^^^^^^^^ + target: ArrayDep> + ^^^^^^^ + note: capture of ? is the captured type argument for B of ArrayDep, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "CAPTURE_OF_ANOTHER_TYPE_IN_BOUND", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard: source has @Nullable List> where target requires List + source: Dep, capture of ?> + ^^^^^^^^^^^^ + target: Dep> + ^^^^^^^ + """), + """ + static class Self> {} + static Self makeSelf() { + throw new RuntimeException(); + } + static void takeSelf(Self> s) {} + void self() { + // BUG: Diagnostic matches: SELF + takeSelf(makeSelf()); + } + static class SubSelf> extends Self {} + static SubSelf makeSubSelf() { + throw new RuntimeException(); + } + void subclassDeclaringTheSameBound() { + // BUG: Diagnostic matches: SUBCLASS_DECLARING_THE_SAME_BOUND + takeSelf(makeSubSelf()); + } + static class NonNullSubSelf> extends Self {} + static NonNullSubSelf makeNonNullSubSelf() { + throw new RuntimeException(); + } + void subclassDeclaringAnotherBound() { + // BUG: Diagnostic matches: SUBCLASS_DECLARING_ANOTHER_BOUND + takeSelf(makeNonNullSubSelf()); + } + static class Base {} + static class SelfSub extends Base> {} + static void takeList(List>>> l) {} + void belowRootNamesNoHolder(List l) { + // BUG: Diagnostic matches: BELOW_ROOT_NAMES_NO_HOLDER + takeList(l); + } + static class Outer { + class Inner> {} + class NonNullInner> extends Inner {} + } + static Outer.NonNullInner makeNonNullInner() { + throw new RuntimeException(); + } + static Outer.Inner makeInner() { + throw new RuntimeException(); + } + static void takeInner(Outer.Inner> i) {} + void inner() { + // BUG: Diagnostic matches: INNER + takeInner(makeInner()); + } + void innerSubclass() { + // BUG: Diagnostic matches: INNER_SUBCLASS + takeInner(makeNonNullInner()); + } + static class Dep> {} + static Dep makeDep() { + throw new RuntimeException(); + } + static void takeDep(Dep> d) {} + void wildcardInBound() { + // BUG: Diagnostic matches: WILDCARD_IN_BOUND + takeDep(makeDep()); + } + static class ArrayDep> {} + static ArrayDep makeArrayDep() { + throw new RuntimeException(); + } + static void takeArrayDep(ArrayDep> d) {} + void arrayInBound() { + // BUG: Diagnostic matches: ARRAY_IN_BOUND + takeArrayDep(makeArrayDep()); + } + static Dep depOf(T t) { + throw new RuntimeException(); + } + static List makeList() { + throw new RuntimeException(); + } + void captureOfAnotherTypeInBound() { + // BUG: Diagnostic matches: CAPTURE_OF_ANOTHER_TYPE_IN_BOUND + takeDep(depOf(makeList())); + } + """); + } + + @Test + public void + aCapturedWildcardGetsNoNoteWhereItsBoundWouldPrintACaptureInsideAnArrayOrAnEnclosingType() { + assertMessages( + Map.of( + "TYPE_PARAMETER_IN_AN_ARRAY", + """ + incompatible nullability in type argument for B of ArrayDep -> upper bound of wildcard: source has @Nullable List where target requires List + source: ArrayDep + ^^^^^^^^^^^^ + target: ArrayDep> + ^^^^^^^ + note: capture of ? is the captured type argument for B of ArrayDep, whose upper bound is @Nullable List (JLS 5.1.10) + """, + "CAPTURE_IN_AN_ARRAY", + """ + incompatible nullability in type argument for B of ArrayDep -> upper bound of wildcard: source has @Nullable List []> where target requires List + source: ArrayDep, capture of ?> + ^^^^^^^^^^^^ + target: ArrayDep> + ^^^^^^^ + """, + "CAPTURE_IN_A_TWO_DIMENSIONAL_ARRAY", + """ + incompatible nullability in type argument for B of Array2Dep -> upper bound of wildcard: source has @Nullable List [] []> where target requires List + source: Array2Dep, capture of ?> + ^^^^^^^^^^^^ + target: Array2Dep> + ^^^^^^^ + """, + "CAPTURE_IN_AN_ENCLOSING_TYPE", + """ + incompatible nullability in type argument for B of Dep2 -> upper bound of wildcard: source has Outer2>.@Nullable In where target requires Outer2.In + source: Dep2, capture of ?> + ^^^^^^^^^^^^ + target: Dep2.In> + ^^^^^^^^^^^^ + """), + """ + static class ArrayDep> {} + static ArrayDep makeArrayDep() { + throw new RuntimeException(); + } + static void takeArrayDep(ArrayDep> d) {} + void typeParameterInAnArray() { + // BUG: Diagnostic matches: TYPE_PARAMETER_IN_AN_ARRAY + takeArrayDep(makeArrayDep()); + } + static List makeList() { + throw new RuntimeException(); + } + static ArrayDep arrayDepOf(T t) { + throw new RuntimeException(); + } + void captureInAnArrayInBound() { + // BUG: Diagnostic matches: CAPTURE_IN_AN_ARRAY + takeArrayDep(arrayDepOf(makeList())); + } + static class Array2Dep> {} + static Array2Dep array2DepOf(T t) { + throw new RuntimeException(); + } + static void takeArray2Dep(Array2Dep> d) {} + void captureInATwoDimensionalArrayInBound() { + // BUG: Diagnostic matches: CAPTURE_IN_A_TWO_DIMENSIONAL_ARRAY + takeArray2Dep(array2DepOf(makeList())); + } + static class Outer2 { + class In {} + } + static class Dep2.@Nullable In> {} + static Dep2 dep2Of(T t) { + throw new RuntimeException(); + } + static void takeDep2(Dep2.In> d) {} + void captureInAnEnclosingTypeInBound() { + // BUG: Diagnostic matches: CAPTURE_IN_AN_ENCLOSING_TYPE + takeDep2(dep2Of(makeList())); + } + """); + } + + // The check views SubL as Base and compares the @Nullable bound of U, so it reports a false + // positive (#2206). There is a note naming the holder's own type parameter only where its bound + // prints as the compared bound does at every node, once the compared class's type parameters are + // replaced by the type arguments the holder's class passes to it. + // A subtype of the compared bound with the same nullness, such as @Nullable List for + // @Nullable Object, gets no note, so TopSub, whose bound TopNested hides the @Nullable type + // argument of Enclosing, gets none either (#2224). + @Test + public void aHolderNoteIsPrintedOnlyWhereItsBoundHasTheNullnessTheCheckCompared() { + assertMessages( + Map.ofEntries( + Map.entry( + "SUBCLASS_BOUND_IS_NON_NULL", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires List + source: SubL + ^ + target: Base> + ^^^^^^^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_INSIDE_A_LIST", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: SubW + ^ + target: Base> + ^^^^^^ + """), + Map.entry( + "BOUND_HOLDS_A_WILDCARD", + """ + incompatible nullability in type argument for T of Wild -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Wild + ^ + target: Wild> + ^^^^^^ + note: the unbounded wildcard ? in Wild has the upper bound of type parameter T of Wild, which is List (JLS 5.1.10) + """), + Map.entry( + "BOUND_HOLDS_AN_ARRAY", + """ + incompatible nullability in type argument for T of Arr -> upper bound of wildcard -> type argument for E of List -> component type -> type argument for E of List: source has @Nullable String where target requires String + source: Arr + ^ + target: Arr []>> + ^^^^^^ + note: the unbounded wildcard ? in Arr has the upper bound of type parameter T of Arr, which is List []> (JLS 5.1.10) + """), + Map.entry( + "BOUND_HOLDS_A_LOWER_BOUND", + """ + incompatible nullability in type argument for T of Low -> upper bound of wildcard -> type argument for E of List -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String + source: Low + ^ + target: Low> + ^^^^^^^^^^^^^^^^ + note: the unbounded wildcard ? in Low has the upper bound of type parameter T of Low, which is List (JLS 5.1.10) + """), + Map.entry( + "BOUND_HOLDS_AN_INNER_CLASS", + """ + incompatible nullability in type argument for T of In -> upper bound of wildcard -> enclosing type -> type argument for E of Outer: source has @Nullable String where target requires String + source: In + ^ + target: In.Inner> + ^^^^^^ + note: the unbounded wildcard ? in In has the upper bound of type parameter T of In, which is Test.Outer<@Nullable String>.Inner (JLS 5.1.10) + """), + Map.entry( + "BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_CLASS", + """ + incompatible nullability in type argument for U of Coll -> upper bound of wildcard -> type argument for V of Map: source has @Nullable String where target requires String + source: SubColl + ^ + target: Coll> + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_STATES_A_TYPE_ARGUMENT", + """ + incompatible nullability in type argument for U of Wide -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Narrow + ^ + target: Wide> + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableListSub + ^ + target: Base + ^^^^^^ + """), + Map.entry( + "SUBCLASS_TWO_LEVELS_DOWN_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableListSubSub + ^ + target: Base + ^^^^^^ + """), + Map.entry( + "SUPER_BOUNDED_IN_A_SUBCLASS_WHOSE_BOUND_IS_A_SUBTYPE", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: NullableListSub> + ^^^^^^^^^^^^^^^^^^^^^^^^^ + target: Base + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_IS_A_SUBCLASS_OF_AN_INNER_CLASS_BOUND", + """ + incompatible nullability in type argument for T of InnerBase -> upper bound of wildcard: source has InnerOuter.@Nullable Inner where target requires InnerOuter.Inner + source: InnerSub + ^ + target: InnerBase + ^^^^^^^^^^^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_DIFFERS_IN_A_NESTED_ANNOTATION", + """ + incompatible nullability in type argument for M of MapBase -> upper bound of wildcard: source has @Nullable Map<@Nullable String, String> where target requires Object + source: MapSub + ^ + target: MapBase + ^^^^^^ + """), + Map.entry( + "SUBCLASS_BOUND_IS_NULLABLE", + """ + incompatible nullability in type argument for U of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Sub + ^ + target: Base + ^^^^^^ + note: the unbounded wildcard ? in Sub has the upper bound of type parameter T of Sub, which is @Nullable Object (JLS 5.1.10) + """), + Map.entry( + "SUBCLASS_BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_BOUND", + """ + incompatible nullability in type argument for T of Holder -> upper bound of wildcard -> enclosing type -> type argument for X of Enclosing: source has @Nullable String where target requires String + source: TopSub + ^ + target: Holder.Nested> + ^^^^^^ + """)), + """ + static class Base {} + static class SubL> extends Base {} + static class SubW extends Base> {} + static class Sub extends Base {} + static void takeList(Base> b) {} + static void takeListOfNonNull(Base> b) {} + static void takeNonNull(Base b) {} + void subclassBoundIsNonNull(SubL s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_NON_NULL + takeList(s); + } + void subclassBoundInsideAList(SubW s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_INSIDE_A_LIST + takeListOfNonNull(s); + } + static class Wild> {} + void boundHoldsAWildcard(Wild w, Wild> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_A_WILDCARD + t = w; + } + static class Arr[]>> {} + void boundHoldsAnArray(Arr a, Arr[]>> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_AN_ARRAY + t = a; + } + static class Low> {} + void boundHoldsALowerBound(Low l, Low> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_A_LOWER_BOUND + t = l; + } + class Outer { + class Inner {} + } + static class In.Inner> {} + void boundHoldsAnInnerClass(In i, In.Inner> t) { + // BUG: Diagnostic matches: BOUND_HOLDS_AN_INNER_CLASS + t = i; + } + static class Reversed + extends HashMap {} + static class Coll> {} + static class SubColl> extends Coll {} + static void takeCollection(Coll> c) {} + void boundIsASubclassOfTheComparedClass(SubColl s) { + // BUG: Diagnostic matches: BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_CLASS + takeCollection(s); + } + static class Wide> {} + static class Narrow> extends Wide {} + static void takeWide(Wide> w) {} + void subclassBoundStatesATypeArgument(Narrow n) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_STATES_A_TYPE_ARGUMENT + takeWide(n); + } + void subclassBoundIsNullable(Sub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_NULLABLE + takeNonNull(s); + } + static class NullableListSub> extends Base {} + static class NullableListSubSub> extends NullableListSub {} + void subclassBoundIsASubtypeWithTheSameNullness(NullableListSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS + takeNonNull(s); + } + void subclassTwoLevelsDownBoundIsASubtypeWithTheSameNullness(NullableListSubSub s) { + // BUG: Diagnostic matches: SUBCLASS_TWO_LEVELS_DOWN_BOUND_IS_A_SUBTYPE_WITH_THE_SAME_NULLNESS + takeNonNull(s); + } + void superBoundedInASubclassWhoseBoundIsASubtype(NullableListSub> s) { + // BUG: Diagnostic matches: SUPER_BOUNDED_IN_A_SUBCLASS_WHOSE_BOUND_IS_A_SUBTYPE + takeNonNull(s); + } + static class InnerOuter { + class Inner {} + } + static class SubInnerOfOuter extends InnerOuter.Inner { + SubInnerOfOuter(InnerOuter o) { + o.super(); + } + } + static class InnerBase {} + static class InnerSub extends InnerBase {} + static void takeInnerBase(InnerBase b) {} + void subclassBoundIsASubclassOfAnInnerClassBound(InnerSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_A_SUBCLASS_OF_AN_INNER_CLASS_BOUND + takeInnerBase(s); + } + static class MapBase> {} + static class MapSub> extends MapBase {} + static void takeMapBase(MapBase b) {} + void subclassBoundDiffersInANestedAnnotation(MapSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_DIFFERS_IN_A_NESTED_ANNOTATION + takeMapBase(s); + } + static class Enclosing { + class Nested {} + } + static class TopNested extends Enclosing<@Nullable String>.Nested { + TopNested(Enclosing<@Nullable String> e) { + e.super(); + } + } + static class Holder.Nested> {} + static class TopSub extends Holder {} + void subclassBoundHasNoEnclosingType(TopSub s) { + // BUG: Diagnostic matches: SUBCLASS_BOUND_IS_A_SUBCLASS_OF_THE_COMPARED_BOUND + Holder.Nested> h = s; + } + """); + } + + @Test + public void aBoundSubstitutesOnlyTheTypeArgumentsThatAreNotWildcards() { + assertMessages( + Map.of( + "DEPENDS_ON_A_WILDCARD", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Dep + ^ + target: Dep> + ^^^^^^ + note: the unbounded wildcard ? in Dep<..., ?> has the upper bound of type parameter B of Dep, which is List (JLS 5.1.10) + """, + "DEPENDS_ON_ITSELF", + """ + incompatible nullability in type argument for T of Self -> upper bound of wildcard: source has @Nullable Comparable where target requires Comparable + source: Self + ^ + target: Self> + ^^^^^^^^^^^^^ + note: the unbounded wildcard ? in Self has the upper bound of type parameter T of Self, which is @Nullable Comparable (JLS 5.1.10) + """, + "DEPENDS_ON_A_WILDCARD_AND_A_STATED_ARGUMENT", + """ + incompatible nullability in type argument for B of Tri -> upper bound of wildcard -> type argument for K of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Tri + ^ + target: Tri> + ^^^^^^ + note: the unbounded wildcard ? in Tri<..., String, ?> has the upper bound of type parameter B of Tri, which is Map (JLS 5.1.10) + """, + "DEPENDS_ON_A_STATED_ARGUMENT", + """ + incompatible nullability in type argument for B of Dep -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Dep<@Nullable String, ?> + ^ + target: Dep<@Nullable String, ? extends List> + ^^^^^^ + note: the unbounded wildcard ? in Dep<@Nullable String, ?> has the upper bound of type parameter B of Dep, which is List<@Nullable String> (JLS 5.1.10) + """), + """ + static class Dep> {} + static class Self> {} + static class Tri> {} + static void takeDep(Dep> d) {} + static void takeSelf(Self> s) {} + static void takeTri(Tri> t) {} + static void takeStatedDep(Dep<@Nullable String, ? extends List> d) {} + void dependsOnAWildcard(Dep d) { + // BUG: Diagnostic matches: DEPENDS_ON_A_WILDCARD + takeDep(d); + } + void dependsOnItself(Self s) { + // BUG: Diagnostic matches: DEPENDS_ON_ITSELF + takeSelf(s); + } + void dependsOnAWildcardAndAStatedArgument(Tri t) { + // BUG: Diagnostic matches: DEPENDS_ON_A_WILDCARD_AND_A_STATED_ARGUMENT + takeTri(t); + } + void dependsOnAStatedArgument(Dep<@Nullable String, ?> d) { + // BUG: Diagnostic matches: DEPENDS_ON_A_STATED_ARGUMENT + takeStatedDep(d); + } + """); + } + + @Test + public void aWildcardInAnEnclosingTypeArgumentGetsANote() { + assertMessage( + """ + incompatible nullability in enclosing type -> type argument for T of Outer -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Outer.Inner + ^ + target: Outer.Inner + ^^^^^^ + note: the unbounded wildcard ? in Outer has the upper bound of type parameter T of Outer, which is @Nullable Object (JLS 5.1.10) + """, + """ + static class Outer { + class Inner {} + } + static void take(Outer.Inner inner) {} + void test(Outer.Inner inner) { + // BUG: Diagnostic matches: MESSAGE + take(inner); + } + """); + } +} 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..b4992d871e --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/PathTests.java @@ -0,0 +1,306 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * A {@code path:} line, and the first line of the message, name the position of a difference in the + * terms of the JLS: one step per type argument, wildcard bound, component type, or enclosing type, + * each type argument named by the type parameter it is for and the class that declares it. The + * position is the one the check rejects, so a nullable root or array is compared below its own + * nullness, and a captured source through its upper bound. + */ +public class PathTests extends MismatchMessageTestBase { + + @Test + public void pathNamesTheTypeParameterTheDeclarationDeclared() { + assertMessage( + """ + incompatible nullability in type argument for Failure of Result: source has @Nullable String where target requires String + source: Result + ^^^^^^^^^^^^^^^^ + target: Result + ^^^^^^ + """, + """ + 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 in type argument for E of List -> type argument for E of Collection -> type argument for E of List: source has @Nullable String where target requires String + source: List>> + ^^^^^^^^^^^^^^^^ + target: List>> + ^^^^^^ + """, + """ + static void take(List>> l) {} + void test(List>> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void pathKeepsTheEnclosingTypeApartFromTheInnerType() { + assertMessage( + """ + incompatible nullability in type argument for U of Inner: source has @Nullable Integer where target requires Integer + source: Outer.Inner<@Nullable Integer> + ^^^^^^^^^^^^^^^^^ + target: Outer.Inner + ^^^^^^^ + """, + """ + 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 in type argument for V of Map -> type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String + source: Map> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + target: Map> + ^^^^^^ ^^^^^^^ + 1 2 + \s + 1. path: type argument for V of Map -> type argument for K of Map + source: @Nullable String + target: String + \s + 2. path: type argument for V of Map -> type argument for V of Map + source: @Nullable Integer + target: Integer + """, + """ + static void take(Map> m) {} + void test(Map> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void mismatchesAtDifferentDepthsEachGetTheirOwnPath() { + assertMessage( + """ + incompatible nullability in type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String + source: Map<@Nullable String, List>> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^ + 1 2 + target: Map>> + ^^^^^^ ^^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map + source: @Nullable String + target: String + \s + 2. path: type argument for V of Map -> type argument for E of List -> upper bound of wildcard -> type argument for E of Collection + source: @Nullable Integer + target: Integer + """, + """ + static void take(Map>> m) {} + void test( + Map<@Nullable String, List>> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void pathReachesATypeArgumentOfAnArrayElement() { + assertMessage( + """ + incompatible nullability in component type -> type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String + source: List [] + ^^^^^^ + target: @Nullable List<@Nullable String> [] + ^^^^^^^^^^^^^^^^ + """, + """ + void test(List[] arr) { + // BUG: Diagnostic matches: MESSAGE + @Nullable List<@Nullable String>[] x = arr; + } + """); + } + + // The target line prints the dimensions innermost first, Integer @Nullable [] [] for the declared + // Integer[] @Nullable [], so it reads as the opposite nullness (#2201). + @Test + public void pathDescendsIntoEveryDimensionOfANestedArray() { + assertMessage( + """ + incompatible nullability in component type -> component type: source has @Nullable Integer where target requires Integer + source: @Nullable Integer [] [] + ^^^^^^^^^^^^^^^^^ + target: Integer @Nullable [] [] + ^^^^^^^ + """, + """ + void test(@Nullable Integer[][] src) { + // BUG: Diagnostic matches: MESSAGE + Integer[] @Nullable [] t = src; + } + """); + } + + @Test + public void pathDescendsIntoEveryDimensionOfAThreeDimensionalArray() { + assertMessage( + """ + incompatible nullability in component type -> component type -> component type: source has @Nullable Integer where target requires Integer + source: @Nullable Integer [] [] [] + ^^^^^^^^^^^^^^^^^ + target: Integer @Nullable [] [] [] + ^^^^^^^ + """, + """ + void test(@Nullable Integer[][][] src3) { + // BUG: Diagnostic matches: MESSAGE + Integer[][] @Nullable [] t = src3; + } + """); + } + + @Test + public void aNullableSourceIsComparedBelowItsOwnNullness() { + assertMessage( + """ + incompatible nullability in type argument for E of Collection -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: @Nullable List + ^ + target: Collection + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + """ + static void take(Collection c) {} + void test(@Nullable List l) { + if (l != null) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + } + """); + } + + @Test + public void aNullableTargetIsComparedBelowItsOwnNullness() { + assertMessage( + """ + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String + source: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: @Nullable List + ^^^^^^ + """, + """ + static void param(@Nullable List l) {} + void test(List<@Nullable String> x) { + // BUG: Diagnostic matches: MESSAGE + param(x); + } + """); + } + + @Test + public void pathNamesOnlyTheTypeArgumentTheCheckRejects() { + assertMessage( + """ + incompatible nullability in type argument for A of Pair: source has @Nullable String where target requires String + source: Pair<@Nullable String, Integer []> + ^^^^^^^^^^^^^^^^ + target: Pair + ^^^^^^ + """, + """ + static class Pair {} + static void take(Pair p) {} + void test(Pair<@Nullable String, Integer[]> p) { + // BUG: Diagnostic matches: MESSAGE + take(p); + } + """); + } + + @Test + public void aCapturedSourceIsComparedThroughItsUpperBound() { + assertMessage( + """ + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String + source: capture of ? extends List<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ + """, + """ + void test(List> wl) { + // BUG: Diagnostic matches: MESSAGE + List l = wl.get(0); + } + """); + } + + @Test + public void aCapturedArgumentIsComparedThroughItsUpperBound() { + assertMessage( + """ + incompatible nullability in type argument for E of List: source has @Nullable String where target requires String + source: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: List + ^^^^^^ + """, + """ + static void take(List l) {} + void test(List> wl) { + // BUG: Diagnostic matches: MESSAGE + take(wl.get(0)); + } + """); + } + + @Test + public void pathCrossesAWildcardLowerBound() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> lower bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has Object where target requires a supertype of @Nullable Object + source: List> + ^^^^^^ + target: List> + ^ + """, + """ + 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/SummaryAndNumberingTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java new file mode 100644 index 0000000000..99d16c5e9d --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/SummaryAndNumberingTests.java @@ -0,0 +1,233 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.Map; +import org.junit.Test; + +/** + * The first line of a generic nullability message names the position of the first difference, how + * many other positions differ, and the two types at the first one, so that it stands alone where a + * tool shows only that line. Where there are several, each gets a numbered entry, five at most, and + * a line after them counts the rest. A non-wildcard type argument must have the same nullability in + * the source and the target, 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 in type argument for A of Args -> upper bound of wildcard and 5 other differing positions: source has @Nullable Object where target requires Object + source: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + target: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for B of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + \s + 3. path: type argument for C of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + \s + 4. path: type argument for D of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + \s + 5. path: type argument for E of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + \s + and 1 more differing position, not listed + """, + """ + static class Args {} + static void take(Args args) {} + void test(Args args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """); + } + + @Test + public void listsFiveMismatchesWithoutSayingThereAreMore() { + assertMessage( + """ + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 4 other differing positions: source has @Nullable Object where target requires Object + source: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + target: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for B of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + \s + 3. path: type argument for C of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + \s + 4. path: type argument for D of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + \s + 5. path: type argument for E of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + """, + """ + static class Args {} + static void take(Args args) {} + void test(Args args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """); + } + + @Test + public void adjacentTypeArgumentsThatBothMismatchAreNumberedSideBySide() { + assertMessage( + """ + incompatible nullability in type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String + source: Map<@Nullable String, @Nullable String> + ^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map + source: @Nullable String + target: String + \s + 2. path: type argument for V of Map + source: @Nullable String + target: String + """, + """ + static void take(Map m) {} + void test(Map<@Nullable String, @Nullable String> m) { + // BUG: Diagnostic matches: MESSAGE + take(m); + } + """); + } + + @Test + public void + everyPositionWhereTheSourceIsLessNullableSaysTheTypeArgumentMustHaveTheSameNullness() { + assertMessages( + Map.of( + "ONLY", + """ + incompatible nullability in type argument for E of List: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String + source: List + ^^^^^^ + target: List<@Nullable String> + ^^^^^^^^^^^^^^^^ + """, + "SECOND", + """ + incompatible nullability in type argument for K of Map and 1 other differing position: source has @Nullable String where target requires String + source: Map<@Nullable String, String> + ^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 + target: Map + ^^^^^^ ^^^^^^^^^^^^^^^^ + 1 2 + \s + 1. path: type argument for K of Map + source: @Nullable String + target: String + \s + 2. path: type argument for V of Map + source: String + target: @Nullable String (a non-wildcard type argument must have the same nullability in source and target) + """), + """ + static void takeMap(Map m) {} + void only(List source) { + // BUG: Diagnostic matches: ONLY + List<@Nullable String> target = source; + target.hashCode(); + } + void second(Map<@Nullable String, String> m) { + // BUG: Diagnostic matches: SECOND + takeMap(m); + } + """); + } + + @Test + public void countsSeveralUnlistedMismatchesInThePlural() { + assertMessage( + """ + incompatible nullability in type argument for A of Args -> upper bound of wildcard and 6 other differing positions: source has @Nullable Object where target requires Object + source: Args + ^ ^ ^ ^ ^ + 1 2 3 4 5 + target: Args + ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 4 5 + \s + 1. path: type argument for A of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args has the upper bound of type parameter A of Args, which is @Nullable Object (JLS 5.1.10) + \s + 2. path: type argument for B of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ?, ..., ..., ..., ..., ...> has the upper bound of type parameter B of Args, which is @Nullable Object (JLS 5.1.10) + \s + 3. path: type argument for C of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ?, ..., ..., ..., ...> has the upper bound of type parameter C of Args, which is @Nullable Object (JLS 5.1.10) + \s + 4. path: type argument for D of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ?, ..., ..., ...> has the upper bound of type parameter D of Args, which is @Nullable Object (JLS 5.1.10) + \s + 5. path: type argument for E of Args -> upper bound of wildcard + source: @Nullable Object + target: Object + note: the unbounded wildcard ? in Args<..., ..., ..., ..., ?, ..., ...> has the upper bound of type parameter E of Args, which is @Nullable Object (JLS 5.1.10) + \s + and 2 more differing positions, not listed + """, + """ + static class Args {} + static void take(Args args) {} + void test(Args args) { + // BUG: Diagnostic matches: MESSAGE + take(args); + } + """); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.java new file mode 100644 index 0000000000..dcac7804c4 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TopLevelNullableTest.java @@ -0,0 +1,34 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import static com.google.common.truth.Truth.assertWithMessage; + +import java.util.Map; +import org.junit.Test; + +public class TopLevelNullableTest { + + @Test + public void aPrintedTypeIsNullableAtItsTopLevelOnlyWhereThePrinterPutsThatAnnotation() { + Map expected = + Map.ofEntries( + Map.entry("@Nullable String", true), + Map.entry("String", false), + Map.entry("List<@Nullable String>", false), + Map.entry("@Nullable List", true), + Map.entry("Outer.@Nullable Inner", true), + Map.entry("Outer.@Nullable Inner", true), + Map.entry("Outer.@Nullable Inner>", true), + Map.entry("Outer.@Nullable Middle.Inner", false), + Map.entry("Outer.Inner", false), + Map.entry("String @Nullable []", true), + Map.entry("String @Nullable [] []", false), + Map.entry("@Nullable String []", false), + Map.entry("Outer.@Nullable Inner []", false), + Map.entry("@Nullable String @Nullable []", true)); + expected.forEach( + (printed, nullable) -> + assertWithMessage("top-level @Nullable of %s", printed) + .that(MismatchMessageTestBase.isTopLevelNullable(printed)) + .isEqualTo(nullable)); + } +} diff --git a/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java new file mode 100644 index 0000000000..103cf657f4 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/TraversalCostTests.java @@ -0,0 +1,178 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import org.junit.Test; + +/** + * Building the message costs time linear in the bound graph the check walks, however many paths + * reach a shared wildcard bound. Each {@code L} bounds its type parameter by a pair of two + * {@code L}, so a walk that revisits a bound once per path takes time exponential in the + * depth, and the timeout of each test is far below what depth 24 takes then. + */ +public class TraversalCostTests extends MismatchMessageTestBase { + + @Test(timeout = 30_000) + public void aSharedBoundBesideTheMismatchIsWalkedOnce() { + assertMessage( + """ + incompatible nullability in type argument for A of P: source has @Nullable String where target requires String + source: P<@Nullable String, L24> + ^^^^^^^^^^^^^^^^ + target: P> + ^^^^^^ + """, + """ + interface P {} + interface L0 {} + interface L1, L0>> {} + interface L2, L1>> {} + interface L3, L2>> {} + interface L4, L3>> {} + interface L5, L4>> {} + interface L6, L5>> {} + interface L7, L6>> {} + interface L8, L7>> {} + interface L9, L8>> {} + interface L10, L9>> {} + interface L11, L10>> {} + interface L12, L11>> {} + interface L13, L12>> {} + interface L14, L13>> {} + interface L15, L14>> {} + interface L16, L15>> {} + interface L17, L16>> {} + interface L18, L17>> {} + interface L19, L18>> {} + interface L20, L19>> {} + interface L21, L20>> {} + interface L22, L21>> {} + interface L23, L22>> {} + interface L24, L23>> {} + static P<@Nullable String, L24> get() { + throw new RuntimeException(); + } + void test() { + // BUG: Diagnostic matches: MESSAGE + P> x = get(); + } + """); + } + + @Test(timeout = 30_000) + public void aSharedBoundBesideANestedMismatchIsWalkedOnce() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> type argument for B of Box: source has @Nullable String where target requires String + source: List, @Nullable String>> + ^^^^^^^^^^^^^^^^ + target: List, String>> + ^^^^^^ + """, + """ + interface P {} + interface L0 {} + interface L1, L0>> {} + interface L2, L1>> {} + interface L3, L2>> {} + interface L4, L3>> {} + interface L5, L4>> {} + interface L6, L5>> {} + interface L7, L6>> {} + interface L8, L7>> {} + interface L9, L8>> {} + interface L10, L9>> {} + interface L11, L10>> {} + interface L12, L11>> {} + interface L13, L12>> {} + interface L14, L13>> {} + interface L15, L14>> {} + interface L16, L15>> {} + interface L17, L16>> {} + interface L18, L17>> {} + interface L19, L18>> {} + interface L20, L19>> {} + interface L21, L20>> {} + interface L22, L21>> {} + interface L23, L22>> {} + interface L24, L23>> {} + static class Box {} + void test(List, @Nullable String>> l) { + // BUG: Diagnostic matches: MESSAGE + List, String>> x = l; + } + """); + } + + // Each L passes its X on to both L in its bound, so the two sides differ at every level + // and no level shares a bound object with the other side. + @Test(timeout = 30_000) + public void aRejectedComparisonReachedAlongManyPathsIsWalkedOnce() { + assertMessage( + """ + incompatible nullability in type argument for X of L24 and 94 other differing positions: source has @Nullable String where target requires String + source: L24<@Nullable String, ?> + ^^^^^^^^^^^^^^^^ ^ + 1 2,3,4,5 + target: L24 + ^^^^^^ ^ + 1 2,3,4,5 + \s + 1. path: type argument for X of L24 + source: @Nullable String + target: String + \s + 2. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L23 + source: @Nullable String + target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) + \s + 3. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L22 + source: @Nullable String + target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) + \s + 4. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L22 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L21 + source: @Nullable String + target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) + \s + 5. path: type argument for T of L24 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L23 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L22 -> upper bound of wildcard -> type argument for A of P -> type argument for T of L21 -> upper bound of wildcard -> type argument for A of P -> type argument for X of L20 + source: @Nullable String + target: String + note: the unbounded wildcard ? in L24<@Nullable String, ?> has the upper bound of type parameter T of L24, which is P, L23<@Nullable String, ?>> (JLS 5.1.10) + \s + and 90 more differing positions, not listed + """, + """ + interface P {} + interface L0 {} + interface L1, L0>> {} + interface L2, L1>> {} + interface L3, L2>> {} + interface L4, L3>> {} + interface L5, L4>> {} + interface L6, L5>> {} + interface L7, L6>> {} + interface L8, L7>> {} + interface L9, L8>> {} + interface L10, L9>> {} + interface L11, L10>> {} + interface L12, L11>> {} + interface L13, L12>> {} + interface L14, L13>> {} + interface L15, L14>> {} + interface L16, L15>> {} + interface L17, L16>> {} + interface L18, L17>> {} + interface L19, L18>> {} + interface L20, L19>> {} + interface L21, L20>> {} + interface L22, L21>> {} + interface L23, L22>> {} + interface L24, L23>> {} + void test(L24<@Nullable String, ?> l) { + // BUG: Diagnostic matches: MESSAGE + L24 x = l; + } + """); + } +} 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..43a55e4728 --- /dev/null +++ b/nullaway/src/test/java/com/uber/nullaway/jspecify/mismatchmessage/ViewedSourceTests.java @@ -0,0 +1,929 @@ +package com.uber.nullaway.jspecify.mismatchmessage; + +import java.util.Map; +import org.junit.Test; + +/** + * Where the check views the source as a supertype of its own class, the one the target names, 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 source itself + * is viewed as a supertype and the node at fault is not in the written type, the message prints the + * view on a {@code source supertype:} line and draws the source carets under it. + */ +public class ViewedSourceTests extends MismatchMessageTestBase { + + @Test + public void aCarriedOverNodeInsideAWildcardBoundIsMarkedOnTheWrittenSource() { + assertMessage( + """ + incompatible nullability in type argument for T of Base -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Sub> + ^^^^^^^^^^^^^^^^ + target: 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 aCarriedOverNodeInsideAnArrayElementIsMarkedOnTheWrittenSource() { + assertMessage( + """ + incompatible nullability in type argument for T of Base -> component type: source has @Nullable String where target requires String + source: Sub<@Nullable String []> + ^^^^^^^^^^^^^^^^ + target: Base + ^^^^^^ + """, + """ + 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 in type argument for T of Base -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Sub + ^^^^^^^^^^^^ + target: Base + ^^^^^^ + note: capture of ? is the captured type argument for T of Sub, whose upper bound is @Nullable Object (JLS 5.1.10) + """, + """ + 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 in type argument for T of Base -> type argument for E of List: source has @Nullable String where target requires String + source: Sub + source supertype: Base> + ^^^^^^^^^^^^^^^^ + target: 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 + aTypeTheSubclassDeclarationWritesIsMarkedOnTheViewedSourceEvenWhereTheReaderWroteIt() { + assertMessages( + Map.of( + "SELF", + """ + incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullability in source and target; source has Sub where target requires @Nullable Sub + source: Sub + source supertype: Base + ^^^ + target: Base<@Nullable Sub> + ^^^^^^^^^^^^^ + """, + "ARGUMENT", + """ + incompatible nullability in type argument for T of Base: a non-wildcard type argument must have the same nullability in source and target; source has Sub where target requires @Nullable Sub + source: Holder + source supertype: Base + ^^^ + target: Base<@Nullable Sub> + ^^^^^^^^^^^^^ + """), + """ + interface Base {} + static final class Sub implements Base {} + static final class Holder implements Base {} + static void take(Base<@Nullable Sub> b) {} + void self(Sub s) { + // BUG: Diagnostic matches: SELF + take(s); + } + void argument(Holder h) { + // BUG: Diagnostic matches: ARGUMENT + take(h); + } + """); + } + + @Test + public void anArrayTheSubclassDeclarationWritesIsFollowedIntoItsElement() { + assertMessages( + Map.of( + "WRITTEN_ELEMENT", + """ + incompatible nullability in type argument for T of Box -> component type: source has @Nullable String where target requires String + source: Strings + source supertype: Box<@Nullable String []> + ^^^^^^^^^^^^^^^^ + target: Box + ^^^^^^ + """, + "PASSED_ELEMENT", + """ + incompatible nullability in type argument for T of Box -> component type: source has @Nullable String where target requires String + source: Elements<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Box + ^^^^^^ + """), + """ + interface Box {} + static final class Strings implements Box<@Nullable String[]> {} + static final class Elements implements Box {} + static void take(Box b) {} + void written(Strings s) { + // BUG: Diagnostic matches: WRITTEN_ELEMENT + take(s); + } + void passed(Elements<@Nullable String> e) { + // BUG: Diagnostic matches: PASSED_ELEMENT + take(e); + } + """); + } + + @Test + public void aViewNestedInADeclaredSupertypeStillReachesTheWrittenArgument() { + assertMessages( + Map.of( + "PASSED", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ + """, + "BELOW_ANNOTATED", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> type argument for E of List: source has @Nullable String where target requires String + source: Annotated> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "VIEWED_BELOW_ANNOTATED", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Annotated> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "WRITTEN", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: Strings + source supertype: Base> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ + """), + """ + interface Base {} + static final class Sub implements Base> {} + static final class Strings implements Base> {} + static void take(Base> b) {} + void passed(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: PASSED + take(s); + } + static final class Annotated implements Base> {} + static void takeNested(Base>> b) {} + void belowAnnotated(Annotated> a) { + // BUG: Diagnostic matches: BELOW_ANNOTATED + takeNested(a); + } + static void takeViewed(Base>> b) {} + void viewedBelowAnnotated(Annotated> a) { + // BUG: Diagnostic matches: VIEWED_BELOW_ANNOTATED + takeViewed(a); + } + void written(Strings s) { + // BUG: Diagnostic matches: WRITTEN + take(s); + } + """); + } + + @Test + public void aTypeVariableBelowAWildcardBoundOfTheDeclaredSupertypeIsMarkedAtTheWrittenArgument() { + assertMessages( + Map.of( + "UPPER_BOUND", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List -> upper bound of wildcard -> type argument for X of Box: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "LOWER_BOUND", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List -> lower bound of wildcard -> type argument for X of Box: source has @Nullable String where target requires String + source: SuperSub<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """, + "WRITTEN", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List -> upper bound of wildcard -> type argument for X of Box: source has @Nullable String where target requires String + source: Strings + source supertype: Base>> + ^^^^^^^^^^^^^^^^ + target: Base>> + ^^^^^^ + """), + """ + static class Base {} + static class Box {} + static class Sub extends Base>> {} + static class SuperSub extends Base>> {} + static class Strings extends Base>> {} + static void take(Base>> b) {} + static void takeSuper(Base>> b) {} + void upperBound(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: UPPER_BOUND + take(s); + } + void lowerBound(SuperSub<@Nullable String> s) { + // BUG: Diagnostic matches: LOWER_BOUND + takeSuper(s); + } + void written(Strings s) { + // BUG: Diagnostic matches: WRITTEN + take(s); + } + """); + } + + // The target line of an intersection has no caret under either differing position (#2202). + @Test + public void eachComponentOfAnIntersectionTargetIsComparedUnderItsOwnView() { + assertMessage( + """ + incompatible nullability in type argument for T of A and 1 other differing position: source has @Nullable String where target requires String + source: B + target: A & D + \s + 1. path: type argument for T of A + source: @Nullable String + target: String + \s + 2. path: type argument for T of D + source: @Nullable String + target: String + """, + """ + interface A {} + interface D {} + static class B implements A<@Nullable String>, D<@Nullable String> {} + static void test(Object o) { + var x = (A & D) o; + // BUG: Diagnostic matches: MESSAGE + x = new B(); + } + """); + } + + // The target lines of INTERSECTION and INTERSECTION_REVERSED have no caret (#2202). + @Test + public void aDifferenceIsMarkedOnTheWrittenSourceWhereItHoldsTheNodeAndOnTheSupertypeOtherwise() { + assertMessages( + Map.of( + "SPLIT", + """ + incompatible nullability in type argument for A of Pair and 1 other differing position: source has @Nullable String where target requires String + source: Sub<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + source supertype: Pair<@Nullable String, List<@Nullable String>> + ^^^^^^^^^^^^^^^^ + 2 + target: Pair> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Pair + source: @Nullable String + target: String + \s + 2. path: type argument for B of Pair -> type argument for E of List + source: @Nullable String + target: String + """, + "SPLIT_ONE_LEVEL_DOWN", + """ + incompatible nullability in type argument for A of Pair -> type argument for E of List and 1 other differing position: source has @Nullable String where target requires String + source: ListSub<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + source supertype: Pair, List<@Nullable String>> + ^^^^^^^^^^^^^^^^ + 2 + target: Pair, List> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Pair -> type argument for E of List + source: @Nullable String + target: String + \s + 2. path: type argument for B of Pair -> type argument for E of List + source: @Nullable String + target: String + """, + "INTERSECTION", + """ + incompatible nullability in type argument for T of A and 1 other differing position: source has @Nullable String where target requires String + source: B<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + source supertype: D<@Nullable String> + ^^^^^^^^^^^^^^^^ + 2 + target: A & D + \s + 1. path: type argument for T of A + source: @Nullable String + target: String + \s + 2. path: type argument for T of D + source: @Nullable String + target: String + """, + "INTERSECTION_REVERSED", + """ + incompatible nullability in type argument for T of D and 1 other differing position: source has @Nullable String where target requires String + source: C<@Nullable String> + ^^^^^^^^^^^^^^^^ + 2 + source supertype: D<@Nullable String> + ^^^^^^^^^^^^^^^^ + 1 + target: D & A + \s + 1. path: type argument for T of D + source: @Nullable String + target: String + \s + 2. path: type argument for T of A + source: @Nullable String + target: String + """), + """ + interface Pair {} + static class Sub implements Pair> {} + static void takePair(Pair> p) {} + void split(Sub<@Nullable String> s) { + // BUG: Diagnostic matches: SPLIT + takePair(s); + } + static class ListSub + implements Pair, List<@Nullable String>> {} + static void takeListPair(Pair, List> p) {} + void splitOneLevelDown(ListSub<@Nullable String> s) { + // BUG: Diagnostic matches: SPLIT_ONE_LEVEL_DOWN + takeListPair(s); + } + interface A {} + interface D {} + static class B implements A, D<@Nullable String> {} + static class C implements D<@Nullable String>, A {} + static void intersection(Object o) { + var x = (A & D) o; + // BUG: Diagnostic matches: INTERSECTION + x = new B<@Nullable String>(); + } + static void intersectionReversed(Object o) { + var x = (D & A) o; + // BUG: Diagnostic matches: INTERSECTION_REVERSED + x = new C<@Nullable String>(); + } + """); + } + + // The written source is the capture of ? extends A<@Nullable String>, while the comparison steps + // into B; the type argument of A is not the one compared, so the source line gets no caret. + @Test + public void theTypeArgumentOfAnotherIntersectionComponentIsNotMarked() { + assertMessage( + """ + incompatible nullability in type argument for E of B: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String + source: capture of ? extends A<@Nullable String> + source supertype: B + ^^^^^^ + target: B<@Nullable String> + ^^^^^^^^^^^^^^^^ + """, + """ + interface A { E a(); } + interface B { E b(); } + interface Holder & B> { + T get(); + } + interface Factory { + Holder> fromA(); + } + static void test(Factory factory) { + // BUG: Diagnostic matches: MESSAGE + B<@Nullable String> result = factory.fromA().get(); + } + """); + } + + // Below the root of the type, the source lines of the BELOW_ROOT keys get no caret and no + // source supertype line (#2197). + // The check compares the bound of BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS and + // BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS as Holder declares it, where NonNullHolder + // declares a non-null one, and reports a false positive (#2206). + @Test + public void aWildcardFromTheSubclassDeclarationIsNamedOnlyWhereALinePrintsIt() { + assertMessages( + Map.of( + "LIST", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: ListSub + source supertype: Base> + ^ + target: Base> + ^^^^^^ + note: the unbounded wildcard ? in List has the upper bound of type parameter E of List, which is @Nullable Object (JLS 5.1.10) + """, + "MAP", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for V of Map -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: MapSub + source supertype: Base> + ^ + target: Base> + ^^^^^^ + note: the unbounded wildcard ? in Map has the upper bound of type parameter V of Map, which is @Nullable Object (JLS 5.1.10) + """, + "BELOW_ROOT", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: List + target: List>> + ^^^^^^ + note: the unbounded wildcard ? in the source has the upper bound @Nullable Object (JLS 5.1.10) + """, + "BELOW_THE_IMPLICIT_BOUND", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: HolderSub + source supertype: Base> + ^ + target: Base>> + ^^^^^^ + note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable String> (JLS 5.1.10) + """, + "BELOW_THE_IMPLICIT_BOUND_INSIDE_A_MAP", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for V of Map -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: MapOfHolderSub + source supertype: Base>> + ^ + target: Base>>> + ^^^^^^ + note: the unbounded wildcard ? in Holder has the upper bound of type parameter E of Holder, which is List<@Nullable String> (JLS 5.1.10) + """, + "BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: NonNullHolderSub + source supertype: Base> + ^ + target: Base>> + ^^^^^^ + """, + "BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: List + target: List>>> + ^^^^^^ + note: the unbounded wildcard ? in the source has the upper bound List<@Nullable String> (JLS 5.1.10) + """, + "BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS", + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for B of Base -> upper bound of wildcard -> type argument for E of Holder -> upper bound of wildcard -> type argument for E of List: source has @Nullable String where target requires String + source: List + target: List>>> + ^^^^^^ + """), + """ + static class Base {} + static class ListSub extends Base> {} + static class MapSub extends Base> {} + static void take(Base> b) {} + static void takeMap(Base> b) {} + static void takeList(List>> l) {} + void list(ListSub s) { + // BUG: Diagnostic matches: LIST + take(s); + } + void map(MapSub s) { + // BUG: Diagnostic matches: MAP + takeMap(s); + } + void belowRoot(List l) { + // BUG: Diagnostic matches: BELOW_ROOT + takeList(l); + } + static class Holder> {} + static class HolderSub extends Base> {} + static void takeHolder(Base>> b) {} + void belowTheImplicitBound(HolderSub s) { + // BUG: Diagnostic matches: BELOW_THE_IMPLICIT_BOUND + takeHolder(s); + } + static class MapOfHolderSub extends Base>> {} + static void takeMapOfHolder( + Base>>> b) {} + void belowTheImplicitBoundInsideAMap(MapOfHolderSub s) { + // BUG: Diagnostic matches: BELOW_THE_IMPLICIT_BOUND_INSIDE_A_MAP + takeMapOfHolder(s); + } + static class NonNullHolder> extends Holder {} + static class NonNullHolderSub extends Base> {} + void belowTheImplicitBoundOfASubclass(NonNullHolderSub s) { + // BUG: Diagnostic matches: BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS + takeHolder(s); + } + static void takeListOfHolder(List>>> l) {} + void belowRootBelowTheImplicitBound(List l) { + // BUG: Diagnostic matches: BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND + takeListOfHolder(l); + } + void belowRootBelowTheImplicitBoundOfASubclass(List l) { + // BUG: Diagnostic matches: BELOW_ROOT_BELOW_THE_IMPLICIT_BOUND_OF_A_SUBCLASS + takeListOfHolder(l); + } + """); + } + + @Test + public void aPathAcrossAViewReachesIntoWhateverTheSubclassPassed() { + assertMessage( + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard: source has @Nullable Object where target requires Object + source: Indirect + ^ + target: Base> + ^^^^^^ + note: the unbounded wildcard ? in Indirect has the upper bound of type parameter X of Indirect, which is @Nullable Object (JLS 5.1.10) + """, + """ + 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 in type argument for T of Result: source has @Nullable String where target requires String + source: Result<@Nullable String> + ^^^^^^^^^^^^^^^^ + target: Result + ^^^^^^ + """)) + .addSourceLines( + "Test.java", + nullMarkedClass( + """ + static void take(a.Result r) {} + void test(b.Result<@Nullable String> r) { + // BUG: Diagnostic matches: MESSAGE + take(r); + } + """)) + .doTest(); + } + + @Test + public void aReorderingSubclassIsMarkedAtTheArgumentItPassesOn() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for A of Pair: source has @Nullable String where target requires String + source: List> + ^^^^^^^^^^^^^^^^ + target: List> + ^^^^^^ + """, + """ + static class Pair {} + static class Swap extends Pair {} + static void take(List> l) {} + void test(List> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void aReorderingSubclassInsideAnArrayIsMarkedAtTheArgumentItPassesOn() { + assertMessage( + """ + incompatible nullability in component type -> type argument for A of Pair: source has @Nullable String where target requires String + source: Swap [] + ^^^^^^^^^^^^^^^^ + target: Pair [] + ^^^^^^ + """, + """ + static class Pair {} + static class Swap extends Pair {} + static void take(Pair[] a) {} + void test(Swap[] a) { + // BUG: Diagnostic matches: MESSAGE + take(a); + } + """); + } + + @Test + public void aReorderingSubclassTwoLevelsDownIsMarkedAtTheArgumentItPassesOn() { + assertMessage( + """ + incompatible nullability in type argument for E of List -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for A of Pair: source has @Nullable String where target requires String + source: List>> + ^^^^^^^^^^^^^^^^ + target: List>> + ^^^^^^ + """, + """ + static class Pair {} + static class Swap extends Pair {} + static void take(List>> l) {} + void test(List>> l) { + // BUG: Diagnostic matches: MESSAGE + take(l); + } + """); + } + + @Test + public void anEnclosingTypeArgumentOfASubclassIsMarkedOnTheWrittenSource() { + assertMessage( + """ + incompatible nullability in enclosing type -> type argument for T of Outer: source has @Nullable String where target requires String + source: Outer<@Nullable String>.SubInner + ^^^^^^^^^^^^^^^^ + target: Outer.Inner + ^^^^^^ + """, + """ + static class Outer { + class Inner {} + class SubInner extends Inner {} + } + static void take(Outer.Inner i) {} + void test(Outer<@Nullable String>.SubInner s) { + // BUG: Diagnostic matches: MESSAGE + take(s); + } + """); + } + + @Test + public void eachOfTwoNestedNodesTheViewMarksGetsItsOwnCaretRow() { + assertMessages( + Map.of( + "NESTED_PAIR", + """ + incompatible nullability in type argument for A of Pair -> upper bound of wildcard and 1 other differing position: source has @Nullable List<@Nullable String> where target requires List<@Nullable String> + source: Same<@Nullable List<@Nullable String>> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 + ^^^^^^^^^^^^^^^^ + 2 + target: Pair, ? extends @Nullable List> + ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Pair -> upper bound of wildcard + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 2. path: type argument for B of Pair -> upper bound of wildcard -> type argument for E of List + source: @Nullable String + target: String + """, + "SIBLING_AFTER_A_NESTED_PAIR", + """ + incompatible nullability in type argument for A of Triple -> upper bound of wildcard and 2 other differing positions: source has @Nullable List<@Nullable String> where target requires List<@Nullable String> + source: SameThenOther<@Nullable List<@Nullable String>, @Nullable String> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^ + 1 3 + ^^^^^^^^^^^^^^^^ + 2 + target: Triple, ? extends @Nullable List, String> + ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ ^^^^^^ + 1 2 3 + \s + 1. path: type argument for A of Triple -> upper bound of wildcard + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 2. path: type argument for B of Triple -> upper bound of wildcard -> type argument for E of List + source: @Nullable String + target: String + \s + 3. path: type argument for C of Triple + source: @Nullable String + target: String + """, + "THREE_DEEP", + """ + incompatible nullability in type argument for A of Triple -> upper bound of wildcard and 2 other differing positions: source has @Nullable List<@Nullable List<@Nullable String>> where target requires List<@Nullable List<@Nullable String>> + source: Thrice<@Nullable List<@Nullable List<@Nullable String>>> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 1 + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + 2 + ^^^^^^^^^^^^^^^^ + 3 + target: Triple>, ? extends @Nullable List>, ? extends @Nullable List<@Nullable List>> + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^ + 1 2 3 + \s + 1. path: type argument for A of Triple -> upper bound of wildcard + source: @Nullable List<@Nullable List<@Nullable String>> + target: List<@Nullable List<@Nullable String>> + \s + 2. path: type argument for B of Triple -> upper bound of wildcard -> type argument for E of List + source: @Nullable List<@Nullable String> + target: List<@Nullable String> + \s + 3. path: type argument for C of Triple -> upper bound of wildcard -> type argument for E of List -> type argument for E of List + source: @Nullable String + target: String + """), + """ + interface Pair {} + interface Triple {} + interface Same extends Pair {} + interface SameThenOther extends Triple {} + interface Thrice extends Triple {} + static void takePair(Pair, ? extends @Nullable List> p) {} + static void takeTriple(Triple, ? extends @Nullable List, String> t) {} + static void takeThrice(Triple>, ? extends @Nullable List>, ? extends @Nullable List<@Nullable List>> t) {} + void nestedPair(Same<@Nullable List<@Nullable String>> s) { + // BUG: Diagnostic matches: NESTED_PAIR + takePair(s); + } + void siblingAfterANestedPair(SameThenOther<@Nullable List<@Nullable String>, @Nullable String> s) { + // BUG: Diagnostic matches: SIBLING_AFTER_A_NESTED_PAIR + takeTriple(s); + } + void threeDeep(Thrice<@Nullable List<@Nullable List<@Nullable String>>> s) { + // BUG: Diagnostic matches: THREE_DEEP + takeThrice(s); + } + """); + } + + @Test + public void aSupertypeLineIsPrintedOnlyWhereItCarriesACaret() { + assertMessages( + Map.of( + "WRITTEN_NODE_AND_A_NODE_OF_A_NESTED_CLASS", + """ + incompatible nullability in type argument for A of Base -> type argument for E of List and 1 other differing position: source has @Nullable String where target requires String + source: Sub> + ^^^^^^^^^^^^^^^^ + 1 + target: Base, ? extends Inner>> + ^^^^^^ ^^^^^^ + 1 2 + \s + 1. path: type argument for A of Base -> type argument for E of List + source: @Nullable String + target: String + \s + 2. path: type argument for B of Base -> upper bound of wildcard -> type argument for Y of Inner -> type argument for E of List + source: @Nullable String + target: String + """, + "ONLY_A_NODE_OF_A_NESTED_CLASS", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for Y of Inner -> type argument for E of List: source has @Nullable String where target requires String + source: Sub> + target: Base>> + ^^^^^^ + """, + "ONLY_A_NODE_OF_A_NESTED_CLASS_BELOW_A_LIST", + """ + incompatible nullability in type argument for B of Base -> upper bound of wildcard -> type argument for E of List -> upper bound of wildcard -> type argument for Y of Inner -> type argument for E of List: source has @Nullable String where target requires String + source: ListSub + target: Base>>> + ^^^^^^ + """, + "A_NODE_OF_THE_SUBCLASS_DECLARATION", + """ + incompatible nullability in type argument for B of Base -> type argument for E of List: source has @Nullable String where target requires String + source: Declared + source supertype: Base> + ^^^^^^^^^^^^^^^^ + target: Base> + ^^^^^^ + """), + """ + static class Base {} + static class Inner {} + static class SubInner extends Inner> {} + static class Sub extends Base {} + static void take(Base, ? extends Inner>> b) {} + static void takeOne(Base>> b) {} + void writtenNodeAndANodeOfANestedClass(Sub> s) { + // BUG: Diagnostic matches: WRITTEN_NODE_AND_A_NODE_OF_A_NESTED_CLASS + take(s); + } + void onlyANodeOfANestedClass(Sub> s) { + // BUG: Diagnostic matches: ONLY_A_NODE_OF_A_NESTED_CLASS + takeOne(s); + } + static class ListSub extends Base> {} + static void takeList(Base>>> b) {} + void onlyANodeOfANestedClassBelowAList(ListSub s) { + // BUG: Diagnostic matches: ONLY_A_NODE_OF_A_NESTED_CLASS_BELOW_A_LIST + takeList(s); + } + static class Declared extends Base> {} + static void takeDeclared(Base> b) {} + void aNodeOfTheSubclassDeclaration(Declared d) { + // BUG: Diagnostic matches: A_NODE_OF_THE_SUBCLASS_DECLARATION + takeDeclared(d); + } + """); + } +} diff --git a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java index eb3fd45924..3dec5d892a 100644 --- a/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java +++ b/test-library-models/src/test/java/com/uber/nullaway/CustomLibraryModelsTests.java @@ -611,7 +611,7 @@ public void deeplyNestedTypeAnnot() { @NullMarked public class Test { void testPositive(NestedAnnots> p) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullability in source and target; source has String where target requires @Nullable String NestedAnnots.deeplyNested(p); } void testNegative(NestedAnnots> p) { @@ -638,7 +638,7 @@ public void nestedArray1() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> component type -> type argument for T of NestedAnnots: source has @Nullable String where target requires String NestedAnnots[]> unused = NestedAnnots.nestedArray1(); } void testNegative() { @@ -665,7 +665,7 @@ public void nestedArray2() { @NullMarked public class Test { void testPositive() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: source has String @Nullable [] where target requires String [] NestedAnnots unused = NestedAnnots.nestedArray2(); } void testNegative() { @@ -692,11 +692,11 @@ public void nestedWildcards() { @NullMarked public class Test { void testUpper(NestedAnnots<@Nullable String> t) { - // BUG: Diagnostic contains: incompatible types: NestedAnnots<@Nullable String> cannot be converted to NestedAnnots + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String NestedAnnots.wildcardUpper(t); } void testLower(NestedAnnots t) { - // BUG: Diagnostic contains: incompatible types: NestedAnnots cannot be converted to NestedAnnots + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> lower bound of wildcard: source has String where target requires a supertype of @Nullable String NestedAnnots.wildcardLower(t); } } @@ -725,7 +725,7 @@ NestedAnnots testDirect( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.wildcardUpperTypeVariable(); } @@ -734,7 +734,7 @@ NestedAnnots testWithSelf( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String return receiver.self().wildcardUpperTypeVariable(); } @@ -745,7 +745,7 @@ NestedAnnots testWithVar( // should reject since return type of wildcardUpperTypeVariable // is modeled to be NestedAnnots, which // here is incompatible with the return type NestedAnnots - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots -> upper bound of wildcard: source has @Nullable String where target requires String return foo.wildcardUpperTypeVariable(); } @@ -771,7 +771,7 @@ public void nestedAnnotationsOnUnboundedWildcardBounds() { public class Test { UnboundWildcards testLiteral() { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of UnboundWildcards -> upper bound of wildcard: source has @Nullable Object where target requires Object return UnboundWildcards.literalWildcard(); } @@ -781,7 +781,7 @@ UnboundWildcards testLiteral() { UnboundWildcards testCaptured( UnboundWildcards receiver) { - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of UnboundWildcards -> upper bound of wildcard: source has @Nullable Object where target requires Object return receiver.self().typeVariable(); } @@ -811,9 +811,9 @@ public void multipleArgs() { public class Test { void testPositive() { NestedAnnots.multipleArgs( - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: source has @Nullable String where target requires String new NestedAnnots<@Nullable String>(), - // BUG: Diagnostic contains: incompatible types + // BUG: Diagnostic contains: incompatible nullability in type argument for T of NestedAnnots: a non-wildcard type argument must have the same nullability in source and target; source has Integer where target requires @Nullable Integer new NestedAnnots()); } void testNegative() {